Owasp Cheat Sheet Github

Media covers the theft of large collections of passwords on an almost daily basis. Media coverage of password theft discloses the password storage scheme, the weakness of that scheme, and often discloses a large population of compromised credentials that can affect multiple web sites or other applications. This article provides guidance on properly storing passwords, secret question responses, and similar credential information. Proper storage helps prevent theft, compromise, and malicious use of credentials. Information systems store passwords and other credentials in a variety of protected forms. Common vulnerabilities allow the theft of protected passwords through attack vectors such as SQL Injection. Protected passwords can also be stolen from artifacts such as logs, dumps, and backups.

  1. OWASP is an international organization and the OWASP Foundation supports OWASP efforts around the world. OWASP is an open community dedicated to enabling organizations to conceive, develop, acquire, operate, and maintain applications that can be trusted. All of the OWASP tools, documents, forums, and chapters are free.
  2. JPCERT/CC web サイト: OWASPアプリケーションセキュリティ検証標準; Cheat Sheet シリーズ. Cheat Sheet シリーズプロジェクトの github リポジトリ. 以下は, github リポジトリ(V2)に移行する前の時代(V1)のファイルの日本語訳スナップショットです.
  3. The OWASP Cheat Sheet Series was created to provide a concise collection of high value information on specific application security topics. View it on GitHub Star 15894 Rank 679 Released by @k0kubun in December 2014.
  4. See instructions and demonstrations in the LESSONS section. The project is maintained in the DVSA. Feel free to open or solve an issue. Open Web Application Security Project, and Global AppSec are registered trademarks and AppSec Days, AppSec California, AppSec Cali, SnowFROC, LASCON, and the OWASP logo are.

The cheat sheets are available on the main website at If you wish to contribute to the cheat sheets, or to suggest any improvements or changes, then please do so via the issue tracker on the GitHub repository. Alternatively, join us in the #cheetsheats channel on the OWASP Slack (details in the sidebar).

Specific guidance herein protects against stored credential theft but the bulk of guidance aims to prevent credential compromise. That is, this guidance helps designs resist revealing users’ credentials or allowing system access in the event threats steal protected credential information. For more information and a thorough treatment of this topic, refer to the Secure Password Storage Threat Model here.

Do not limit the character set and set long max lengths for credentials

Some organizations restrict the 1) types of special characters and 2) length of credentials accepted by systems because of their inability to prevent SQL Injection, Cross-site scripting, command-injection and other forms of injection attacks. These restrictions, while well-intentioned, facilitate certain simple attacks such as brute force.

Do not allow short or no-length passwords and do not apply character set, or encoding restrictions on the entry or storage of credentials. Continue applying encoding, escaping, masking, outright omission, and other best practices to eliminate injection risks.

A reasonable long password length is 160. Very long password policies can lead to DOS in certain circumstances.

Hash the password as one of several steps

Owasp Authentication Cheat Sheet

Very large passwords can be a performance bottleneck or a DOS situation when users utilize very long passwords. Also, some implementations of some of the adaptive algorithms suggested below, such as bcrypt, truncate long passwords making them less effective. By hashing the passwords with a hash such as SHA-512, even giant passwords are reduced to 512 bits, solving both problems.

Use a cryptographically strong credential-specific salt

A salt is fixed-length cryptographically-strong random value. Append credential data to the salt and use this as input to a protective function.

Store the protected form appended to the salt as follows:

Follow these practices to properly implement credential-specific salts:

  • Generate a unique salt upon creation of each stored credential (not just per user or system wide);
  • Use cryptographically-strong random data;
  • As storage permits, use a 32 byte or 64 byte salt (actual size dependent on protection function);
  • Scheme security does not depend on hiding, splitting, or otherwise obscuring the salt.

Salts serve two purposes:

  1. prevent the protected form from revealing two identical credentials and
  2. augment entropy fed to protecting function without relying on credential complexity. The second aims to make pre-computed lookup attacks on an individual credential and time-based attacks on a population intractable.

Impose infeasible verification on attacker

The function used to protect stored credentials should balance attacker and defender verification. The defender needs an acceptable response time for verification of users’ credentials during peak use. However, the time required to map <credential> → <protected form> must remain beyond threats’ hardware (GPU, FPGA) and technique (dictionary-based, brute force, etc) capabilities.

Two approaches facilitate this, each imperfectly.

Leverage an adaptive one-way function

Adaptive one-way functions compute a one-way (irreversible) transform. Each function allows configuration of ‘work factor’. Underlying mechanisms used to achieve irreversibility and govern work factors (such as time, space, and parallelism) vary between functions and remain unimportant to this discussion.

Select:

  • Argon2 is the winner of the password hashing competition and should be considered as your first choice for new applications;
  • PBKDF2 when FIPS certification or enterprise support on many platforms is required;
  • Scrypt where resisting any/all hardware accelerated attacks is necessary but support isn’t.
  • Bcrypt where PBKDF2 or Scrypt support is not available.

Example protect() pseudo-code follows:

In the example above, as PBKDF2 computation time depend on the target system, iteration_count must have a number implying that the computation time on the target system must take at least 1 second (like 1000.000 for example).

Designers select one-way adaptive functions to implement protect() because these functions can be configured to cost (linearly or exponentially) more than a hash function to execute. Defenders adjust work factor to keep pace with threats’ increasing hardware capabilities. Those implementing adaptive one-way functions must tune work factors so as to impede attackers while providing acceptable user experience and scale.

Additionally, adaptive one-way functions do not effectively prevent reversal of common dictionary-based credentials (users with password ‘password’) regardless of user population size or salt usage.

Work Factor

Since resources are normally considered limited, a common rule of thumb for tuning the work factor (or cost) is to make protect() run as slow as possible without affecting the users' experience and without increasing the need for extra hardware over budget. So, if the registration and authentication's cases accept protect() taking up to 1 second, you can tune the cost so that it takes 1 second to run on your hardware. This way, it shouldn't be so slow that your users become affected, but it should also affect the attackers' attempt as much as possible.

While there is a minimum number of iterations recommended to ensure data safety, this value changes every year as technology improves and then require to be reviewed on a regular basis or after an hardware upgrade.

However, it is critical to understand that a single work factor does not fit all designs, experimentation is important.

Leverage Keyed functions

Keyed functions, such as HMACs, compute a one-way (irreversible) transform using a private key and given input. For example, HMACs inherit properties of hash functions including their speed, allowing for near instant verification. Key size imposes infeasible size- and/or space- requirements on compromise--even for common credentials (aka password = ‘password’). Designers protecting stored credentials with keyed functions:

  • Use a single “site-wide” key;
  • Protect this key as any private key using best practices;
  • Store the key outside the credential store (aka: not in the database);
  • Generate the key using cryptographically-strong pseudo-random data;
  • Do not worry about output block size (i.e. SHA-256 vs. SHA-512).

Example protect() pseudo-code follows:

Upholding security improvement over (solely) salted schemes relies on proper key management.

Design password storage assuming eventual compromise

The frequency and ease with which threats steal protected credentials demands “design for failure”. Having detected theft, a credential storage scheme must support continued operation by marking credential data as compromised. It's also critical to engage alternative credential validation workflows as follows:

  1. Protect the user’s account

    1. Invalidate authentication ‘shortcuts’ by disallowing login without 2nd factors, secret questions or some other form of strong authentication.
    2. Disallow changes to user accounts such as editing secret questions and changing account multi-factor configuration settings.
  2. Load and use new protection scheme

    1. Load a new, stronger credential protection scheme (See next section on: Upgrading your existing password hashing solution)
    2. Include version information stored with form
    3. Set ‘tainted’/‘compromised’ bit until user resets credentials
    4. Rotate any keys and/or adjust protection function parameters such as work factor or salt
    5. Increment scheme version number
  3. When user logs in:

    1. Validate credentials based on stored version (old or new); if older compromised version is still active for user, demand 2nd factor or secret answers until the new method is implemented or activated for that user
    2. Prompt user for credential change, apologize, & conduct out-of-band confirmation
    3. Convert stored credentials to new scheme as user successfully log in

Upgrading your existing password hashing solution

The above guidance describes how to do password hashing correctly/safely. However, it is very likely you'll be in a situation where you have an existing solution you want to upgrade. This article provides some good guidance on how to accomplish an upgrade in place without adversely affecting existing user accounts and future proofing your upgrade so you can seamlessly upgrade again (which you eventually will need to do).

The objective is to propose a example of secure usage/integration of the Argon2 algorithm in Java application to protect password when stored.

Argon2 library used

The Argon2 implementation provided by phc-winner-argon2 project has been used because:

  • It's the reference implementation of this algorithm.
  • It's dedicated to this new algorithm so all work by the maintainer is focused on the implementation.
  • Project is active, last release date from december 2017.
  • There bindings for many technologies.

Java bindings by phxql has been used because it's currently the only binding proposed for Java in the bindings list and is simple to use.

libsodium propose an implementation but it have been decided to use a dedicated project because libsodium provide several crypto features and thus work from maintainer will not focus on Argon2 implementation (however project is active and propose also bindings for many technologies).

Remark about Argon2 native library embedding

Due to the kind of data processed (password), the implementation without the embedded pre-compiled native library has been used in order to don't embed native untrusted compiled code (there absolutely no issue with the project owner of argon2-jvm, it is just a secure approach) that will be difficult to validate. For java part, sources are provided in Maven repositories along jar files.

Technical details about how to build the Argon2 library on different platforms are available on PHC repository and on argon2-jvm repository.

Note:

Always name the compiled library with this format to simplify integration with the argon2-jvm binding project:

  • For Windows: argon2.dll
  • For Linux: libargon2.so
  • For OSX: libargon2.dylib

Integration in company projects

Integration in company projects can use the following approach:

  1. Create a internal shared java utility library that embeed your compiled version of the Argon2 library.
  2. Use this shared java library in the different projects in order to:
    1. Prevent to embed a version of the Argon2 library in all your project.
    2. Centralize and unify the version of the Argon2 library used (important for upgrade process).

Implementation proposal

The following class propose utility methods to compute and verify a hash of a password along creating a abstraction layer on the algorithm used behind the scene.

Proposed configuration options for Argon2 are based on the following source of recommendation:

  • PHC project.
  • Section 9 of the Argon2 specifications document.

Documented configuration is the following, increase the number of the ITERATIONS parameter if the computing of a hash take less than 2 seconds on your environement:

Input password size

In order to prevent any DOS attack using a very big password, it's recommended to define a higher size limit for the password choosen by the user.

A limit of 1000 characters is sufficient to let the user choose a very big password without impacting the system.

A test with a password with an alphanumeric content of 10 000 000 characters has been performed on the used Argon2 library and binding using the proposed configuration:

There no problem meet, library and binding supports it:

Sources of the prototype

The entire source code of the POC is available here.

The objective is to propose a example of secure usage/integration of the Argon2 algorithm in PHP application to protect password when stored.

From PHP version 7.2, Argon2 is supported in built-in password hashing related functions:

  • password_hash()
  • password_verify()
  • password_get_info()

Like for the Java proposal, the Argon2 implementation provided by phc-winner-argon2 project has been used and for the same reasons.

Remark about self compilation of binaries for PHP and Argon2

Like for Java proposal, focus is made here on non-installing binaries from untrusted sources (non official linux repositories - PHC Github repository for Argon2 is considered as trusted because sources are provided and a security code review can be applied).

The third-party linux repository ondrej/php provide pre-compiled packages for Argon2 and PHP 7.2 but it have been decided to not trust it because is not an official repository.

Implementation proposal

Setup PHP for Argon2 usage

The following shell script show a proposal for the setup of a PHP 7.2 installation to enable the usage of Argon2 for password hashing:

Password hashing usage

The following class propose utility methods to compute and verify a hash of a password along creating a abstraction layer on the algorithm used behind the scene.

Like for Java proposal, this class can be included in a internal shared utility library that will be used by others projects.

Remark made for Java proposal about input password size is also applicable for PHP.

Proposed configuration options for Argon2 are based on the same sources than for the Java proposal.

Documented configuration is the following:

Sources of the prototype

The entire source code of the POC is available here.

Ref1

Ref2

  • Rainbow Tables.

Ref3

  • For example: Java SecureRandom class.

Ref4

  • Kalski, B., PKCS #5: Password-Based Cryptography Specification Version 2.0, IETF RFC 2898, September, 2000, p9.

Ref5

  • Percival, C., Stronger Key Derivation Via Sequential Memory-Hard Functions, BSDCan ‘09, May, 2009.

Ref6

For instance, one might set work factors targeting the following run times:

  1. Password-generated session key - fraction of a second;
  2. User credential - ~0.5 seconds;
  3. Password-generated site (or other long-lived) key - potentially a second or more.

Ref7

  • Argon2 detailed specifications can be found here.

Ref8

  • Painless Password Hash Upgrades.

John Steven - [email protected]

Jim Manico - [email protected]

Dominique Righetto - [email protected]

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.

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.

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:

Owasp Input Validation Cheat Sheet

Attacker top frame: Mac fan control download el capitan installer.

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.

Owasp Cheat Sheet Github

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

Owasp Checklist Github

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 - [email protected]

Santhosh Tuppad - [email protected]

Jeffrey Walton

Till Maas

Dave Wichers - [email protected]

Michael Brook

Tom Parker

Shruti kulkarni

Yozo

Eelgheez

Owasp Sql Injection Cheat Sheet Github

Aabashkin