Owasp Cheat Sheet



  • In order to read the cheat sheets and reference them, use the project's official website. The project details can be viewed on the OWASP main website without the cheat sheets. 🚩 Markdown files are the working sources and are not intended to be referenced in any external documentation, books or websites. Cheat Sheet Series Team Project.
  • The OWASP Cheat Sheet Series was created to provide a concise collection of high value information on specific application security topics. These cheat sheets were created by various application security professionals who have expertise in specific topics.

The OWASP Cheat Sheet Series was created to provide a set of simple good practice guides for application developers and defenders to follow. Rather than focused on detailed best practices that are impractical for many developers and applications, they are intended to provide good practices that the majority of developers will actually be able. Clickjacking Defense Cheat Sheet¶ Introduction¶. This cheat sheet is intended to provide guidance for developers on how to defend against Clickjacking, also known as UI redress attacks. There are three main mechanisms that can be used to defend against these attacks. The OWASP Attach Surface Analysis Cheat Sheet provided a complete list of items for securing applications. According to the cheat sheet, network-facing code, web forms, files from outside of the network, backward compatible interfaces with other systems, APIs, and security codes are all attack surfaces.

This page intends to provide quick basic .NET security tips for developers.

The .NET Framework

The .NET Framework is Microsoft's principal platform for enterprise development. It is the supporting API for ASP.NET, Windows Desktop applications, Windows Communication Foundation services, SharePoint, Visual Studio Tools for Office and other technologies.

Updating the Framework

The .NET Framework is kept up-to-date by Microsoft with the Windows Update service. Developers do not normally need to run seperate updates to the Framework. Windows update can be accessed at Windows Update or from the Windows Update program on a Windows computer.

Individual frameworks can be kept up to date using NuGet. As Visual Studio prompts for updates, build it into your lifecycle.

Remember that third party libraries have to be updated separately and not all of them use Nuget. ELMAH for instance, requires a separate update effort.

The .NET Framework is the set of APIs that support an advanced type system, data, graphics, network, file handling and most of the rest of what is needed to write enterprise apps in the Microsoft ecosystem. It is a nearly ubiquitous library that is strong named and versioned at the assembly level.

Data Access

  • Use Parameterized SQL commands for all data access, without exception.
  • Do not use SqlCommand with a string parameter made up of a concatenated SQL String.
  • Whitelist allowable values coming from the user. Use enums, TryParse or lookup values to assure that the data coming from the user is as expected.
    • Enums are still vulnerable to unexpected values because .NET only validates a successful cast to the underlying data type, integer by default. Enum.IsDefined can validate whether the input value is valid within the list of defined constants.
  • Apply the principle of least privilege when setting up the Database User in your database of choice. The database user should only be able to access items that make sense for the use case.
  • Use of the Entity Framework is a very effective SQL injection prevention mechanism. Remember that building your own ad hoc queries in Entity Framework is just as susceptible to SQLi as a plain SQL query.
  • When using SQL Server, prefer integrated authentication over SQL authentication.
  • Use Always Encrypted where possible for sensitive data (SQL Server 2016 and SQL Azure),

Encryption

  • Never, ever write your own encryption.
  • Use the Windows Data Protection API (DPAPI) for secure local storage of sensitive data.
  • Use a strong hash algorithm.
    • In .NET (both Framework and Core) the strongest hashing algorithm for general hashing requirements is System.Security.Cryptography.SHA512.
    • In the .NET framework the strongest algorithm for password hashing is PBKDF2, implemented as System.Security.Cryptography.Rfc2898DeriveBytes.aspx).
    • In .NET Core the strongest algorithm for password hashing is PBKDF2, implemented as Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2 which has several significant advantages over Rfc2898DeriveBytes.
    • When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing.
  • Make sure your application or protocol can easily support a future change of cryptographic algorithms.
  • Use Nuget to keep all of your packages up to date. Watch the updates on your development setup, and plan updates to your applications accordingly.

General

  • Lock down the config file.
    • Remove all aspects of configuration that are not in use.
    • Encrypt sensitive parts of the web.config using aspnet_regiis -pe (command line help)).
  • For Click Once applications the .Net Framework should be upgraded to use version 4.6.2 to ensure TLS 1.1/1.2 support.

ASP.NET Web Forms is the original browser-based application development API for the .NET framework, and is still the most common enterprise platform for web application development.

  • Always use HTTPS.
  • Enable requireSSL on cookies and form elements and HttpOnly on cookies in the web.config.
  • Implement customErrors).
  • Make sure tracing is turned off.
  • While viewstate isn't always appropriate for web development, using it can provide CSRF mitigation. To make the ViewState protect against CSRF attacks you need to set the ViewStateUserKey:

If you don't use Viewstate, then look to the default master page of the ASP.NET Web Forms default template for a manual anti-CSRF token using a double-submit cookie.

  • Consider HSTS in IIS. See here for the procedure.
  • This is a recommended web.config setup that handles HSTS among other things.
  • Remove the version header.
  • Also remove the Server header.

HTTP validation and encoding

  • Do not disable validateRequest in the web.config or the page setup. This value enables limited XSS protection in ASP.NET and should be left intact as it provides partial prevention of Cross Site Scripting. Complete request validation is recommended in addition to the built in protections.
  • The 4.5 version of the .NET Frameworks includes the AntiXssEncoder library, which has a comprehensive input encoding library for the prevention of XSS. Use it.
  • Whitelist allowable values anytime user input is accepted.
  • Validate the URI format using Uri.IsWellFormedUriString.

Forms authentication

  • Use cookies for persistence when possible. Cookieless auth will default to UseDeviceProfile.
  • Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.
  • Reduce the forms authentication timeout from the default of 20 minutes to the shortest period appropriate for your application. If slidingExpiration is used this timeout resets after each request, so active users won't be affected.
  • If HTTPS is not used, slidingExpiration should be disabled. Consider disabling slidingExpiration even with HTTPS.
  • Always implement proper access controls.
    • Compare user provided username with User.Identity.Name.
    • Check roles against User.Identity.IsInRole.
  • Use the ASP.NET Membership provider and role provider, but review the password storage. The default storage hashes the password with a single iteration of SHA-1 which is rather weak. The ASP.NET MVC4 template uses ASP.NET Identity instead of ASP.NET Membership, and ASP.NET Identity uses PBKDF2 by default which is better. Review the OWASP Password Storage Cheat Sheet for more information.
  • Explicitly authorize resource requests.
  • Leverage role based authorization using User.Identity.IsInRole.

ASP.NET MVC (Model-View-Controller) is a contemporary web application framework that uses more standardized HTTP communication than the Web Forms postback model.

The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every 3 years.

This section is based on this. Your approach to securing your web application should be to start at the top threat A1 below and work down, this will ensure that any time spent on security will be spent most effectively spent and cover the top threats first and lesser threats afterwards. After covering the top 10 it is generally advisable to assess for other threats or get a professionally completed Penetration Test.

A1 SQL Injection

DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.

DO: Use parameterized queries where a direct sql query must be used.

e.g. In entity frameworks:

DO NOT: Concatenate strings anywhere in your code and execute them against your database (Known as dynamic sql).

NB: You can still accidentally do this with ORMs or Stored procedures so check everywhere.

Owasp

e.g

DO: Practise Least Privilege - Connect to the database using an account with a minimum set of permissions required to do it's job i.e. not the sa account

A2 Weak Account management

Ensure cookies are sent via httpOnly:

Reduce the time period a session can be stolen in by reducing session timeout and removing sliding expiration:

See here for full startup code snippet

Ensure cookie is sent over https in the production environment. This should be enforced in the config transforms:

Protect LogOn, Registration and password reset methods against brute force attacks by throttling requests (see code below), consider also using ReCaptcha.

DO NOT: Roll your own authentication or session management, use the one provided by .Net

DO NOT: Tell someone if the account exists on LogOn, Registration or Password reset. Say something like 'Either the username or password was incorrect', or 'If this account exists then a reset token will be sent to the registered email address'. This protects against account enumeration.

The feedback to the user should be identical whether or not the account exists, both in terms of content and behaviour: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested.

A3 Cross Site Scripting

DO NOT: Trust any data the user sends you, prefer white lists (always safe) over black lists

You get encoding of all HTML content with MVC3, to properly encode all content whether HTML, javascript, CSS, LDAP etc use the Microsoft AntiXSS library:

Install-Package AntiXSS

Then set in config:

DO NOT: Use the [AllowHTML] attribute or helper class @Html.Raw unless you really know that the content you are writing to the browser is safe and has been escaped properly.

DO: Enable a Content Security Policy, this will prevent your pages from accessing assets it should not be able to access (e.g. a malicious script):

A4 Insecure Direct object references

When you have a resource (object) which can be accessed by a reference (in the sample below this is the id) then you need to ensure that the user is intended to be there

A5 Security Misconfiguration

Ensure debug and trace are off in production. This can be enforced using web.config transforms:

DO NOT: Use default passwords

DO: (When using TLS) Redirect a request made over Http to https: In Global.asax.cs:

A6 Sensitive data exposure

DO NOT: Store encrypted passwords.

DO: Use a strong hash to store password credentials. Use Argon2, PBKDF2, BCrypt or SCrypt with at least 8000 iterations and a strong key.

DO: Enforce passwords with a minimum complexity that will survive a dictionary attack i.e. longer passwords that use the full character set (numbers, symbols and letters) to increase the entropy.

DO: Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it's original format. Do not encrypt passwords. Protect encryption keys more than any other asset. Apply the following test: Would you be happy leaving the data on a spreadsheet on a bus for everyone to read. Assume the attacker can get direct access to your database and protect it accordingly.

DO: Use TLS 1.2 for your entire site. Get a free certificate LetsEncrypt.org.

DO NOT: Allow SSL, this is now obsolete.

DO: Have a strong TLS policy (see SSL Best Practises), use TLS 1.2 wherever possible. Then check the configuration using SSL Test or TestSSL.

DO: Ensure headers are not disclosing information about your application. See HttpHeaders.cs , Dionach StripHeaders or disable via web.config:

A7 Missing function level access control

DO: Authorize users on all externally facing endpoints. The .Net framework has many ways to authorize a user, use them at method level:

or better yet, at controller level:

You can also check roles in code using identity features in .net: System.Web.Security.Roles.IsUserInRole(userName, roleName)

DO: Send the anti-forgery token with every Post/Put request:

Then validate it at the method or preferably the controller level:

Make sure the tokens are removed completely for invalidation on logout.

NB: You will need to attach the anti-forgery token to Ajax requests.

After .NET Core 2.0 it is possible to automatically generate and verify the antiforgery token. Forms must have the requisite helper as seen here:

And then add the [AutoValidateAntiforgeryToken] attribute to the action result.

A9 Using components with known vulnerabilities

DO: Keep the .Net framework updated with the latest patches

Owasp Cheat Sheet

DO: Keep your NuGet packages up to date, many will contain their own vulnerabilities.

DO: Run the OWASP Dependency Checker against your application as part of your build process and act on any high level vulnerabilities.

A10 Unvalidated redirects and forwards

A protection against this was introduced in Mvc 3 template. Here is the code:

Other advice:

  • Protect against Clickjacking and man in the middle attack from capturing an initial Non-TLS request, set the X-Frame-Options and Strict-Transport-Security (HSTS) headers. Full details here
  • Protect against a man in the middle attack for a user who has never been to your site before. Register for HSTS preload
  • Maintain security testing and analysis on Web API services. They are hidden inside MEV sites, and are public parts of a site that will be found by an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.

More information:

For more information on all of the above and code samples incorporated into a sample MVC5 application with an enhanced security baseline go to Security Essentials Baseline project

  • Work within the constraints of Internet Zone security for your application.
  • Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.
  • Use partial trust when possible. Partially trusted Windows applications reduce the attack surface of an application. Manage a list of what permissions your app must use, and what it may use, and then make the request for those permissions declaratively at run time.
  • Use ClickOnce deployment. For enhanced permissions, use permission elevation at runtime or trusted application deployment at install time.

WCF Guidance

  • Keep in mind that the only safe way to pass a request in RESTful services is via HTTP POST, with TLS enabled. GETs are visible in the querystring, and a lack of TLS means the body can be intercepted.
  • Avoid BasicHttpBinding. It has no default security configuration. Use WSHttpBinding instead.
  • Use at least two security modes for your binding. Message security includes security provisions in the headers. Transport security means use of SSL. TransportWithMessageCredential combines the two.
  • Test your WCF implementation with a fuzzer like the ZAP.

Bill Sempf - bill.sempf@owasp.org

Owasp Cheat Sheet Xxe Prevention

Troy Hunt - troyhunt@hotmail.com

Jeremy Long - jeremy.long@owasp.org

Shane Murnion

John Staveley

Steve Bamelis

Owasp cheat sheet github

Owasp Cheat Sheet Xss Prevention

Xander Sherry

Owasp Xss Prevention Cheat Sheet

Sam Ferree