2. 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
3. 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.
4. Information Leakage and improper error
handling
Definition: Providing too much information to the
user when an error occurs.
Examples:
An error message with too much detail
Stack trace
Failed SQL statement
Functions that produce different error messages/codes
based upon different inputs
Invalid username
Invalid password
5. Information Leakage and improper error
handling Protection
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>
Always give generic error;
“The username/password is not correct”.
“Merchant Authentication Failed”
6. Cross Site Scripting (XSS)
XSS: Describes the act of embedding malicious
HTML/JavaScript code in dynamically generated
pages based on invalidated input from untrustworthy
sources.
7. Cross Site Scripting (XSS)
XSS is the most common vulnerability
XSS impact:
Data on a page can be stolen and sent anywhere.
Your Website behavior can be altered.
Types of XSS
Reflected XSS; reflects user input (manipulate user input)
out.writeln(“You input is:”+request.getParamter(“userInput”))
Stored XSS; attackers script is stored on server (e.g.
blogs)
out.writeln(“Comment: ”+blog.comment);
8. Cross Site Scripting (XSS) Protection
Input Validation; Checking each input for validity
Accept known good:
Accept valid input types.
Accept valid input lengths.
Accept valid input patterns; e.g., phone pattern.
Reject known bad
Reject input values with bad characters and patterns; for
example: <script>
Sanitize
Rather than accept or reject input, change the input to an
acceptable format.
Set the HTTPOnly flag on your session cookie
Cookie with this flag cannot be accessed through client
script
9. Cross-Site Scripting (XSS) Protection
Output Escaping (Encoding): is a technique used to
ensure that characters are treated as data, not as
characters that are relevant to the interpreter's
parser.
HTML Escape: <body>...ESCAPE UNTRUSTED DATA BEFORE
PUTTING HERE...</body>
(& &) (< <) (> >) (“ ") („
' ) (/ /)
Attribute Escape: <div attr='...ESCAPE UNTRUSTED DATA BEFORE
PUTTING HERE...'>content</div>
Javascript Escape: <script>x='...ESCAPE UNTRUSTED DATA
BEFORE PUTTING HERE...'</script>
CSS Escape
URL Escape: <a
href="http://www.somesite.com?test=...ESCAPE UNTRUSTED
DATA BEFORE PUTTING HERE...">link</a >
10. Cross-Site Scripting (XSS) Protection
Input Validation using ESAPI:
boolean isValidFirstName =
ESAPI.validator().isValidInput("FirstName",
request.getParameter("FirstName"), "FirstNameRegex", 255,
false);
Sanitize using AntiSamy
import org.owasp.validator.html.*;
Policy policy =
Policy.getInstance(POLICY_FILE_LOCATION);
AntiSamy as = new AntiSamy();
CleanResults cr = as.scan(dirtyInput, policy);
MyUserDAO.storeUserProfile(cr.getCleanHTML());
11. Cross-Site Scripting (XSS) Protection
Set HttpOnly
Before Servlet v3:
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid +
"; HttpOnly");
Servlet v3:
<session-config>
<cookie-config>
<http-only>true</http-only>
</cookie-config>
<session-config>
Output Escaping using ESAPI:
<p>Hello, <%=name%></p>
//performing output encoding for the HTML context String
<p>Hello, <%=ESAPI.encoder().encodeForHTML(name)%></p>
12. Injection Flaws
Definition: Attacker modifies a query/command that
is executed by target interpreter
Injection applies to:
SQL injection
XPATH injection
LDAP injection
13. Injection Flaws
SQL Injection:
SQL Statement for Authentication: StringsqlString =
"SELECT * FROM users WHERE fullname = '" +
form.getFullName() + "' AND password = '" +
form.getPassword() + "'";
User Input:
Case 1: full name: Haitham, password: 123pass
Result: SELECT * FROM users WHERE username = „Haitham'
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: blah, password: ' OR '1' = '1
Result: SELECT * FROM users WHERE username = 'blah' AND
password = '' OR '1' = '1'
15. Injection Flaws Protection
SQL Injection Protection using:
Use prepared statements/parameterized queries (don‟t use
concatenation while building the SQL stmt)
String stmt = “select * from emp where id=?”;
PreparedStatement pstmt = con.prepareStatement(stmt);
pstmt.setString(1, empId);
Use stored procedures
SQL Escape using ESAPI
Codec ORACLE_CODEC = new OracleCodec();
String query = "SELECT name FROM users WHERE id = "+
ESAPI.encoder().encodeForSQL(ORACLE_CODEC, userId)+
" AND date_created >= '"+
ESAPI.encoder().encodeForSQL(ORACLE_CODEC, date)+
"'";
myStmt = conn.createStatement(query);
17. Injection Flaws Protection
XPATH Injection Protection
User input must not contain any of the following
characters:
( ) = ' [ ] : , * / WHITESPACE
XPATH Injection protection using ESAPI
String exp = “/employees/employee[@id=„”+
ESAPI.encoder().encodeForXPath(form.getEID())+
”']”
18. Malicious File Execution
Definition: occurs when attacker's files are executed
or processed by the web server.
Expected Threats:
Malicious file (e.g., script) can be executed on the
application server
Access to a configuration file
Override a configuration file
Fill up the filesystem
This happen when
Filename is accepted from the user without validation
File is uploaded without validation
19. Malicious File Execution
Example:
Code Snippet
// get the absolute file path on the server's filesystem
String dir =
servlet.getServletContext().getRealPath("/ebanking")
// get input file name
String file = request.getParameter(“file”);
// Create a new File instance from pathname string
File f = new File((dir + "" + file).replaceAll("",
"/"));
User Input: ../../web.xml
Result: it will allow access to web server configuration file
20. Malicious File Execution Protection
Filename Validation
File Type Validation
Size Validation
Don‟t allow the user to influence the final filename.
Upload files to a destination outside of the web
application directory
21. Malicious File Execution Protection
Filename and file type validation using ESAPI
ESAPI.validator().isValidFileName("upload", filename,
allowedExtensions, false));
Size Validation using Commons-FileUpload:
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxBytes);
22. Direct Object References (DOR)
DOR occurs when a developer exposes a reference
to an internal implementation:
Object
File or Directory
Database record
Attacker can manipulate object references to access
other objects without authorization.
For Example:
URL (or form parameter) to my banking account is:
/accounts/viewDetail?id=3540
What will happen if I changed this to
/accounts/viewDetail?id=3541
23. Direct Object References (DOR) Protection
Avoid exposing direct object references
Use Indirect Object References
Verify Authorization to all referenced objects
24. Direct Object References (DOR) Protection
Indirect Object Reference using ESAPI
//create ESAPI random access reference map
AccessReferenceMap map = new
RandomAccessReferenceMap();
//get indirect reference using direct reference
String indirectReference =
map.addDirectReference(obj.getId());
//set indirect reference for each object - requires
your app object to have this method
obj.setIndirectReference(indirectReference);
// Store the map in the session
25. Direct Object References (DOR) Protection
Verify Authorization
For example:
Before: select * from accounts where accNum = ?
After: select * from accounts where accNum = ? And userId = ?
26. Direct Object References (DOR) Protection
Authorization 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
27. Cross Site Request Forgery (CSRF)
CSRF: forces logged-in victim to send a request to a
vulnerable web application, which then performs
action on behalf of the victim.
Sample CSRF Scenario:
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 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
28. Cross Site Request Forgery (CSRF)
Protection
Make sure there are no XSS vulnerabilities in your
application; refer to XSS protection slides.
Do not use GET requests to perform transactional
operations.
Javascript can be used to create auto submit POST
forms.
Check the referrer header. Shows where the request
originated
This is optional and the user can disable it.
For sensitive transactions, re-authenticate.
Add a confirmation page.
29. Cross Site Request Forgery (CSRF)
Protection
Insert custom random tokens into every form and
URL
Generate CSRF token
Store user in http session
On any form/URL add the token as a parameter/hidden
field.
On the server, check the submitted token matches the
token form.
On logout, the CSRF token is removed.
30. Cross Site Request Forgery (CSRF)
Protection
Do not use GET requests
public void doGet(HttpServletRequest req,
HttpServletResponse resp) {
throw new Exception(“Invalid operation”);
}
Check the referrer header using
HTTPServletRequest:
String referer = request.getHeader(“Referer”);
if (referer != null && referer != “our trusted
link”) {
session.invalidate();
throw new Exception();
}
31. Cross Site Request Forgery (CSRF)
Protection
Implementing CSRF tokens using ESAPI
// To generate CSRF token
String csrfToken = ESAPI.randomizer().getRandomString(8,
DefaultEncoder.CHAR_ALPHANUMERICS);
// After user authentication, add token to user‟s session
request.getSession().setAttribute(“csrfToken”, csrfToken);
// To Validate a Token; this code can be added a filter
String requestToken = request.getParameter(“csrfToken”);
String sessionToken = session.getAttribute(“csrfToken”);
if (!requestToken.equals(sessionToken)) {
throw new Exception(“Invalid CSRF Token”);
}
32. Cross Site Request Forgery (CSRF)
Protection
// At logout, delete the session which removes its content
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
Implementing CSRF tokens using CSRFGuard
project via ServletFilters
Tokens are automatically generated, managed, verified,
and inserted
Copy Owasp.CsrfGuard.jar file to your application‟s classpath
Declate CsrfGuard in web.xml
Configure the Owasp.CsrfGuard.properties file as you see fit
33. Failure to Restrict URL Access
Attacker, who is an authorized user, simply changes
the URL to a privileged page.
URL is not protected with authorization.
Just because your URL is hard to guess, doesn‟t
mean it can‟t be found!
Example:
“hidden” URLs rendered only to admins
/admin/adduser.do
Attacker can find unprotected URLs
Test pages deployed in production
“hidden” files such as system reports
34. Failure to Restrict URL Access Protection
Create Access Control Matrix for your Application:
Function 1 Function 2 Function 3
PG Admin Read, write Read, Write Read,
Write
Acquirer Admin Read Read, Write Read,
Write
Access Control Matrix shouldReadeasily configured
Bank Admin be Read,
For each request, ensure that the userWrite
is authorized
to access that function.
Block access to all file types that your application
should never serve
Put all your UI files under /WEB-INF
35. Broken Authentication & Session
Management
Flaws in this area most frequently involve the failure
to protect credentials and session tokens through
their lifecycle
If this issue is not properly addressed, many issues
arise:
Account hijacked
Credentials stolen
Privacy violation
36. Broken Authentication & Session
Management Protection
Use the build-in session management
Utilize SSL / TLS Session identifier
With regards to authentication:
Use a single authentication point
Invalidate the HttpSession before login and after login to
prevent session fixation
Make sure logout function invalidate the session
Add a session time-out
Do not expose any session identifiers in URLs or
logs
Check the old password when the user changes to a
new password
37. Broken Authentication & Session
Management Protection
Prevent brute force attacks by limiting the number of
attempts
Destroy session if Referrer is suspicious (see CSRF)
Regenerate session if remote IP changed
Regenerate session if user agent changed
To Fetch the direct reference using the indirect reference use:map.getDirectReference()setIndirectReference can be supported by using a super class for all the entities
Session hijacking: - Predictable session key use Build-in Session management to generate random and v. long key - Session Fixation Regenerate session id after login - Sniffing: use Https - Steal the session key (XSS) refer to XSS