This cheat sheet is focused on providing developer guidance on Clickjack/UI Redress attack prevention.

The most popular way to defend against Clickjacking is to include some sort of 'frame-breaking' functionality which prevents other web pages from framing the site you wish to defend. This cheat sheet will discuss two methods of implementing frame-breaking: first is X-Frame-Options headers (used if the browser supports the functionality); and second is javascript frame-breaking code.

Owasp checklist github

The frame-ancestors directive can be used in a Content-Security-Policy HTTP response header to indicate whether or not a browser should be allowed to render a page in a <frame> or <iframe>. Sites can use this to avoid Clickjacking attacks by ensuring that their content is not embedded into other sites.

The OWASP Cheat Sheet Series was created to provide a concise collection of high value information on specific application security topics. See instructions and demonstrations in the LESSONS section. Damn Vulnerable Serverless Application (DVSA) is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later.

frame-ancestors allows a site to authorize multiple domains using the normal Content Security Policy semantics.

Content-Security-Policy: frame-ancestors Examples

Common uses of CSP frame-ancestors:

  • Content-Security-Policy: frame-ancestors 'none';
    • This prevents any domain from framing the content. This setting is recommended unless a specific need has been identified for framing.
  • Content-Security-Policy: frame-ancestors 'self';
    • This only allows the current site to frame the content.
  • Content-Security-Policy: frame-ancestors 'self' '*.somesite.com' 'https://myfriend.site.com';
    • This allows the current site, as well as any page on somesite.com (using any protocol), and only the page myfriend.site.com, using HTTPS only on the default port (443).

Note that the single quotes are required.

See the following documentation for further details and more complex examples:

Limitations

  • Browser support: CSP frame-ancestors is not supported by all the major browsers yet.
  • X-Frame-Options takes priority:Section 'Relation to X-Frame-Options' of the CSP Spec says: 'If a resource is delivered with an policy that includes a directive named frame-ancestors and whose disposition is 'enforce', then the X-Frame-Options header MUST be ignored', but Chrome 40 & Firefox 35 ignore the frame-ancestors directive and follow the X-Frame-Options header instead.

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame> or <iframe>. Sites can use this to avoid Clickjacking attacks, by ensuring that their content is not embedded into other sites. Set the X-Frame-Options header for all responses containing HTML content. The possible values are 'DENY', 'SAMEORIGIN', or 'ALLOW-FROM uri'

X-Frame-Options Header Types

There are three possible values for the X-Frame-Options header:

  • DENY, which prevents any domain from framing the content. The 'DENY' setting is recommended unless a specific need has been identified for framing.
  • SAMEORIGIN, which only allows the current site to frame the content.
  • ALLOW-FROM uri, which permits the specified 'uri' to frame this page. (e.g., ALLOW-FROM http://www.example.com).
    • Check limitations below because this will fail open if the browser does not support it.
    • Other browsers support the new CSP frame-ancestors directive instead. A few support both.

Browser Support

The following browsers support X-Frame-Options headers.

References:

  • X-Frame-Options Compatibility Test - Check this for the LATEST browser support info for the X-Frame-Options header

Implementation

To implement this protection, you need to add the X-Frame-Options HTTP Response header to any page that you want to protect from being clickjacked via framebusting. One way to do this is to add the HTTP Response Header manually to every page. A possibly simpler way is to implement a filter that automatically adds the header to every page or to add it at Web Application Firewall of Web/Application Server level.

Common Defense Mistakes

Meta-tags that attempt to apply the X-Frame-Options directive DO NOT WORK. For example, <meta http-equiv='X-Frame-Options'> will not work. You must apply the X-FRAME-OPTIONS directive as HTTP Response Header as described above.

Limitations

  • Per-page policy specification: The policy needs to be specified for every page, which can complicate deployment. Providing the ability to enforce it for the entire site, at login time for instance, could simplify adoption.
  • Problems with multi-domain sites: The current implementation does not allow the webmaster to provide a whitelist of domains that are allowed to frame the page. While whitelisting can be dangerous, in some cases a webmaster might have no choice but to use more than one hostname.
  • ALLOW-FROM browser support: The ALLOW-FROM option is a relatively recent addition (circa 2012) and may not be supported by all browsers yet. BE CAREFUL ABOUT DEPENDING ON ALLOW-FROM. If you apply it and the browser does not support it, then you will have NO clickjacking defense in place.
  • Multiple options not supported: There is no way to allow the current site and a 3rd party site to frame the same response. Browsers only honour one X-Frame-Options header and only one value on that header.
  • Nested Frames don't work with SAMEORIGIN and ALLOW-FROM: In the following situation, the http://framed.invalid/child frame does not load because ALLOW-FROM applies to the top-level browsing context, not that of the immediate parent. The solution is to use ALLOW-FROM in both the parent and child frames (but this prevents the child frame loading if the //framed.invalid/parent page is loaded as the top level document).
  • X-Frame-Options Deprecated While the X-Frame-Options header is supported by the major browsers, it was never standardized and has been deprecated in favour of the frame-ancestors directive from the CSP Level 2 specification.
  • Proxies Web proxies are notorious for adding and stripping headers. If a web proxy strips the X-Frame-Options header then the site loses its framing protection.

One way to defend against clickjacking is to include a 'frame-breaker' script in each page that should not be framed. The following methodology will prevent a webpage from being framed even in legacy browsers, that do not support the X-Frame-Options-Header.

In the document HEAD element, add the following:

First apply an ID to the style element itself:

Then, delete that style by its ID immediately after in the script:

This way, everything can be in the document HEAD and you only need one method/taglib in your API.

Reference:

The use of X-Frame-Options or a frame-breaking script is a more fail-safe method of clickjacking protection. However, in scenarios where content must be frameable, then a window.confirm() can be used to help mitigate Clickjacking by informing the user of the action they are about to perform.

Invoking window.confirm() will display a popup that cannot be framed. If the window.confirm() originates from within an iframe with a different domain than the parent, then the dialog box will display what domain the window.confirm() originated from. In this scenario the browser is displaying the origin of the dialog box to help mitigate Clickjacking attacks. It should be noted that Internet Explorer is the only known browser that does not display the domain that the window.confirm() dialog box originated from, to address this issue with Internet Explorer insure that the message within the dialog box contains contextual information about the type of action being performed. For example:

Consider the following snippet which is NOT recommended for defending against clickjacking:

This simple frame breaking script attempts to prevent the page from being incorporated into a frame or iframe by forcing the parent window to load the current frame's URL. Unfortunately, multiple ways of defeating this type of script have been made public. We outline some here.

Double Framing

Some frame busting techniques navigate to the correct page by assigning a value to parent.location. This works well if the victim page is framed by a single page. However, if the attacker encloses the victim in one frame inside another (a double frame), then accessing parent.location becomes a security violation in all popular browsers, due to the descendant frame navigation policy. This security violation disables the counter-action navigation.

Victim frame busting code:

Attacker top frame:

Attacker sub-frame:

The onBeforeUnload Event

A user can manually cancel any navigation request submitted by a framed page. To exploit this, the framing page registers an onBeforeUnload handler which is called whenever the framing page is about to be unloaded due to navigation. The handler function returns a string that becomes part of a prompt displayed to the user.

Say the attacker wants to frame PayPal. He registers an unload handler function that returns the string 'Do you want to exit PayPal?'. When this string is displayed to the user is likely to cancel the navigation, defeating PayPal's frame busting attempt.

The attacker mounts this attack by registering an unload event on the top page using the following code:

PayPal's frame busting code will generate a BeforeUnload event activating our function and prompting the user to cancel the navigation event.

No-Content Flushing

While the previous attack requires user interaction, the same attack can be done without prompting the user. Most browsers (IE7, IE8, Google Chrome, and Firefox) enable an attacker to automatically cancel the incoming navigation request in an onBeforeUnload event handler by repeatedly submitting a navigation request to a site responding with '204 - No Content'.

Navigating to a No Content site is effectively a NOP, but flushes the request pipeline, thus canceling the original navigation request. Here is sample code to do this:

Exploiting XSS filters

IE8 and Google Chrome introduced reflective XSS filters that help protect web pages from certain types of XSS attacks. Nava and Lindsay (at Blackhat) observed that these filters can be used to circumvent frame busting code. The IE8 XSS filter compares given request parameters to a set of regular expressions in order to look for obvious attempts at cross-site scripting. Using 'induced false positives', the filter can be used to disable selected scripts. By matching the beginning of any script tag in the request parameters, the XSS filter will disable all inline scripts within the page, including frame busting scripts. External scripts can also be targeted by matching an external include, effectively disabling all external scripts. Since subsets of the JavaScript loaded is still functional (inline or external) and cookies are still available, this attack is effective for clickjacking.

Victim frame busting code:

Attacker:

The XSS filter will match that parameter <script>if to the beginning of the frame busting script on the victim and will consequently disable all inline scripts in the victim's page, including the frame busting script. The XSSAuditor filter available for Google Chrome enables the same exploit.

Clobbering top.location

Several modern browsers treat the location variable as a special immutable attribute across all contexts. However, this is not the case in IE7 and Safari 4.0.4 where the location variable can be redefined.

IE7: Once the framing page redefines location, any frame busting code in a subframe that tries to read top.location will commit a security violation by trying to read a local variable in another domain. Similarly, any attempt to navigate by assigning top.location will fail.

Victim frame busting code:

Attacker:

Safari 4.0.4

We observed that although location is kept immutable in most circumstances, when a custom location setter is defined via defineSetter (through window) the object location becomes undefined.

The framing page simply does:

Now any attempt to read or navigate the top frame's location will fail.

Restricted zones

Most frame busting relies on JavaScript in the framed page to detect framing and bust itself out. If JavaScript is disabled in the context of the subframe, the frame busting code will not run. There are unfortunately several ways of restricting JavaScript in a subframe:

In IE 8:

In Chrome:

Firefox and IE:

Activate designMode in parent page.

Jim Manico - jim@owasp.org

Santhosh Tuppad - santhosh.tuppad@gmail.com

Jeffrey Walton

Till Maas

Dave Wichers - dwichers@gmail.com

Michael Brook

Tom Parker

Shruti kulkarni

Yozo

Eelgheez

Aabashkin

Authentication is the process of verification that an individual, entity or website is who it claims to be. Authentication in the context of web applications is commonly performed by submitting a user name or ID and one or more items of private information that only a given user should know.

Session Management is a process by which a server maintains the state of an entity interacting with it. This is required for a server to remember how to react to subsequent requests throughout a transaction. Sessions are maintained on the server by a session identifier which can be passed back and forward between the client and server when transmitting and receiving requests. Sessions should be unique per user and computationally very difficult to predict.

User IDs

Make sure your usernames/userids are case insensitive. User 'smith' and user 'Smith' should be the same user. User names should also be unique. For high security applications usernames could be assigned and secret instead of user-defined public data.

Email address as a User ID

For information on validating email addresses, please visit the input validation cheatsheet email discussion.

Authentication Solution and Sensitive Accounts

  • Do NOT allow login with sensitive accounts (i.e. accounts that can be used internally within the solution such as to a back-end / middle-ware / DB) to any front end user interface
  • Do NOT use the same authentication solution (e.g. IDP / AD) used internally for unsecured access (e.g. public access / DMZ)

Implement Proper Password Strength Controls

A key concern when using passwords for authentication is password strength. A 'strong' password policy makes it difficult or even improbable for one to guess the password through either manual or automated means. The following characteristics define a strong password:

Password Length

Longer passwords provide a greater combination of characters and consequently make it more difficult for an attacker to guess.

  • Minimum length of the passwords should be enforced by the application.
    • Passwords shorter than 10 characters are considered to be weak (NIST SP800-132).

While minimum length enforcement may cause problems with memorizing passwords among some users, applications should encourage them to set passphrases (sentences or combination of words) that can be much longer than typical passwords and yet much easier to remember.

  • Maximum password length should not be set too low, as it will prevent users from creating passphrases. Typical maximum length is 128 characters.
    • Passphrases shorter than 20 characters are usually considered weak if they only consist of lower case Latin characters.

Password Complexity

Applications should enforce password complexity rules to discourage easy to guess passwords. Password mechanisms should allow virtually any character the user can type to be part of their password, including the space character. Passwords should, obviously, be case sensitive in order to increase their complexity. Occasionally, we find systems where passwords aren't case sensitive, frequently due to legacy system issues like old mainframes that didn't have case sensitive passwords.

The password change mechanism should require a minimum level of complexity that makes sense for the application and its user population. For example:

  • Password must meet at least 3 out of the following 4 complexity rules
    • at least 1 uppercase character (A-Z)
    • at least 1 lowercase character (a-z)
    • at least 1 digit (0-9)
    • at least 1 special character (punctuation) — do not forget to treat space as special characters too
  • at least 10 characters
  • at most 128 characters
  • not more than 2 identical characters in a row (e.g., 111 not allowed)

Further reading:

  • Your Password Complexity Requirements are Worthless - OWASP AppSecUSA 2014 presentation for further discussion of legacy password complexity rules

Password Topologies

  • Ban commonly used password topologies
  • Force multiple users to use different password topologies
  • Require a minimum topology change between old and new passwords

Additional Information

  • Make sure that every character the user types in is actually included in the password. We've seen systems that truncate the password at a length shorter than what the user provided (e.g., truncated at 15 characters when they entered 20).
  • As application's require more complex password policies, they need to be very clear about what these policies are. The required policy needs to be explicitly stated on the password change page
  • If the new password doesn't comply with the complexity policy, the error message should describe EVERY complexity rule that the new password does not comply with, not just the 1st rule it doesn't comply with.

Implement Secure Password Recovery Mechanism

It is common for an application to have a mechanism that provides a means for a user to gain access to their account in the event they forget their password. Please see Forgot Password Cheat Sheet for details on this feature.

Store Passwords in a Secure Fashion

It is critical for a application to store a password using the right cryptographic technique. Please see Password Storage Cheat Sheet for details on this feature.

Transmit Passwords Only Over TLS or Other Strong Transport

See: Transport Layer Protection Cheat Sheet

The login page and all subsequent authenticated pages must be exclusively accessed over TLS or other strong transport. The initial login page, referred to as the 'login landing page', must be served over TLS or other strong transport. Failure to utilize TLS or other strong transport for the login landing page allows an attacker to modify the login form action, causing the user's credentials to be posted to an arbitrary location. Failure to utilize TLS or other strong transport for authenticated pages after login enables an attacker to view the unencrypted session ID and compromise the user's authenticated session.

Require Re-authentication for Sensitive Features

In order to mitigate CSRF and session hijacking, it's important to require the current credentials for an account before updating sensitive account information such as the user's password, user's email, or before sensitive transactions, such as shipping a purchase to a new address. Without this countermeasure, an attacker may be able to execute sensitive transactions through a CSRF or XSS attack without needing to know the user's current credentials. Additionally, an attacker may get temporary physical access to a user's browser or steal their session ID to take over the user's session.

Consider Strong Transaction Authentication

Some applications should use a second factor to check whether a user may perform sensitive operations. For more information see the Transaction Authorization Cheat Sheet.

TLS Client Authentication

TLS Client Authentication, also known as two-way TLS authentication, consists of both, browser and server, sending their respective TLS certificates during the TLS handshake process. Just as you can validate the authenticity of a server by using the certificate and asking a well known Certificate Authority (CA) if the certificate is valid, the server can authenticate the user by receiving a certificate from the client and validating against a third party CA or its own CA. To do this, the server must provide the user with a certificate generated specifically for him, assigning values to the subject so that these can be used to determine what user the certificate should validate. The user installs the certificate on a browser and now uses it for the website.

It is a good idea to do this when:

  • It is acceptable (or even preferred) that the user only has access to the website from only a single computer/browser.
  • The user is not easily scared by the process of installing TLS certificates on his browser or there will be someone, probably from IT support, that will do this for the user.
  • The website requires an extra step of security.
  • It is also a good thing to use when the website is for an intranet of a company or organization.

It is generally not a good idea to use this method for widely and publicly available websites that will have an average user. For example, it wouldn't be a good idea to implement this for a website like Facebook. While this technique can prevent the user from having to type a password (thus protecting against an average keylogger from stealing it), it is still considered a good idea to consider using both a password and TLS client authentication combined.

For more information, see: Client-authenticated TLS handshake

Authentication and Error Messages

Incorrectly implemented error messages in the case of authentication functionality can be used for the purposes of user ID and password enumeration. An application should respond (both HTTP and HTML) in a generic manner.

Authentication Responses

An application should respond with a generic error message regardless of whether the user ID or password was incorrect. It should also give no indication to the status of an existing account.

Incorrect Response Examples

  • 'Login for User foo: invalid password'
  • 'Login failed, invalid user ID'
  • 'Login failed; account disabled'
  • 'Login failed; this user is not active'

Correct Response Example

  • 'Login failed; Invalid userID or password'

The correct response does not indicate if the user ID or password is the incorrect parameter and hence inferring a valid user ID.

Error Codes and URLs

The application may return a different HTTP Error code depending on the authentication attempt response. It may respond with a 200 for a positive result and a 403 for a negative result. Even though a generic error page is shown to a user, the HTTP response code may differ which can leak information about whether the account is valid or not.

Prevent Brute-Force Attacks

If an attacker is able to guess passwords without the account becoming disabled due to failed authentication attempts, the attacker has an opportunity to continue with a brute force attack until the account is compromised. Automating brute-force/password guessing attacks on web applications is a trivial challenge. Password lockout mechanisms should be employed that lock out an account if more than a preset number of unsuccessful login attempts are made. Password lockout mechanisms have a logical weakness. An attacker that undertakes a large number of authentication attempts on known account names can produce a result that locks out entire blocks of user accounts. Given that the intent of a password lockout system is to protect from brute-force attacks, a sensible strategy is to lockout accounts for a period of time (e.g., 20 minutes). This significantly slows down attackers, while allowing the accounts to reopen automatically for legitimate users.

Also, multi-factor authentication is a very powerful deterrent when trying to prevent brute force attacks since the credentials are a moving target. When multi-factor is implemented and active, account lockout may no longer be necessary.

Owasp Cheat Sheet Pdf

Enable logging and monitoring of authentication functions to detect attacks / failures on a real time basis

  • Ensure that all failures are logged and reviewed
  • Ensure that all password failures are logged and reviewed
  • Ensure that all account lockouts are logged and reviewed

While authentication through a user/password combination and using multi-factor authentication is considered generally secure, there are use cases where it isn't considered the best option or even safe. Examples of this are third party applications that desire connecting to the web application, either from a mobile device, another website, desktop or other situations. When this happens, it is NOT considered safe to allow the third party application to store the user/password combo, since then it extends the attack surface into their hands, where it isn't in your control. For this, and other use cases, there are several authentication protocols that can protect you from exposing your users' data to attackers.

OAuth

Open Authorization (OAuth) is a protocol that allows an application to authenticate against a server as a user, without requiring passwords or any third party server that acts as an identity provider. It uses a token generated by the server, and provides how the authorization flows most occur, so that a client, such as a mobile application, can tell the server what user is using the service.

The recommendation is to use and implement OAuth 1.0a or OAuth 2.0, since the very first version (OAuth1.0) has been found to be vulnerable to session fixation.

OAuth 2.0 relies on HTTPS for security and is currently used and implemented by API's from companies such as Facebook, Google, Twitter and Microsoft. OAuth1.0a is more difficult to use because it requires the use of cryptographic libraries for digital signatures. However, since OAuth1.0a does not rely on HTTPS for security it can be more suited for higher risk transactions.

OpenId

OpenId is an HTTP-based protocol that uses identity providers to validate that a user is who he says he is. It is a very simple protocol which allows a service provider initiated way for single sign-on (SSO). This allows the user to re-use a single identity given to a trusted OpenId identity provider and be the same user in multiple websites, without the need to provide any website the password, except for the OpenId identity provider.

Due to its simplicity and that it provides protection of passwords, OpenId has been well adopted. Some of the well known identity providers for OpenId are Stack Exchange, Google, Facebook and Yahoo!

For non-enterprise environments, OpenId is considered a secure and often better choice, as long as the identity provider is of trust.

SAML

Security Assertion Markup Language (SAML) is often considered to compete with OpenId. The most recommended version is 2.0, since it is very feature complete and provides a strong security. Like OpenId, SAML uses identity providers, but unlike OpenId, it is XML-based and provides more flexibility. SAML is based on browser redirects which send XML data. Furthermore, SAML isn't only initiated by a service provider; it can also be initiated from the identity provider. This allows the user to navigate through different portals while still being authenticated without having to do anything, making the process transparent.

While OpenId has taken most of the consumer market, SAML is often the choice for enterprise applications. The reason for this is often that there are few OpenId identity providers which are considered of enterprise class (meaning that the way they validate the user identity doesn't have high standards required for enterprise identity). It is more common to see SAML being used inside of intranet websites, sometimes even using a server from the intranet as the identity provider.

In the past few years, applications like SAP ERP and SharePoint (SharePoint by using Active Directory Federation Services 2.0) have decided to use SAML 2.0 authentication as an often preferred method for single sign-on implementations whenever enterprise federation is required for web services and web applications.

See also: SAML Security Cheat Sheet

FIDO

The Fast Identity Online (FIDO) Alliance has created two protocols to facilitate online authentication : the Universal Authentication Framework (UAF) protocol and the Universal Second Factor (U2F) protocol. While UAF focuses on passwordless authentication, U2F allows the addition of a second factor to existing password-based authentication. Both protocols are based on a public key cryptography challenge-response model.

UAF takes advantage of existing security technologies present on devices for authentication including fingerprint sensors, cameras(face biometrics), microphones(voice biometrics), Trusted Execution Environments(TEEs), Secure Elements(SEs) and others. The protocol is designed to plug-in these device capabilities into a common authentication framework. UAF works with both native applications and web applications.

U2F augments password-based authentication using a hardware token (typically USB) that stores cryptographic authentication keys and uses them for signing. The user can use the same token as a second factor for multiple applications. U2F works with web applications. It provides protection against phishing by using the URL of the website to lookup the stored authentication key.

Session management is directly related to authentication. The Session Management General Guidelines previously available on this OWASP Authentication Cheat Sheet have been integrated into the Session Management Cheat Sheet.

Password managers are programs, browser plugins or web services that automate management of large number of different credentials, including memorizing and filling-in, generating random passwords on different sites etc. While use of password managers is subject to controversies and many organisations block their usage, their contribution to authentication security is positive, as pointed out by National Cyber Security Centre.

Web applications should at least not make password managers job more difficult than necessary by observing the following recommendations:

  • use standard HTML forms for username and password input with appropriate type attributes,
  • do not artificially limit user passwords to a length 'reasonable for humans' and allow passwords lengths up to 128 characters,
  • do not artificially prevent copy and paste on username and password fields,
  • avoid plugin-based login pages (Flash, Silverlight etc)

As of 2017 Credential Management Level 1 standard for web browsers is being developed that may further facilitate interaction between password managers and complex log-in schemes (e.g. single sign-on).

Owasp Zap Github

Eoin Keary eoinkeary

Jim Manico

Timo Goosen

Pawel Krawczyk

Sven Neuhaus

Owasp Session Management Cheat Sheet

Manuel Aude Morales