51
1 2005 JavaOne SM Conference | Session TS-5210 Strategies for Securing Java™ Technology Code Mark Lambert Jtest™ Product Specialist Parasoft www.parasoft.com TS-5210

Strategies for Securing Java™ Technology Code · 2005 JavaOneSM Conference | Session TS-5210 1 Strategies for Securing Java™ Technology Code Mark Lambert Jtest™ Product Specialist

  • Upload
    ngohanh

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

12005 JavaOneSM Conference | Session TS-5210

Strategies for Securing Java™ Technology CodeMark LambertJtest™ Product SpecialistParasoftwww.parasoft.comTS-5210

2005 JavaOneSM Conference | Session TS-5210 | 2

Learn how to develop secure Java technology-based applications and avoid un-authorized access to privileged data

A strategy for securing Java code

Guidelines for Securing Java Technology Code

2005 JavaOneSM Conference | Session TS-5210 | 3

Agenda

IntroductionApplication SecuritySecurity Misconceptions

Implementing a Secure ApplicationThree Strategies

Using Coding GuidelinesCoding DefensivelyExpose and Correct Bugs

Penetration TestingImplementing a Security PolicyConclusion

2005 JavaOneSM Conference | Session TS-5210 | 4

AgendaIntroduction

Application SecuritySecurity Misconceptions

Implementing a Secure ApplicationThree Strategies

Using Coding GuidelinesCoding DefensivelyExpose and Correct Bugs

Penetration TestingImplementing a Security PolicyConclusion

2005 JavaOneSM Conference | Session TS-5210 | 5

What is application security?Introduction

• Application Security != Network Security• Applications provide access to data and

resources• Applications are the “Drawbridge” to the

Enterprise Network• Applications must defend against threats

2005 JavaOneSM Conference | Session TS-5210 | 6

Security misconceptionsIntroduction

• There is no problem• Until the application is compromised

• Runtime errors are not important• Until they expose internal information• Until they consume resources

• Penetration testing is the solution• Complex, time consuming, resource intensive

• Web services are not vulnerable• Often poorly tested and rarely security tested

2005 JavaOneSM Conference | Session TS-5210 | 7

Applications are the culpritIntroduction

• Gartner• 75% hacks happen at the application level

• NIST• 92% vulnerabilities are at the application level

• Theo de Raadt, OpenBSD• “…probably 95% of security problems that happen in

software are low-level programmer errors.”

2005 JavaOneSM Conference | Session TS-5210 | 8

Why is it a challenge?Introduction

• High priority, high visibility• Recent high profile security breaches• Compliance• Not serious until litigation

• Challenges for managers• Cost• Existing code• Education gap

• Web applications/services easy targets

2005 JavaOneSM Conference | Session TS-5210 | 9

What needs to be addressed?Introduction

• Establish responsibility• According to Gartner…

• “Developer is three times more likely than System Administrator to be culprit”

• Are SysAdmins security aware?• Education gap: developers, architects

• Don’t outsource the problem!• “Ethical hackers”• Treating the symptoms• Don’t detect vulnerabilities, prevent them

2005 JavaOneSM Conference | Session TS-5210 | 10

Security issues and prioritiesSo What Is Important?

• Protecting sensitive data• Information integrity• Authentication• Authorization• Compliance and auditing

• Sarbanes-Oxley (SOX), HIPPA, PCI, ISO 17799, etc…

2005 JavaOneSM Conference | Session TS-5210 | 11

Agenda

IntroductionApplication SecuritySecurity Misconceptions

Implementing a Secure ApplicationThree Strategies

Using Coding GuidelinesCoding DefensivelyExpose and Correct Bugs

Penetration TestingImplementing a Security PolicyConclusion

2005 JavaOneSM Conference | Session TS-5210 | 12

The ‘inside-out’ approachImplementing a Secure Application

• Prevention vs. inspection• Inside the “Application Code”

• Code analysis• Unit tests

• Outside the “Web Interface”• Penetration tests• Regression tests• Different interfaces

• Web applications (HTML)• Web services

2005 JavaOneSM Conference | Session TS-5210 | 13

AgendaIntroduction

Application SecuritySecurity Misconceptions

Implementing a Secure ApplicationThree Strategies

Using Coding GuidelinesCoding DefensivelyExpose and Correct Bugs

Penetration TestingImplementing a Security PolicyConclusion

2005 JavaOneSM Conference | Session TS-5210 | 14

‘Inside the code’Three Strategies

• Three strategies for building secure Java code:• Coding guidelines• Code defensively• Expose and correct bugs

• Create clean code before testing completed system

2005 JavaOneSM Conference | Session TS-5210 | 15

AgendaIntroduction

Application SecuritySecurity Misconceptions

Implementing a Secure ApplicationThree Strategies

Using Coding GuidelinesCoding DefensivelyExpose and Correct Bugs

Penetration TestingImplementing a Security PolicyConclusion

2005 JavaOneSM Conference | Session TS-5210 | 16

Why use coding standards for security?Using Coding Guidelines

• Leverage industry best practises• Standardize to improve stability:

• Protect data from external access• Ensure that Java security mechanisms are

used properly• Identify areas where data is exposed• Identify insecure code

2005 JavaOneSM Conference | Session TS-5210 | 17

Avoid using inner classesUsing Coding Guidelines

• No concept of inner classes in Java byte code• Compiler translates to a package scoped classes• Enclosed private variables are changed to

package scoped• Using inner classes can exposes private variables

to package level code• Solution: prohibit the use of inner classes

• If inner classes must be used, make private

2005 JavaOneSM Conference | Session TS-5210 | 18

Avoid comparing class objects by nameUsing Coding Guidelines

• Prohibit comparing class objects using getName()• More than one class in a running JVM may have

the same name• Replacement classes can be used to insert

malicious code• Solution: Compare using object equality

• thisClass.getName() == otherClass.getName //VIOLATION

• thisClass == otherClass //FIXED

2005 JavaOneSM Conference | Session TS-5210 | 19

Make your classes non-cloneableUsing Coding Guidelines

• Cloning can allow an attacker to manufacture new instances without using a constructor

• Solution: define a final clone method that will throw a CloneNotSupporedException()• If a class needs to be cloneable, make the clone()

method final

Public final Object clone() throws java.lang.CloneNotSupportedException {throw new java.lang.CloneNotSupporedException();

}

2005 JavaOneSM Conference | Session TS-5210 | 20

Make your classes non-serializableUsing Coding Guidelines

• Serialization allows hackers to view the full internal state

• Solution: Define a final writeObject() method that will throw IOException• If you need to make the class serializable

• Use the Transient keyword for sensitive information• Do not pass internal arrays to DataInput/DataOutput

2005 JavaOneSM Conference | Session TS-5210 | 21

Do not depend on package scopeUsing Coding Guidelines

• Adding a class to a package allows access to package-private fields

• Solution: Prohibit use of package-private scope• If you need to use package scope,

use package sealing

2005 JavaOneSM Conference | Session TS-5210 | 22

Avoid returning references to mutable objectsUsing Coding Guidelines

• Returning references to mutable objects allows the caller to change the state of that internal object

• Solution: avoid returning references to mutable objects• If necessary, clone the mutable object before returning

a reference to itpublic Date getDate() {

return fDate; //VIOLATION}public Date getDate() {

return new Date(fDate.getTime()); //FIXED}

2005 JavaOneSM Conference | Session TS-5210 | 23

Do not directly store user given mutable objectsUsing Coding Guidelines

• Directly storing provided mutable objects (including arrays) allows a caller to change the object while the called class is using the data, potentially bypassing security ‘checks’

• Solution: do not use the mutable object directlypublic void useDate(Date date) {

if (isValid(date))

scheduleTask(date); //VIOLATION

---

public void useDate(Date date) {

Date copied_date = new Date(date.getTime());

if (isValid(copied_date)) //FIXED:Not using date directly

scheduleTask(date);

2005 JavaOneSM Conference | Session TS-5210 | 24

Use private and final to control accessUsing Coding Guidelines

• Reduce the number of potential entry points using private and final

• All methods, fields and classes should be declared private

• All classes and methods should be final• Clearly document any exceptions to the rule

2005 JavaOneSM Conference | Session TS-5210 | 25

Tips for implementing security coding standardsUsing Coding Guidelines

• Apply guidelines before submitting to source control

• Apply before the application is completed• Apply uniformly across a development team• Automation is the key to adoption

2005 JavaOneSM Conference | Session TS-5210 | 26

AgendaIntroduction

Application SecuritySecurity Misconceptions

Implementing a Secure ApplicationThree Strategies

Using Coding GuidelinesCoding DefensivelyExpose and Correct Bugs

Penetration TestingImplementing a Security PolicyConclusion

2005 JavaOneSM Conference | Session TS-5210 | 27

What is defensive programming?Coding Defensively

• Enforce consistent operation• Validate input• Error handling

• Maintain centralization of security mechanisms• Logging• Software firewalls• Database access

• Avoid dangerous functions• Native code• External components

2005 JavaOneSM Conference | Session TS-5210 | 28

Defensive firewallsCoding Defensively

• Software firewall != network firewall• Ensure that hackers that access the code

cannot move to critical sections• Hackers often access code from an

unexpected path• Validate the stack trace to control access

to critical calls

2005 JavaOneSM Conference | Session TS-5210 | 29

Example: defensive firewalls—protecting the databaseCoding Defensively

void method (int a) {

int b;

int value_returned = calculate (a, b);

String user_name = getUserName( );

boolean valid_stack_trace = isValidStackTrace(newThrowable().getStackTrace());

assertTrue("Warning!, Unexpected sequence of operations" , valid_strack_trace);

// critical call, will not execute if assertion fails.

updateDataBase(user_name, value_returned);

}

2005 JavaOneSM Conference | Session TS-5210 | 30

Validating user/external inputsCoding Defensively

• External inputs are doors into the application• All input needs to be validated before use

• Identify improper or malicious inputs• Validation options

• Assertions• If statements• Design by Contract (DbC)

2005 JavaOneSM Conference | Session TS-5210 | 31

Example: dynamic system.exec()Coding Defensively

void method (String filename) {System.exec("more " + filename); //VIOLATION

}

---

filename =“joe; /bin/rm –rf /*”; //malicious argument

---

void method (String filename){if (new File(filename).exists()){ //FIXED

System.exec("more " + filename);

}

}

2005 JavaOneSM Conference | Session TS-5210 | 32

Preventing SQL InjectionCoding Defensively

• Insufficient security checks on dynamical created SQL statements using fixed user inputs

• Potential issues• Logging in with valid username/password• Login with admin privileges• Unauthorized access to privileged data• Ability to make unauthorized modifications to the

database• Solution: use PreparedStatement

2005 JavaOneSM Conference | Session TS-5210 | 33

Example: SQL Injection bypassing login checksCoding Defensively

String s = "SELECT User_id, Username FROM USERS WHERE Username = '" + sUsername + "' AND Password = '" + sPassword + "'";…Statement queryStatement =

connection.createStatement();queryStatement.executeQuery(s);

• Imagine:

sUsername = ‘ or 1=1 ‘sPassword = (ANY)

2005 JavaOneSM Conference | Session TS-5210 | 34

Example: SQL Injection bypassing login checksCoding Defensively

PreparedStatement queryStatement = null;try {

queryStatement = connection.prepareStatement("SELECT User_id FROM USERS WHERE Username = ? AND Password = ?");queryStatement.setString (1, user);queryStatement.setString (2, password);

…} catch { …

2005 JavaOneSM Conference | Session TS-5210 | 35

Using Design by ContractCoding Defensively

• Enforces contracts between code and its caller• Can be used to validate user inputs and

implement firewall-like restrictions• Java tools implement DbC by instrumenting code

with assertions that check:• Preconditions• Postconditions• Invariants

2005 JavaOneSM Conference | Session TS-5210 | 36

AgendaIntroduction

Application SecuritySecurity Misconceptions

Implementing a Secure ApplicationThree Strategies

Using Coding GuidelinesCoding DefensivelyExpose and Correct Bugs

Penetration TestingImplementing a Security PolicyConclusion

2005 JavaOneSM Conference | Session TS-5210 | 37

Security Bugs != Functional BugsExpose and Correct Bugs

• Security bugs seen as a separate class• Frequently result from unspecified program

behaviour• Developers not sensitive to security issues• A system can perform to functional spec but still

be insecure• If not found by QA… who finds them?

2005 JavaOneSM Conference | Session TS-5210 | 38

Security Testing != Functional TestingExpose and Correct Bugs

• Look for unspecified behaviour• Test wide range of valid and ‘unexpected’ data• Looking for every single security bug• A passed functional test may be a failed

security test• Complex and time consuming

2005 JavaOneSM Conference | Session TS-5210 | 39

Example: NullPointerException bypassing loginExpose and Correct Bugspublic boolean isValidLogin(String uname, String pass){

boolean valid = true;

try {

setDatabaseConnection();

valid = XpUserFinder.getUser(uname).getPassword().equals(pass);

//If uname is null, an exception is thrown and

//‘valid’ will default to true.

}

catch (Throwable e) {

e.printStackTrace();

}

}

2005 JavaOneSM Conference | Session TS-5210 | 40

AgendaIntroduction

Application SecuritySecurity Misconceptions

Implementing a Secure ApplicationThree Strategies

Using Coding GuidelinesCoding DefensivelyExpose and Correct Bugs

Penetration TestingImplementing a Security PolicyConclusion

2005 JavaOneSM Conference | Session TS-5210 | 41

“Outside the application”Penetration Testing

• “… a method of evaluating the security of a computer system or network by simulating an attack by a malicious hacker.” (en.wikipedia.org)

• Goals• Find vulnerabilities• Test the effectiveness of secure development initiatives• Compliance

• Testing guidelines• OWASP Pen-Testing Checklist (www.owasp.org)

• WebGoat• Open Source Security Testing Methodology Manual (OSSTMM)• NIST, PCI, others

2005 JavaOneSM Conference | Session TS-5210 | 42

AgendaIntroduction

Application SecuritySecurity Misconceptions

Implementing a Secure ApplicationThree Strategies

Using Coding GuidelinesCoding DefensivelyExpose and Correct Bugs

Penetration TestingImplementing a Security PolicyConclusion

2005 JavaOneSM Conference | Session TS-5210 | 43

Seven steps to securing an applicationImplementing a Security Policy

1. Determine risks/threats2. Develop countermeasures as Security Policy3. Implement Security Policy process at code level4. Eliminate security vulnerabilities in code5. Test application from ‘outside’6. Address problems found by fixing code7. Regression test

2005 JavaOneSM Conference | Session TS-5210 | 44

Defining a security policyImplementing a Security Policy

• Trade off between secure code and...• Optimal performance• Following requirements• Achieving milestones

• Trade-offs need to be defined in a security policy• Applied uniformly• Enforced in an automated manner• Used for SOX compliance• Removes arbitrary decisions made by developers

2005 JavaOneSM Conference | Session TS-5210 | 45

AgendaIntroduction

Application SecuritySecurity Misconceptions

Implementing a Secure ApplicationThree Strategies

Using coding guidelinesCoding defensivelyExpose and correct bugs

Penetration TestingImplementing a Security PolicyConclusion

2005 JavaOneSM Conference | Session TS-5210 | 46

Putting it all togetherConclusion

• The first step implement Security Policy• Simple strategy for building secure applications:

• Apply coding guidelines• Defensive programming• Reducing bugs

• The next steps• Validate the Policy• Refine and improve

2005 JavaOneSM Conference | Session TS-5210 | 47

For More Information

• Whitepapers available at:• http://www.parasoft.com/JavaOne/Security

• Demonstrations at the Parasoft booth #718• Jtest—Java security testing• WebKing—Web application penetration testing• SOATest—Web services penetration testing• Group Reporting Server—SOX Compliance

2005 JavaOneSM Conference | Session TS-5210 | 48

More References• Compaq. Extended Static Checking for Java, SQL Injection Walkthrough.

http://www.securiteam.com/securityreviews/5DP0N1P76E.html

• Graff, Mark G. and Kenneth R.van Wyk. Secure Coding Principles and Practices. OReilly, 2003.

• Howard, Michael and DavidLeBlanc. Writing Secure Code. Microsoft Press, 2002, pp. 307-322.

• Kolawa, Adam, Wendell Hicken, and Cynthia Dunlop. Bulletproofing Web Applications. John Wiley & Sons, 2001.

• McGraw, Gary and Edward Felten. Twelve Rules for Developing More Secure Java Code. JavaWorld (December 1998). http://www.javaworld.com/javaworld/jw-12-1998/jw-12-securityrules_p.html

• McGraw, Gary and Edward Felten. Securing Java. John Wiley & Sons, 1999. http://www.securingjava.com

• Rao, Ravinda. Writing Secure Java Code. Macmillan Technical Publishing, 1999.

• SQL Injection Walkthrough. http://www.securiteam.com/securityreviews/5DP0N1P76E.html

• Sun Microsystems. Security Code Guidelines. http://java.sun.com/security/seccodeguide.html

• Viega, John, Gary McGraw, Tom Mutdosch, and Edward W. Felten. Statically Scanning Java Code: Finding Security Vulnerabilities. IEEE Software (September/October 2000).

• Wheeler, David A. Secure Programming for Linux and Unix HOWTO. http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/java.html

2005 JavaOneSM Conference | Session TS-5210 | 49

Q&AMark Lambert

2005 JavaOneSM Conference | Session TS-5210 | 50

Submit Session Evaluations for Prizes!

• You can win a $75.00 gift certificate to the on-site Retail Store by telling Sun what you think!

• Turn in completed forms to enter the daily drawing• Each evaluation must be turned in the same day as

the session presentation• Five winners will be chosen each day (Sun will send

the winners e-mail)• Drop-off locations: give to the room monitors or use any

of the three drop-off stations in the North and South Halls

Note: Winners on Thursday, 6/30, will receive and can redeem certificates via e-mail.

Your opinions are important to Sun

512005 JavaOneSM Conference | Session TS-5210

Strategies for Securing Java CodeMark LambertJtest Product SpecialistParasoftwww.parasoft.comTS-5210