secure coding for java

154
The OWASP Foundation http://www.owasp.org Integrating security & privacy in a web application project OWASP Training Day - Ottawa Feb 27th 2012 Module 2 : Secure Coding mardi 8 janvier 13

Upload: sebastien-gioria

Post on 08-Jun-2015

911 views

Category:

Technology


9 download

TRANSCRIPT

Page 1: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Integrating security & privacy in a web application project

OWASP Training Day - OttawaFeb 27th 2012

Module 2 : Secure Coding

mardi 8 janvier 13

Page 2: Secure Coding for Java

•Introduction

•Using OWASP materials to secure code

•Secure Coding principles

•Code Review

Agenda

mardi 8 janvier 13

Page 3: Secure Coding for Java

CISA && ISO 27005 Risk Manager

http://www.google.fr/#q=sebastien gioria

➡OWASP France Leader & Founder - Evangéliste➡ OWASP Global Education Comittee Member ([email protected])

➡Head of IT and Security Audit at Groupe Y

Twitter :@SPoint

★More than 15 years of manager and technical leads in differents firms ; bank, insurance, telecom, startups, ...

★Technical Expertise★Securing SDLC★Pentesting★CodeReview★Risk management, audits★Security and Network training

➡Leader and technical advisor on the Web App security group at CLUSIF

mardi 8 janvier 13

Page 4: Secure Coding for Java

ForeWords•This is a Training made from my own

experience with a big number of company using OWASP materials.

•Only the documents from OWASP wiki are OWASP officials (see https://www.owasp.org)

•Some extracts come from document I wrote as OWASP leader, this is why you could find it elsewhere.

5

mardi 8 janvier 13

Page 5: Secure Coding for Java

Majors OWASP publications we can use

All are on the wiki https://www.owasp.orgAll are under GPL or friendly licensesMajors publications you can use to secure

your projects/SDLC

Building Guide

Code Review Guide Testing Guide

Application Security Desk Reference (ASDR)

Top10 reference this 3 guides

Ø OWASP Top10Ø Auditor/Testing GuideØ Code Review GuideØ Building GuideØ Application Security Verification

Standard (ASVS)Ø Secure Coding Practices

12

mardi 8 janvier 13

Page 6: Secure Coding for Java

13

mardi 8 janvier 13

Page 7: Secure Coding for Java

13

mardi 8 janvier 13

Page 8: Secure Coding for Java

13

Learning

mardi 8 janvier 13

Page 9: Secure Coding for Java

13

Learning

mardi 8 janvier 13

Page 10: Secure Coding for Java

13

Learning Contract

mardi 8 janvier 13

Page 11: Secure Coding for Java

13

Learning Contract

mardi 8 janvier 13

Page 12: Secure Coding for Java

13

Learning Contract

Testing

mardi 8 janvier 13

Page 13: Secure Coding for Java

13

Learning Contract

Testing

mardi 8 janvier 13

Page 14: Secure Coding for Java

13

Learning Contract

Testing

Build

mardi 8 janvier 13

Page 15: Secure Coding for Java

13

Learning Contract

Testing

Build

mardi 8 janvier 13

Page 16: Secure Coding for Java

13

Learning Contract

Testing

Build

Check

mardi 8 janvier 13

Page 17: Secure Coding for Java

13

Learning Contract

Testing

Build

Check

mardi 8 janvier 13

Page 18: Secure Coding for Java

13

Learning Contract

Testing

Build

Check Progress

mardi 8 janvier 13

Page 19: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Introduction

mardi 8 janvier 13

Page 20: Secure Coding for Java

Consequences of bad or no security

• Identity theft

• Hardware theft

• Bad Media coverage

• Customers loss

• Legals/business penalty

• Financials loss

• IT downtime8

mardi 8 janvier 13

Page 21: Secure Coding for Java

© CLUSIF 2010 - Extrait de la présentation MIPS2010

17

mardi 8 janvier 13

Page 22: Secure Coding for Java

© CLUSIF 2010 - Extrait de la présentation MIPS2010

18

mardi 8 janvier 13

Page 23: Secure Coding for Java

What Verizon (PCI-DSS company) said ?

© Verizon 2010

11mardi 8 janvier 13

Page 24: Secure Coding for Java

What Verizon (PCI-DSS company) said ?

© Verizon 2010

11mardi 8 janvier 13

Page 25: Secure Coding for Java

What Verizon (PCI-DSS company) said ?

© Verizon 2010

11mardi 8 janvier 13

Page 26: Secure Coding for Java

© Verizon 2010

Verizon Study

12mardi 8 janvier 13

Page 27: Secure Coding for Java

© Verizon 2010

Verizon Study

12mardi 8 janvier 13

Page 28: Secure Coding for Java

© IBM X-Force 2009 - Extrait du rapport 2009

22

mardi 8 janvier 13

Page 29: Secure Coding for Java

© IBM X-Force 2009 - Extrait du rapport 2009

23

mardi 8 janvier 13

Page 30: Secure Coding for Java

Vulnerability exposure

26

mardi 8 janvier 13

Page 31: Secure Coding for Java

What you CIO Said : I got a Firewall !

27

mardi 8 janvier 13

Page 32: Secure Coding for Java

What your business user said : I have SSL based Web Site

28

mardi 8 janvier 13

Page 33: Secure Coding for Java

What your business user said : only the hacker can attack my website

• Tools are more and more simples.

• Try a simple request on google website on SQL Injection and look at it.

• An attack on a Web Server cost 100$/200$ per day on the underground market.

29

mardi 8 janvier 13

Page 34: Secure Coding for Java

What your user said : a vulnerability on internal WebApp is not critical.

•No, The web is anywhere, and CSRF, HTML5 CORS and more can make this completly destructive

•Be aware and share this :

• AJAX doing a lot of things without you

•Be aware and share this :

• HTML5 will come with “nice” user functionnality , but with big impact on security (WebSocket, CORS, ...)

30

mardi 8 janvier 13

Page 35: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

OWASP Application Security Verification Standard

mardi 8 janvier 13

Page 36: Secure Coding for Java

What is ASVS ?•A standard that provides a basis for the

verification of web applications application-independent.

•A standard life-cycle model independent.

•A standard that define requirements that can be applied across applications without special interpretation.

43

mardi 8 janvier 13

Page 37: Secure Coding for Java

What are ASVS responses ?

•How much trust can be placed in a web application?

•What features should be built into security controls?

•How do I acquire a web application that is verified to have a certain range in coverage and level of rigor?

mardi 8 janvier 13

Page 38: Secure Coding for Java

ASVS secure controls requirements

Security AreaLevel

1A

Level

1B

Level

2A

Level

2BLevel 3 Level 4

V1 – Security Architecture Verification Requirements 1 1 2 2 4 5

V2 – Authentication Verification Requirements 3 2 9 13 13 14

V3 – Session Management Verification Requirements 4 1 6 7 8 9

V4 – Access Control Verification Requirements 5 1 12 13 14 15

V5 – Input Validation Verification Requirements 3 1 5 7 8 9

V6 – Output Encoding/Escaping Verification Requirements 0 1 2 8 9 10

V7 – Cryptography Verification Requirements 0 0 2 8 9 10

V8 – Error Handling and Logging Verification Requirements 1 1 2 8 8 9

V9 – Data Protection Verification Requirements 1 1 2 3 4 4

V10 – Communication Security Verification Requirements 1 0 3 6 8 8

V11 – HTTP Security Verification Requirements 3 3 6 6 7 7

V12 – Security Configuration Verification Requirements 0 0 0 2 3 4

V13 – Malicious Code Search Verification Requirements 0 0 0 0 0 5

V14 – Internal Security Verification Requirements 0 0 0 0 1 3

Totals 22 12 51 83 96 112

23mardi 8 janvier 13

Page 39: Secure Coding for Java

But ASVS stand for Verification ?

•ASVS just said functionals needs for controls.

•We could use it as a Secure Coding Policy.

★Don’t be medium(ASVS Level1/2), just target excellence (ASVS Level 4)

24mardi 8 janvier 13

Page 40: Secure Coding for Java

Using ASVS as a secure coding policy

ASVS : Verify that all password fields do not echo the user’s password when it is entered.

➡ All Password fields must be define as HTML passwd fields and must not echo user passwd.

➡ All login forms must include autocomplete=off tag

ASVS : Verify that all input validation is performed on the server side.

➡ Performs all input validation on the server. Nothing in the browser

25mardi 8 janvier 13

Page 42: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

OWASP Secure Coding Practices

mardi 8 janvier 13

Page 43: Secure Coding for Java

OWASP Secure Coding Practices

•Small document (only 9 pages)

•Could be use as an simple checklist for your policy.

•Could be use together with ASVS or alone.

•More technical and deeper approach than ASVS .

•Wrote and use by Boeing :)28

mardi 8 janvier 13

Page 44: Secure Coding for Java

Secure Coding Practices Contents

•Input Validation

•Output Encoding

•Authentication and Password Management

•Session Management

•Access Control

•Cryptographic Practices

•Error Handling and Logging

•Data Protection

•Communication Security

•System Configuration

•Database Security

•File Management

•Memory Management

•General Coding Practices

29mardi 8 janvier 13

Page 45: Secure Coding for Java

Now the torture room

30mardi 8 janvier 13

Page 46: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

(extracts from OWASP Secure Coding Practices/OWASP CheatSheets OWASP ASVS, ...)

Let talk Secure Coding now

mardi 8 janvier 13

Page 47: Secure Coding for Java

32

KISS : Keep it Short and Simple

mardi 8 janvier 13

Page 48: Secure Coding for Java

Some secures principles to follow

33

•Deep defense of application is mandatory

•Following less privileges is the best solution

•Segregate duty more that user think

➡Remember that application need to answer user needs and not security pleasure.

mardi 8 janvier 13

Page 49: Secure Coding for Java

Deep defense of an Application (example)

70

Firewall

Applica5onWeb  Apps

SGBDApp ServerWebServer

Browser

User auth

Input Validation

Secure configuration

Good crash mecanisms

• Critical data transport protection

• Preventing session and ID theft

Critical data protectionsLogs/Audit of transactions

Authorisation and

authentication

Authorisation and authentication

Critical data protectionsPreventing parameters thefts

mardi 8 janvier 13

Page 50: Secure Coding for Java

Fail securelyDon’t give user technical details of the crash.

Example :

• 404

• 500

35mardi 8 janvier 13

Page 51: Secure Coding for Java

Fail Securely

36mardi 8 janvier 13

Page 52: Secure Coding for Java

Don’t try to make obscure things

72

mardi 8 janvier 13

Page 53: Secure Coding for Java

Don’t try to make obscure things

72

GEOPORTAIL

mardi 8 janvier 13

Page 54: Secure Coding for Java

Don’t try to make obscure things

72

mardi 8 janvier 13

Page 55: Secure Coding for Java

Don’t try to make obscure things

72

GOOGLE MAPS

mardi 8 janvier 13

Page 56: Secure Coding for Java

Controls• Controls need :

• to be simple

• to be used correctly

• functional

• present in every part of the application74

Bad understanding of a control result of unused it by developers and application will be

vulnerable.

mardi 8 janvier 13

Page 57: Secure Coding for Java

Minimals controls to have

You must have at least this components in your application :

• Authentication

• Authorization

• Logging and audit

• Secure Storage

• Secure transport

• Secure input and output manipulation of data

75

mardi 8 janvier 13

Page 58: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Authentication

mardi 8 janvier 13

Page 59: Secure Coding for Java

Implement good passwd strategy

Password length

- Categorize applications :

• Important : at least 6 characters

• Critical : at least 8 characters and perhaps multi-factors authentication

• High Critical : at least 14 characters and multi-factors authentication

Password strength

- Implement passwd complexity with previous categories

• at least : 1 upper, 1 lower, 1 digit, 1 special

• don’t allow dictionnary passwd

• don’t allow continuous characters

41mardi 8 janvier 13

Page 60: Secure Coding for Java

Implement good passwd strategy

•Let the user choose it

•Force the user to change it regulary, and add no reuse capability.

•Don’t allow too much “I forgot my passwd”

•Don’t allow change of passwd without user approval; require actual passwd from the user and more for high critical.

•Add sleep strategy !

•Add detection of misuse strategy !

•Don’t store passwd in clear !!!!! use hash !42

mardi 8 janvier 13

Page 61: Secure Coding for Java

Multi-Factor authentication

•Passwds are bad

•Passwds are guessable

•Multi-factor combine:

• something you have (token, mobile, ...)

• something you know (details about you, passwd, ...)

• sometime, something you are (biometrics)

• Use it for high critical applications.

43mardi 8 janvier 13

Page 62: Secure Coding for Java

Implement good global strategy

•Ask second authentication for critical transactions (with multi-factor auth...)

•Force authentication to be in TLS/SSL

•Regenerate Session ID after authentication

•Force Session ID to be “secure”

•Limiting forgotten passwd,change of login/passwd

44mardi 8 janvier 13

Page 63: Secure Coding for Java

Good Passwd strategy

45mardi 8 janvier 13

Page 64: Secure Coding for Java

How to do ? •Authenticate all pages but not public pages (login,

logout, help, ....)

•Don’t allow more than one authentication mecanism

•Authenticate on the SERVER

•Simply send back “user or passwd mismatch” and nothing else after a failed authentication.

•Logged all failed and all correct authentication

•After each authentication give the user the last status of his authentication.

46mardi 8 janvier 13

Page 65: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Exercice 1.1Adding secure Authentication to ePoney

mardi 8 janvier 13

Page 66: Secure Coding for Java

Exercice 1.1 - IdeasSetup Passwd strategy

• Length

• Complexity

Fighting brute-force

• in-session limitation

• out of session limitation

48mardi 8 janvier 13

Page 67: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Session Management

mardi 8 janvier 13

Page 68: Secure Coding for Java

Session •Use Default Java Framework Generator

•Use other name than the default name of the Framework (rename JSESSIONID...)

•Force transport of ID authentication on SSL/TLS.

•Don’t allow Session ID in URL !

•If using cookie :

• Secure Cookie

• HTTPOnly Cookie

• Limiting path + domain

• Max Age and expiration50

mardi 8 janvier 13

Page 69: Secure Coding for Java

Session trickyAutomatic expiration

• categorize applications :

• default : 1 hour

• critical (some transaction) : 20mns

• high critical (financials or account impact) : 5mns

Renew Session ID after any privilege change

Don’t allow simultaneous logon

Add Session Attack Detection

• add in-session tips : ip of session, other random number, ...

51mardi 8 janvier 13

Page 70: Secure Coding for Java

Browser defensesBind JavaScript events to close session

• on window.close()

• on window.stop()

• on window.blur()

• on window.home()

Use Javascripts timer to automatic close session in high critical applications

Disable WebBrowser Cross-tab Session if possible...(bad user experiences....)

• If you use cookie, this is not possible !!!!

52mardi 8 janvier 13

Page 71: Secure Coding for Java

53

<session-­‐config>    <cookie-­‐config>        <http-­‐only>true</http-­‐only>        <secure>true</secure>    </cookie-­‐config></session-­‐config>

Using Servlet 3.0 ?

mardi 8 janvier 13

Page 72: Secure Coding for Java

Access Controls

107

mardi 8 janvier 13

Page 73: Secure Coding for Java

Remember

mardi 8 janvier 13

Page 74: Secure Coding for Java

Remember(1)Without access control, you can’t

control the user in your application

mardi 8 janvier 13

Page 75: Secure Coding for Java

Remember(1)Without access control, you can’t

control the user in your application

(2)Client inputs are EVIL

mardi 8 janvier 13

Page 76: Secure Coding for Java

Authentication && Authorization

• Two Levels of authentication and authorization are needed

–In the Application

–In infrastructure

Table  A

Table  B

Connexion Table A + duty ARole  A

Role  B

SGBDApp Server

Connexion Table B + Duty B

mardi 8 janvier 13

Page 77: Secure Coding for Java

AuthorizationHave in mind the rule :

• Nothing by default

Centralize all authorization code on the SERVER

If client state are mandatory, use encryption and integrity checking on the server side to catch state tampering.

Limit number of transaction per user at a interval time.

57mardi 8 janvier 13

Page 78: Secure Coding for Java

AuthorizationEnforce :

• protection of URL to authorized account only

• protection of function to authorized account only

• protection of file access to authorized account only

Application need to terminate session when authorization failed.

Split administrative and user authorization

Enforce dormant account :

• loss privileges.

• “disable account”

• alerts

58mardi 8 janvier 13

Page 79: Secure Coding for Java

Exercice Make que application mono-session per

user

59mardi 8 janvier 13

Page 80: Secure Coding for Java

Input ValidationEnsure all data validation are done on THE SERVER.

• If you do something on client side we can said you do “painting”

Classify your data :

• Trusted Data

• Untrusted Data

Conduct trusted path.

Centralize your data validation

Use parametrize query when exists (SQL)

60mardi 8 janvier 13

Page 81: Secure Coding for Java

Border validationConsider validating data along all the entry

points of your Application border

61mardi 8 janvier 13

Page 82: Secure Coding for Java

Input ValidationUse proper characters set for all input

Encode all data to the same character set before doing anything <=>Canonicalize

Reject all not validated datas

Validate data :

• expected type (convert as soon as possible to Java Types)

• expected range

• expected length

• expected values

• expected “white list” if possible

62mardi 8 janvier 13

Page 83: Secure Coding for Java

Input ValidationBe careful of using “hazardous” characters (ex:

<>’,”!(+)&\ %.)

Add specific validation :

• check for null bytes (%00)

• check for new lines (%0D, %0A, \n, \r, ...)

• check for dot-dot-slashes (../)

63mardi 8 janvier 13

Page 84: Secure Coding for Java

Be careful of encoding for specific validation...

URL%3c%73%63%72%69%70%74%3e%61%6c%65%72%74%28%58%53%53%29%3b%3c%2f%73%63%72%69%70%74%3e%0a

HTML&#x3c;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x3e;&#x61;&#x6c;&#x65;&#x72;&#x74;&#x28;&#x58;&#x53;&#x53;&#x29;&#x3b;&#x3c;&#x2f;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x3e;&#x0a;

UTF-8%u003c%uff53%uff43%uff52%uff49%uff50%uff54%u003e%uff41%uff4c%uff45%uff52%uff54%uff08%uff38%uff33%uff33%uff09%u003c%u2215%uff53%uff43%uff52%uff49%uff50%uff54%u003

One space ?< s c r i p t > a l e r t ( X S S ) ; < / s c r i p t >

<script>alert(XSS);</script>

mardi 8 janvier 13

Page 85: Secure Coding for Java

Validating Datas

124

mardi 8 janvier 13

Page 86: Secure Coding for Java

SQL => bad

125

mardi 8 janvier 13

Page 87: Secure Coding for Java

SQL => bad

125

mardi 8 janvier 13

Page 88: Secure Coding for Java

SQL => bad

125

mardi 8 janvier 13

Page 89: Secure Coding for Java

SQL => a little bit better

126

mardi 8 janvier 13

Page 90: Secure Coding for Java

XML => bad

127

mardi 8 janvier 13

Page 91: Secure Coding for Java

XML => bad

127

mardi 8 janvier 13

Page 92: Secure Coding for Java

XML => Validating

128

mardi 8 janvier 13

Page 93: Secure Coding for Java

Better, a XML schema<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="item">

<xs:complexType>

<xs:sequence>

<xs:element name="description" type="xs:string"/>

<xs:element name="price" type="xs:decimal"/>

<xs:element name="quantity" type="xs:integer"/>

</xs:sequence>

</xs:complexType>

</xs:element>

</xs:schema>

mardi 8 janvier 13

Page 94: Secure Coding for Java

XML => XML Parser

mardi 8 janvier 13

Page 95: Secure Coding for Java

LDAP => bad

131

mardi 8 janvier 13

Page 96: Secure Coding for Java

LDAP => bad

131

mardi 8 janvier 13

Page 97: Secure Coding for Java

LDAP => better

132

mardi 8 janvier 13

Page 98: Secure Coding for Java

Using OWASP ESAPI

74mardi 8 janvier 13

Page 99: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Output Encoding

mardi 8 janvier 13

Page 100: Secure Coding for Java

Output encodingIt’s a Defense in depth mechanism

Encode ON THE SERVER

Centralize the encoder functions

Sanitize all data send to the client

• HTMLEncode is a minimum but did not work on all cases

76mardi 8 janvier 13

Page 101: Secure Coding for Java

Essai 1 => bad

137

mardi 8 janvier 13

Page 102: Secure Coding for Java

Essai 1 => bad

137

mardi 8 janvier 13

Page 103: Secure Coding for Java

Essai 2 => it’s bad, but better than nothing

138

mardi 8 janvier 13

Page 104: Secure Coding for Java

Essai 2 => it’s bad, but better than nothing

138

mardi 8 janvier 13

Page 105: Secure Coding for Java

A good solution with a robust Sanitizer :)

139

mardi 8 janvier 13

Page 106: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Error Logging

mardi 8 janvier 13

Page 107: Secure Coding for Java

Error HandlingYour Application will crash !

Catch all exceptions without exception (remember the null pointer exception !)

• Clean all exception code of sensitive datas

• Don’t give user any details about crash, just said “It’s a crash, try again later”

Logs are sensitive, you MUST PROTECT THEM

Log :

• input validation failures

• authentication request; especially failures

• access control failures

• systems exceptions

• administrative functionality

• crypto failures

• invalid/expired session token access

81mardi 8 janvier 13

Page 108: Secure Coding for Java

Logging/ErrorsSplit your logs with categories, examples :

• Access

• Error

• Debug

• Audit

Use log4j for standard logging

82mardi 8 janvier 13

Page 109: Secure Coding for Java

Log4J Example

83

import com.sec.dev;

// Import log4j classes. import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator;

public class SecLogger {

// Define a static logger variable so that it references the // Logger instance named "MyApp". static Logger logger = Logger.getLogger(MyApp.class);

public static void main(String[] args) {

// Set up a simple configuration that logs on the console. BasicConfigurator.configure();

logger.setLevel(Level.DEBUG); // optional if log4j.properties file not used // Possible levels: TRACE, DEBUG, INFO, WARN, ERROR, and FATAL

logger.info("Entering application."); Bar bar = new Bar(); bar.doIt(); logger.info("Exiting application."); } }

mardi 8 janvier 13

Page 110: Secure Coding for Java

ExerciceAdd correct logging to ePoney

Verify error handling implementation

84mardi 8 janvier 13

Page 111: Secure Coding for Java

Bad handling of Exception

144

mardi 8 janvier 13

Page 112: Secure Coding for Java

Bad handling of Exception

144

mardi 8 janvier 13

Page 113: Secure Coding for Java

Good handling of exception

145<error-page> <exception-type>java.lang.Throwable</exception-type> <location>/error.jsp</location> </error-page>

mardi 8 janvier 13

Page 114: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Data Protection

mardi 8 janvier 13

Page 115: Secure Coding for Java

Data protectionProtect sensitive datas, don’t store them

in clear.

Store sensitive datas in trusted systems

Don’t use GET request for sensitive data.

Disable client site caching

88mardi 8 janvier 13

Page 116: Secure Coding for Java

Disable Client Side caching

89

import  javax.servlet.*;import  javax.servlet.http.HttpServletResponse;import  java.io.IOException;import  java.util.Date;

public  class  CacheControlFilter  implements  Filter  {

       public  void  doFilter(ServletRequest  request,  ServletResponse  response,                                                  FilterChain  chain)  throws  IOException,  ServletException  {

               HttpServletResponse  resp  =  (HttpServletResponse)  response;                resp.setHeader("Expires",  "Tue,  03  Jul  2001  06:00:00  GMT");                resp.setHeader("Last-­‐Modified",  new  Date().toString());                resp.setHeader("Cache-­‐Control",  "no-­‐store,  no-­‐cache,  must-­‐revalidate,  max-­‐age=0,  post-­‐check=0,  pre-­‐check=0");                resp.setHeader("Pragma",  "no-­‐cache");

               chain.doFilter(request,  response);        }

}

<filter>        <filter-­‐name>SetCacheControl</filter-­‐name>        <filter-­‐class>com.sec.dev.cacheControlFilter</filter-­‐class></filter>                                              <filter-­‐mapping>        <filter-­‐name>SetCacheControl</filter-­‐name><url-­‐pattern>/*</url-­‐pattern></filter-­‐mapping>

web.xml

mardi 8 janvier 13

Page 117: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Acces to FileSystem

mardi 8 janvier 13

Page 118: Secure Coding for Java

Absolute Path is bad

151

mardi 8 janvier 13

Page 119: Secure Coding for Java

Absolute Path is bad

151

mardi 8 janvier 13

Page 120: Secure Coding for Java

Absolute Path is bad

151

mardi 8 janvier 13

Page 121: Secure Coding for Java

Canonicalisation is good

92mardi 8 janvier 13

Page 122: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Secure Communications

mardi 8 janvier 13

Page 123: Secure Coding for Java

Secure CommunicationsUse TLS/SSL :

• at least SSL v3.0/TLS 1.0

• minimum of 128bits encryption

• use secure crypto : AES is good

Don’t expose critical data in the URL

Failed SSL/TLS communications should not fall back to insecure

Validate certificate when used

Protect all page, not just logon page !

94mardi 8 janvier 13

Page 124: Secure Coding for Java

Force TLS/SSL Response

Use HTTP Strict Transport Security (HSTS).

• Available on some browsers

• draft IETF : http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-04

95

HttpServletResponse  ...;response.setHeader("Strict-­‐Transport-­‐Security",  "max-­‐age=7776000;  includeSubdomains");

mardi 8 janvier 13

Page 125: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Administrative interfaces

mardi 8 janvier 13

Page 126: Secure Coding for Java

Administratives interfaces

Use multi-factor authentication system

Log transaction in other log files than user.

Enforce logging, examples :

• transaction on duty

• transaction on user accounts

Be careful of duty :

• Help Desk is not an Administrator !

97mardi 8 janvier 13

Page 127: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Configuration

mardi 8 janvier 13

Page 128: Secure Coding for Java

site:yale.edu inurl:password

mardi 8 janvier 13

Page 129: Secure Coding for Java

Configuration

100

Review all properties, configuration files

Be careful of default passwds...

Remove, and not just desactivate, unused functions/modules

Use sandbox system when available :

Be careful of Java Signed code who execute with more privileges !

mardi 8 janvier 13

Page 130: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Code Review

mardi 8 janvier 13

Page 131: Secure Coding for Java

Why Security Code review /Vulnerability searching?

102mardi 8 janvier 13

Page 132: Secure Coding for Java

Why Security Code review /Vulnerability searching?

✓To find them ?

102mardi 8 janvier 13

Page 133: Secure Coding for Java

Why Security Code review /Vulnerability searching?

✓To find them ?

✓To know where there are in the code ?

102mardi 8 janvier 13

Page 134: Secure Coding for Java

Why Security Code review /Vulnerability searching?

✓To find them ?

✓To know where there are in the code ?

✓To ensure they are not in our code ?

102mardi 8 janvier 13

Page 135: Secure Coding for Java

Why Security Code review /Vulnerability searching?

✓To find them ?

✓To know where there are in the code ?

✓To ensure they are not in our code ?

✓To conform to legal/business rule ?

102mardi 8 janvier 13

Page 136: Secure Coding for Java

What is security code review ?

It’s a tools driven review of your code.

Security Code Review imply :

• Source code access

• Business document access

• Configuration access

103mardi 8 janvier 13

Page 137: Secure Coding for Java

SQL Injection ?

104mardi 8 janvier 13

Page 138: Secure Coding for Java

Injection code

105mardi 8 janvier 13

Page 139: Secure Coding for Java

106

False  Posi5ve False  Nega5ve Didn’t  find

Code  Review 1 1 1

Test 3 3 5

A voir : http://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

mardi 8 janvier 13

Page 140: Secure Coding for Java

106

False  Posi5ve False  Nega5ve Didn’t  find

Code  Review 1 1 1

Test 3 3 5

A voir : http://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

mardi 8 janvier 13

Page 141: Secure Coding for Java

XSS

107mardi 8 janvier 13

Page 142: Secure Coding for Java

108

False  Posi5ve False  Nega5ve Didn’t  find

Code  Review 2 2 2

Test 5 3 1

A voir : http://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

mardi 8 janvier 13

Page 143: Secure Coding for Java

108

False  Posi5ve False  Nega5ve Didn’t  find

Code  Review 2 2 2

Test 5 3 1

A voir : http://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

mardi 8 janvier 13

Page 144: Secure Coding for Java

Common AuthN & Session Mgt Reqts

109mardi 8 janvier 13

Page 145: Secure Coding for Java

Both Have Their Advantages

110

Pen Testing Pros

• Requires less specialized expertise

• Easier setup

• Easier to perform

• Exercises the entire app infrastructure

• Proves vulnerabilities

Code Review Pros

•Easier to

•Find all the content

•Find all instances of certain types of flaws

•Verify controls are correct

•Verify controls are used in all the required places

mardi 8 janvier 13

Page 146: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Tools

mardi 8 janvier 13

Page 147: Secure Coding for Java

LAPSE+ is a eclipse plugin to static analysis of code for detecting vulnerabilities of untrusted data injection in Java EE Applications.

LAPSE+ is inspired by existing lightweight security auditing tools such as FlawFinder.

Developed by Group of Stanford University.

GPL Software.

112mardi 8 janvier 13

Page 148: Secure Coding for Java

LAPSE+ Vulnerabilities Detected

URL Tampering

Cookie Poisoning

Parameter Tampering

Header Manipulation

Cross-site Scripting (XSS)

HTTP Response Splitting

Injections (SQL, Command, XPath, XML, LDAP)

Path Traversal113

mardi 8 janvier 13

Page 149: Secure Coding for Java

114mardi 8 janvier 13

Page 150: Secure Coding for Java

115mardi 8 janvier 13

Page 151: Secure Coding for Java

CodePro on ePoney

116mardi 8 janvier 13

Page 152: Secure Coding for Java

The OWASP Foundationhttp://www.owasp.org

Demo

mardi 8 janvier 13

Page 153: Secure Coding for Java

Now you can protect against him

118mardi 8 janvier 13

Page 154: Secure Coding for Java

License

119mardi 8 janvier 13