SlideShare a Scribd company logo
The OWASP Foundation
http://www.owasp.org
Escape ’Attacks!’
India, Kerala
2015
Rajesh P
Board Member, OWASP Kerala
Copyright © The OWASP Foundation
Permission is granted to copy, distribute and/or modify the document under the terms of the OWASP License
All trademarks, service marks, trade names, product names and logos appearing on the slides are the property of their respective owners
Secure Coding
Practice Series
Parse what you code
The OWASP Foundation
http://www.owasp.org
2
The OWASP Foundation
http://www.owasp.org
• Developer approaches application
based on what it is intended to do
• Attacker’s approach is based on
what application can be made to do
• Any action not specifically denied is
considered allowed
3
Fundamental
difference
The OWASP Foundation
http://www.owasp.org
• Minimize Attack Surface Area
• Secure Defaults
• Principle of Least Privilege
• Principle of Defense in Depth
• Fail Securely
• External Systems are Insecure
• Separation of Duties
• Do not trust Security through Obscurity
• Simplicity
• Fix Security Issues Correctly
4
Security
Principles
The OWASP Foundation
http://www.owasp.org
• Price related hidden fields, CSS visibility –
perform server side validation
• Cross Site Request Forgery (CSRF)
• Sensitive Information Disclosure via Client-
Side Storage and Comments
• Hardcoded domain in HTML
• HTML5: Form validation turned off
• Password Submission using GET method
5
HTML
The OWASP Foundation
http://www.owasp.org
• Selects, radio buttons, and checkboxes
Wrong Approach
<input type="radio" name="acctNo"
value="455712341234">Gold Card
<input type="radio" name="acctNo"
value="455712341235">Platinum Card
String acctNo = getParameter('acctNo');
String sql = "SELECT acctBal FROM accounts
WHERE acctNo = '?'"; 6
HTML
The OWASP Foundation
http://www.owasp.org
Right Approach
<input type="radio" name="acctIndex"
value="1" />Gold Credit Card
<input type="radio" name="acctIndex"
value="2" />Platinum Credit Card
String acctNo =
acct.getCardNumber(getParameter('acctIndex'))
String sql = "SELECT acctBal FROM accounts
WHERE acct_id = '?' AND acctNo ='?'";
7
HTML
The OWASP Foundation
http://www.owasp.org
• Display of passwords in form, Autocomplete
• Don’t populate password in form
<input name="password"
type="password" value="<%=pass%>" />
8
HTML
The OWASP Foundation
http://www.owasp.org
• Ajax Hijacking
• Cross Site Scripting: DOM, Poor validation
• Dynamic code evaluation: Code, Script
Injection, Unsafe XMLHTTPRequest – eval
• Open Redirect
• Path Manipulation – dot dot slash attack
• Obfuscate Client Side JavaScript. Remember
the jQuery.min, jQuery.dev versions
9
JavaScript
The OWASP Foundation
http://www.owasp.org
• jQuery
Unsafe usage
var txtAlertMsg = "Hello World: ";
var txtUserInput =
"test<script>alert(1)</script>";
$("#message").html( txtAlertMsg +"" +
txtUserInput + "");
Safe usage (use text, not html)
$("#userInput").text(
"test<script>alert(1)</script>"); <-- treat
user input as text 10
JavaScript
The OWASP Foundation
http://www.owasp.org
• Use of =, != for null comparison
• Ignoring exception – try & catch
• Persistent Cross Site Scripting
• Use parameterized statements, validate
input before string concatenation in dynamic
SQL’s in stored procedures
• Avoid xp_cmdshell
• Never store passwords in plaintext
11
SQL
The OWASP Foundation
http://www.owasp.org
• Use stored procedures to abstract
data access and allow for the
removal of permissions to the base
tables in the database
12
SQL
The OWASP Foundation
http://www.owasp.org
• The Java libraries (java.lang, java.util etc, often
referred to as the Java API) are themselves written
in Java, although methods marked as native. The
Sun JVM is written in C, JVM running on your
machine is a platform-dependent executable and
hence could have been originally written in any
language. The Oracle JVM (HotSpot) is written in
the C++ programming language. Java Compiler
provided By Oracle is written in JAVA itself. Many
Java vulnerabilities are really C vulnerabilities that
occur in an implementation of Java.
13
About Java
The OWASP Foundation
http://www.owasp.org
• Secure data types – char[], GuardedString
• Zip Bombs
private static final int LINE_LIMIT = 1000000;
int totalLinesRead = 0;
while ((s = reader.readLine()) != null) {
doSomethingWithLine(s);
totalLinesRead++;
if (totalLinesRead > LINE_LIMIT) {
throw new Exception("File being read is too big.");
}
}
14
Java
The OWASP Foundation
http://www.owasp.org
• Do not ignore values returned by methods.
private void deleteFile()
{
File tempFile = new File(tempFileName);
if (tempFile.exists()) {
if (!tempFile.delete()) {
// handle failure to delete the
file
}
}
}
15
Java
The OWASP Foundation
http://www.owasp.org
• Release resources in all cases. The try-with-
resource syntax introduced in Java SE 7
automatically handles the release of many
resource types.
try (final InputStream in =
Files.newInputStream(path)) {
handler.handle(new
BufferedInputStream(in));
}
16
Java - DOS
The OWASP Foundation
http://www.owasp.org
• Billion laughs attack - XML entity expansion
causes an XML document to grow
dramatically during parsing.
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSI
NG, true);
DocumentBuilder parser = dbf.newDocumentBuilder();
parser.parse(xmlfile);
17
Java
The OWASP Foundation
http://www.owasp.org
• Add security wrapper around native method
calls – use JNI defensively
• Make public static fields final
• java.lang.SecurityManager – policy
• In Struts deny direct jsp access explicitly
• Use SecureRandom for PRNG, 128 bit length
SecureRandom random = new
SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);
18
Java
The OWASP Foundation
http://www.owasp.org
• JSP Source code disclosure
• Non-Final classes let an attacker extend a
class in a malicious manner
• Packages are by default open, not sealed,
which means a rogue class can be added to
your package
• Check uploaded file header than just
extension alone
https://www.owasp.org/images/0/08/OWASP_S
CP_Quick_Reference_Guide_v2.pdf
19
Java
The OWASP Foundation
http://www.owasp.org
• Override the clone method to make classes
unclonable unless required. Cloning allows
an attacker to instantiate a class without
running any of the class constructors.
20
Java Cloning
The OWASP Foundation
http://www.owasp.org
• Define the following method in each of your
classes:
public final Object clone() throws
java.lang.CloneNotSupportedException {
throw new
java.lang.CloneNotSupportedException();
}
21
Java Cloning
The OWASP Foundation
http://www.owasp.org
• If a clone is required, one can make one’s
clone method immune to overriding by using
the final keyword:
public final Object clone() throws
java.lang.CloneNotSupportedException {
return super.clone();
}
22
Java Cloning
The OWASP Foundation
http://www.owasp.org
• Unfavour serialization of objects containing
sensitive information – transient fields
private final void
writeObject(ObjectOutputStream out)
throws java.io.IOException {
throw new java.io.IOException("Object cannot
be serialized");
}
23
Java Serialization
The OWASP Foundation
http://www.owasp.org
• Prevent deserialization of objects containing
sensitive information
private final void
readObject(ObjectInputStream in)
throws java.io.IOException {
throw new java.io.IOException("Class cannot
be deserialized");
}
24
Java Deserialization
The OWASP Foundation
http://www.owasp.org
• deny access by default
isAdmin = false;
try {
codeWhichMayFail();
isAdmin = isUserInRole(“Administrator”);
}
catch (Exception ex) {
log.write(ex.toString());
}
25
Java
The OWASP Foundation
http://www.owasp.org
26
Return after
sendRedirect
The OWASP Foundation
http://www.owasp.org
• Response splitting allows an attacker to take
control of the response body by adding extra
CRLFs into headers
String author = request.getParameter(AUTHOR_PARAM);
...
Cookie cookie = new Cookie("author", author);
cookie.setMaxAge(cookieExpiration);
response.addCookie(cookie);
27
Response Splitting
The OWASP Foundation
http://www.owasp.org
If an attacker submits a malicious string, such as “Rajesh
PrnHTTP/1.1 200 OKrn...", then the HTTP response would
be split into two responses of the following form:
HTTP/1.1 200 OK
...
Set-Cookie: author=Rajesh P
HTTP/1.1 200 OK
...
Clearly, the second response is completely controlled by the
attacker and can be constructed with any header and body
content desired.
Response Splitting
The OWASP Foundation
http://www.owasp.org
Attacker Proxy
Web
Server
302
302
200
(Gotcha!)
1st attacker request
(response splitter)
1st attacker request
(response splitter)
request
/account?id=victim
200
(Gotcha!)
200
(Victim’s account data)
Victim
request
/index.html
request
/index.html
200
(Victim’s account data)
Response Splitting
The OWASP Foundation
http://www.owasp.org
• How to Identify new vulnerability disclosures
in Java? – NVD, CVE
• Always remove older versions of Java on
devices while updating to the new secure
version
30
Miscellaneous
The OWASP Foundation
http://www.owasp.org
The OWASP Enterprise
Security API
Custom Enterprise Web Application
Enterprise Security API
Authenticator
User
AccessController
AccessReferenceMap
Validator
Encoder
HTTPUtilities
Encryptor
EncryptedProperties
Randomizer
ExceptionHandling
Logger
IntrusionDetector
SecurityConfiguration
Existing Enterprise Security Services/Libraries
31
The OWASP Foundation
http://www.owasp.org
Validate:
getValidDate()
getValidCreditCard()
getValidInput()
getValidNumber()
…
Validating Untrusted
Input / Output
BackendController Business
Functions
User Data Layer
Presentation
Layer
Validate:
getValidDate()
getValidCreditCard()
getValidSafeHTML()
getValidInput()
getValidNumber()
getValidFileName()
getValidRedirect()
safeReadLine()
…
Validation
Engine
Validation
Engine
The OWASP Foundation
http://www.owasp.org
OWASP Top Ten
Coverage
33
OWASP Top Ten
A1. Cross Site Scripting (XSS)
A2. Injection Flaws
A3. Malicious File Execution
A4. Insecure Direct Object Reference
A5. Cross Site Request Forgery (CSRF)
A6. Leakage and Improper Error Handling
A7. Broken Authentication and Sessions
A8. Insecure Cryptographic Storage
A9. Insecure Communications
A10. Failure to Restrict URL Access
OWASP ESAPI
Validator, Encoder
Encoder
HTTPUtilities (upload)
AccessReferenceMap
User (csrftoken)
EnterpriseSecurityException, HTTPUtils
Authenticator, User, HTTPUtils
Encryptor
HTTPUtilities (secure cookie, channel)
AccessController
The OWASP Foundation
http://www.owasp.org
• Disgruntled staff
• Unintentional program execution
• Identify Training need, Certification
• Urgent and Frequent patches
• Selection of Third Party Libraries
• “Drive by” attacks, such as side
effects or direct consequences of a
virus, worm or Trojan attack
34
Why Static
Code Analysis
The OWASP Foundation
http://www.owasp.org
• Categories of Vulnerability Sources
• URL, Parameter Tampering
• Header Manipulation
• Cookie Poisoning
• Categories of Vulnerability Sinks
• SQL, XPath, XML, LDAP Injection
• Cross-site Scripting
• HTTP Response Splitting
• Command Injection
• Path Traversal
35
LAPSE+
Static Code Analysis
The OWASP Foundation
http://www.owasp.org
36
Free Static Analysis
Tools
The OWASP Foundation
http://www.owasp.org
Thank you!
Until next time, stay secure!
rajesh.nair@owasp.or
g
https://www.facebook.com/OWASPKerala
https://www.twitter.com/owasp_kerala

More Related Content

PPTX
Cross Site Scripting ( XSS)
PDF
Secure code
PDF
How to steal and modify data using Business Logic flaws - Insecure Direct Obj...
PDF
Android Security & Penetration Testing
PDF
Time based CAPTCHA protected SQL injection through SOAP-webservice
PDF
CSRF, ClickJacking & Open Redirect
PDF
Secure PHP Coding
PDF
Local File Inclusion to Remote Code Execution
Cross Site Scripting ( XSS)
Secure code
How to steal and modify data using Business Logic flaws - Insecure Direct Obj...
Android Security & Penetration Testing
Time based CAPTCHA protected SQL injection through SOAP-webservice
CSRF, ClickJacking & Open Redirect
Secure PHP Coding
Local File Inclusion to Remote Code Execution

What's hot (20)

PPSX
Broken Authentication & authorization
PDF
Bug Bounty Hunter Methodology - Nullcon 2016
PDF
JCR In 10 Minutes
PPTX
Secure coding guidelines
PPTX
Reverse proxies & Inconsistency
PDF
Threat Hunting Workshop
PDF
Secure Coding for Java
PPTX
Secure coding practices
PDF
OpenSearch.pdf
PDF
"CERT Secure Coding Standards" by Dr. Mark Sherman
PPT
Top 10 Web Security Vulnerabilities (OWASP Top 10)
PDF
Hunting for security bugs in AEM webapps
PDF
OWASP Top 10 Web Application Vulnerabilities
PDF
PDF
Livro - código limpo caps (3,4) (clean code)
PDF
Frans Rosén Keynote at BSides Ahmedabad
PPTX
Xss attack
PDF
Railway Oriented Programming
PPTX
개발팀을 위한 소통과 협업스킬
PDF
Serverless Security: Are you ready for the Future?
Broken Authentication & authorization
Bug Bounty Hunter Methodology - Nullcon 2016
JCR In 10 Minutes
Secure coding guidelines
Reverse proxies & Inconsistency
Threat Hunting Workshop
Secure Coding for Java
Secure coding practices
OpenSearch.pdf
"CERT Secure Coding Standards" by Dr. Mark Sherman
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Hunting for security bugs in AEM webapps
OWASP Top 10 Web Application Vulnerabilities
Livro - código limpo caps (3,4) (clean code)
Frans Rosén Keynote at BSides Ahmedabad
Xss attack
Railway Oriented Programming
개발팀을 위한 소통과 협업스킬
Serverless Security: Are you ready for the Future?
Ad

Viewers also liked (12)

PPTX
EC-Council Secure Programmer Java
PDF
JBoss Negotiation in AS7
PPTX
Jar signing
PDF
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
PDF
Java Security Manager Reloaded - jOpenSpace Lightning Talk
PPTX
Security Architecture of the Java Platform (http://www.javaday.bg event - 14....
PPT
Java security
PPTX
Security Architecture of the Java platform
ODP
OWASP Secure Coding
PDF
CIS14: Best Practices You Must Apply to Secure Your APIs
PPTX
Deep dive into Java security architecture
PDF
Javantura v4 - Security architecture of the Java platform - Martin Toshev
EC-Council Secure Programmer Java
JBoss Negotiation in AS7
Jar signing
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Java Security Manager Reloaded - jOpenSpace Lightning Talk
Security Architecture of the Java Platform (http://www.javaday.bg event - 14....
Java security
Security Architecture of the Java platform
OWASP Secure Coding
CIS14: Best Practices You Must Apply to Secure Your APIs
Deep dive into Java security architecture
Javantura v4 - Security architecture of the Java platform - Martin Toshev
Ad

Similar to Java Secure Coding Practices (20)

PPTX
Application Security Vulnerabilities: OWASP Top 10 -2007
PDF
Web Application Security 101
PDF
Xebia Knowledge Exchange - Owasp Top Ten
PDF
OWASP Top 10 2007 for JavaEE
PPTX
OWASP -Top 5 Jagjit
PPTX
Top Ten Java Defense for Web Applications v2
PPTX
OWASP_Top_Ten_Proactive_Controls_v32.pptx
PDF
OWASP Top 10 (2010 release candidate 1)
PPTX
OWASP_Top_Ten_Proactive_Controls_v2.pptx
PPTX
OWASP_Top_Ten_Proactive_Controls_v2.pptx
PPTX
OWASP_Top_Ten_Proactive_Controls version 2
PPTX
OWASP_Top_Ten_Proactive_Controls_v2.pptx
PDF
Security Awareness
PPTX
OWASP top 10-2013
PPT
OWASP_Top_10_Introduction_and_Remedies_2017.ppt
PPTX
OWASP Top Ten 2017
PDF
OWASP Top 10 List Overview for Web Developers
PPT
OWASP Top10 2010
PDF
Application Security around OWASP Top 10
Application Security Vulnerabilities: OWASP Top 10 -2007
Web Application Security 101
Xebia Knowledge Exchange - Owasp Top Ten
OWASP Top 10 2007 for JavaEE
OWASP -Top 5 Jagjit
Top Ten Java Defense for Web Applications v2
OWASP_Top_Ten_Proactive_Controls_v32.pptx
OWASP Top 10 (2010 release candidate 1)
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls version 2
OWASP_Top_Ten_Proactive_Controls_v2.pptx
Security Awareness
OWASP top 10-2013
OWASP_Top_10_Introduction_and_Remedies_2017.ppt
OWASP Top Ten 2017
OWASP Top 10 List Overview for Web Developers
OWASP Top10 2010
Application Security around OWASP Top 10

Recently uploaded (20)

PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
UNIT 4 Total Quality Management .pptx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
Construction Project Organization Group 2.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Sustainable Sites - Green Building Construction
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PPT
Mechanical Engineering MATERIALS Selection
PDF
Well-logging-methods_new................
PPTX
Welding lecture in detail for understanding
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
additive manufacturing of ss316l using mig welding
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
web development for engineering and engineering
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
UNIT 4 Total Quality Management .pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Lecture Notes Electrical Wiring System Components
Construction Project Organization Group 2.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Sustainable Sites - Green Building Construction
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Arduino robotics embedded978-1-4302-3184-4.pdf
Mechanical Engineering MATERIALS Selection
Well-logging-methods_new................
Welding lecture in detail for understanding
OOP with Java - Java Introduction (Basics)
additive manufacturing of ss316l using mig welding
UNIT-1 - COAL BASED THERMAL POWER PLANTS
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
web development for engineering and engineering
Lesson 3_Tessellation.pptx finite Mathematics
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk

Java Secure Coding Practices

  • 1. The OWASP Foundation http://www.owasp.org Escape ’Attacks!’ India, Kerala 2015 Rajesh P Board Member, OWASP Kerala Copyright © The OWASP Foundation Permission is granted to copy, distribute and/or modify the document under the terms of the OWASP License All trademarks, service marks, trade names, product names and logos appearing on the slides are the property of their respective owners Secure Coding Practice Series Parse what you code
  • 3. The OWASP Foundation http://www.owasp.org • Developer approaches application based on what it is intended to do • Attacker’s approach is based on what application can be made to do • Any action not specifically denied is considered allowed 3 Fundamental difference
  • 4. The OWASP Foundation http://www.owasp.org • Minimize Attack Surface Area • Secure Defaults • Principle of Least Privilege • Principle of Defense in Depth • Fail Securely • External Systems are Insecure • Separation of Duties • Do not trust Security through Obscurity • Simplicity • Fix Security Issues Correctly 4 Security Principles
  • 5. The OWASP Foundation http://www.owasp.org • Price related hidden fields, CSS visibility – perform server side validation • Cross Site Request Forgery (CSRF) • Sensitive Information Disclosure via Client- Side Storage and Comments • Hardcoded domain in HTML • HTML5: Form validation turned off • Password Submission using GET method 5 HTML
  • 6. The OWASP Foundation http://www.owasp.org • Selects, radio buttons, and checkboxes Wrong Approach <input type="radio" name="acctNo" value="455712341234">Gold Card <input type="radio" name="acctNo" value="455712341235">Platinum Card String acctNo = getParameter('acctNo'); String sql = "SELECT acctBal FROM accounts WHERE acctNo = '?'"; 6 HTML
  • 7. The OWASP Foundation http://www.owasp.org Right Approach <input type="radio" name="acctIndex" value="1" />Gold Credit Card <input type="radio" name="acctIndex" value="2" />Platinum Credit Card String acctNo = acct.getCardNumber(getParameter('acctIndex')) String sql = "SELECT acctBal FROM accounts WHERE acct_id = '?' AND acctNo ='?'"; 7 HTML
  • 8. The OWASP Foundation http://www.owasp.org • Display of passwords in form, Autocomplete • Don’t populate password in form <input name="password" type="password" value="<%=pass%>" /> 8 HTML
  • 9. The OWASP Foundation http://www.owasp.org • Ajax Hijacking • Cross Site Scripting: DOM, Poor validation • Dynamic code evaluation: Code, Script Injection, Unsafe XMLHTTPRequest – eval • Open Redirect • Path Manipulation – dot dot slash attack • Obfuscate Client Side JavaScript. Remember the jQuery.min, jQuery.dev versions 9 JavaScript
  • 10. The OWASP Foundation http://www.owasp.org • jQuery Unsafe usage var txtAlertMsg = "Hello World: "; var txtUserInput = "test<script>alert(1)</script>"; $("#message").html( txtAlertMsg +"" + txtUserInput + ""); Safe usage (use text, not html) $("#userInput").text( "test<script>alert(1)</script>"); <-- treat user input as text 10 JavaScript
  • 11. The OWASP Foundation http://www.owasp.org • Use of =, != for null comparison • Ignoring exception – try & catch • Persistent Cross Site Scripting • Use parameterized statements, validate input before string concatenation in dynamic SQL’s in stored procedures • Avoid xp_cmdshell • Never store passwords in plaintext 11 SQL
  • 12. The OWASP Foundation http://www.owasp.org • Use stored procedures to abstract data access and allow for the removal of permissions to the base tables in the database 12 SQL
  • 13. The OWASP Foundation http://www.owasp.org • The Java libraries (java.lang, java.util etc, often referred to as the Java API) are themselves written in Java, although methods marked as native. The Sun JVM is written in C, JVM running on your machine is a platform-dependent executable and hence could have been originally written in any language. The Oracle JVM (HotSpot) is written in the C++ programming language. Java Compiler provided By Oracle is written in JAVA itself. Many Java vulnerabilities are really C vulnerabilities that occur in an implementation of Java. 13 About Java
  • 14. The OWASP Foundation http://www.owasp.org • Secure data types – char[], GuardedString • Zip Bombs private static final int LINE_LIMIT = 1000000; int totalLinesRead = 0; while ((s = reader.readLine()) != null) { doSomethingWithLine(s); totalLinesRead++; if (totalLinesRead > LINE_LIMIT) { throw new Exception("File being read is too big."); } } 14 Java
  • 15. The OWASP Foundation http://www.owasp.org • Do not ignore values returned by methods. private void deleteFile() { File tempFile = new File(tempFileName); if (tempFile.exists()) { if (!tempFile.delete()) { // handle failure to delete the file } } } 15 Java
  • 16. The OWASP Foundation http://www.owasp.org • Release resources in all cases. The try-with- resource syntax introduced in Java SE 7 automatically handles the release of many resource types. try (final InputStream in = Files.newInputStream(path)) { handler.handle(new BufferedInputStream(in)); } 16 Java - DOS
  • 17. The OWASP Foundation http://www.owasp.org • Billion laughs attack - XML entity expansion causes an XML document to grow dramatically during parsing. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSI NG, true); DocumentBuilder parser = dbf.newDocumentBuilder(); parser.parse(xmlfile); 17 Java
  • 18. The OWASP Foundation http://www.owasp.org • Add security wrapper around native method calls – use JNI defensively • Make public static fields final • java.lang.SecurityManager – policy • In Struts deny direct jsp access explicitly • Use SecureRandom for PRNG, 128 bit length SecureRandom random = new SecureRandom(); byte bytes[] = new byte[20]; random.nextBytes(bytes); 18 Java
  • 19. The OWASP Foundation http://www.owasp.org • JSP Source code disclosure • Non-Final classes let an attacker extend a class in a malicious manner • Packages are by default open, not sealed, which means a rogue class can be added to your package • Check uploaded file header than just extension alone https://www.owasp.org/images/0/08/OWASP_S CP_Quick_Reference_Guide_v2.pdf 19 Java
  • 20. The OWASP Foundation http://www.owasp.org • Override the clone method to make classes unclonable unless required. Cloning allows an attacker to instantiate a class without running any of the class constructors. 20 Java Cloning
  • 21. The OWASP Foundation http://www.owasp.org • Define the following method in each of your classes: public final Object clone() throws java.lang.CloneNotSupportedException { throw new java.lang.CloneNotSupportedException(); } 21 Java Cloning
  • 22. The OWASP Foundation http://www.owasp.org • If a clone is required, one can make one’s clone method immune to overriding by using the final keyword: public final Object clone() throws java.lang.CloneNotSupportedException { return super.clone(); } 22 Java Cloning
  • 23. The OWASP Foundation http://www.owasp.org • Unfavour serialization of objects containing sensitive information – transient fields private final void writeObject(ObjectOutputStream out) throws java.io.IOException { throw new java.io.IOException("Object cannot be serialized"); } 23 Java Serialization
  • 24. The OWASP Foundation http://www.owasp.org • Prevent deserialization of objects containing sensitive information private final void readObject(ObjectInputStream in) throws java.io.IOException { throw new java.io.IOException("Class cannot be deserialized"); } 24 Java Deserialization
  • 25. The OWASP Foundation http://www.owasp.org • deny access by default isAdmin = false; try { codeWhichMayFail(); isAdmin = isUserInRole(“Administrator”); } catch (Exception ex) { log.write(ex.toString()); } 25 Java
  • 27. The OWASP Foundation http://www.owasp.org • Response splitting allows an attacker to take control of the response body by adding extra CRLFs into headers String author = request.getParameter(AUTHOR_PARAM); ... Cookie cookie = new Cookie("author", author); cookie.setMaxAge(cookieExpiration); response.addCookie(cookie); 27 Response Splitting
  • 28. The OWASP Foundation http://www.owasp.org If an attacker submits a malicious string, such as “Rajesh PrnHTTP/1.1 200 OKrn...", then the HTTP response would be split into two responses of the following form: HTTP/1.1 200 OK ... Set-Cookie: author=Rajesh P HTTP/1.1 200 OK ... Clearly, the second response is completely controlled by the attacker and can be constructed with any header and body content desired. Response Splitting
  • 29. The OWASP Foundation http://www.owasp.org Attacker Proxy Web Server 302 302 200 (Gotcha!) 1st attacker request (response splitter) 1st attacker request (response splitter) request /account?id=victim 200 (Gotcha!) 200 (Victim’s account data) Victim request /index.html request /index.html 200 (Victim’s account data) Response Splitting
  • 30. The OWASP Foundation http://www.owasp.org • How to Identify new vulnerability disclosures in Java? – NVD, CVE • Always remove older versions of Java on devices while updating to the new secure version 30 Miscellaneous
  • 31. The OWASP Foundation http://www.owasp.org The OWASP Enterprise Security API Custom Enterprise Web Application Enterprise Security API Authenticator User AccessController AccessReferenceMap Validator Encoder HTTPUtilities Encryptor EncryptedProperties Randomizer ExceptionHandling Logger IntrusionDetector SecurityConfiguration Existing Enterprise Security Services/Libraries 31
  • 32. The OWASP Foundation http://www.owasp.org Validate: getValidDate() getValidCreditCard() getValidInput() getValidNumber() … Validating Untrusted Input / Output BackendController Business Functions User Data Layer Presentation Layer Validate: getValidDate() getValidCreditCard() getValidSafeHTML() getValidInput() getValidNumber() getValidFileName() getValidRedirect() safeReadLine() … Validation Engine Validation Engine
  • 33. The OWASP Foundation http://www.owasp.org OWASP Top Ten Coverage 33 OWASP Top Ten A1. Cross Site Scripting (XSS) A2. Injection Flaws A3. Malicious File Execution A4. Insecure Direct Object Reference A5. Cross Site Request Forgery (CSRF) A6. Leakage and Improper Error Handling A7. Broken Authentication and Sessions A8. Insecure Cryptographic Storage A9. Insecure Communications A10. Failure to Restrict URL Access OWASP ESAPI Validator, Encoder Encoder HTTPUtilities (upload) AccessReferenceMap User (csrftoken) EnterpriseSecurityException, HTTPUtils Authenticator, User, HTTPUtils Encryptor HTTPUtilities (secure cookie, channel) AccessController
  • 34. The OWASP Foundation http://www.owasp.org • Disgruntled staff • Unintentional program execution • Identify Training need, Certification • Urgent and Frequent patches • Selection of Third Party Libraries • “Drive by” attacks, such as side effects or direct consequences of a virus, worm or Trojan attack 34 Why Static Code Analysis
  • 35. The OWASP Foundation http://www.owasp.org • Categories of Vulnerability Sources • URL, Parameter Tampering • Header Manipulation • Cookie Poisoning • Categories of Vulnerability Sinks • SQL, XPath, XML, LDAP Injection • Cross-site Scripting • HTTP Response Splitting • Command Injection • Path Traversal 35 LAPSE+ Static Code Analysis
  • 37. The OWASP Foundation http://www.owasp.org Thank you! Until next time, stay secure! rajesh.nair@owasp.or g https://www.facebook.com/OWASPKerala https://www.twitter.com/owasp_kerala