Sql Injection Cheat Sheet Owasp

Posted : admin On 1/1/2022
  1. Sql Injection Cheat Sheet Owasp Pdf
  2. Blind Sql Injection Cheat Sheet Owasp
  3. Owasp Cheat Sheet Series
  4. Owasp Sql Injection Attacks
  5. Sql Injection Cheat Sheet Owasp

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

The code has to be injected in such a way that the SQL statement should generate a valid result upon execution. If the executed SQL query has errors in the syntax, it won't fetch a valid result. So filling in random SQL commands and submitting the form will not always result in successful authentication. The following articles describe how to exploit different kinds of SQL Injection Vulnerabilities on various platforms that this article was created to help you avoid: SQL Injection Cheat Sheet; Bypassing WAF's with SQLi - SQL Injection Bypassing WAF; Description of SQL Injection Vulnerabilities: OWASP article on SQL Injection Vulnerabilities. OWASP SQL Injection cheat sheet. StackOverflow question and useful answers. Hacksplaining article on parameterised queries. 5 – Preventing Unauthorised Operations with Permissions.

SQL injection attacks are typically created as a resulted of dynamic database queries that include user supplied input. Specifically, we will use 'Mutillidae - OWASP 2013 - A1 - Injection (SQL) - SQLi - Extract Data - User Info (SQL)”. First on our agenda is to test the page to see if the possibility exists for an SQL injection. SQL Injection is one of the most dangerous web vulnerabilities. So much so that it's the #1 item in the OWASP Top 10. It represents a serious threat because SQL Injection allows evil attacker code to change the structure of a web application's SQL statement in a way that can steal data, modify data, or potentially facilitate command injection to the underlying OS.

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.
Cheat
  • 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.

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

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

Troy Hunt - [email protected]

Jeremy Long - [email protected]

Shane Murnion

Sql Injection Cheat Sheet Owasp Pdf

John Staveley

Steve Bamelis

Xander Sherry

Sam Ferree

Welcome to this new episode of the OWASP Top 10 vulnerabilities course, where we explain in detail each vulnerability. In this blog post, you will learn SQL injection.
This is a subset of the OWASP Top 10 injection vulnerabilities. If you’d like to have a bigger picture of Injection, I invite you to read this blog post before continuing.

What is SQL injection?

This vulnerability happens where the application processes malicious user input to query a SQL database. A n example would be the login feature of an admin portal. In fact, a vulnerable piece of code could be as follows:

The code above expects two user inputs, an email and a password. Then, it constructs a SQL query by concatenating the email and password. From there, if the result is not empty, the application allows the user to access the administration dashboard.

The idea is to construct a valid SQL query while bypassing the password protection. If we try the payload ‘ or 1=1;– in the email input and dummy in the password, the resulting SQL query would be:

It is a valid SQL query which always returns true since 1 is always equal to 1. Besides, the double dashes comment out the rest of the SQL query. The result will pass the check and give us admin access without knowing neither the email nor the password.

You can practice SQL injection by going to the SQL injection hands-on examples blog post.

SQL injection attacks

This vulnerability is really impactful. I mentioned the TalkTalk’s breach on the OWASP Top 10 Injection blog post, which should give you an insight into how serious SQL injection could be. The following is a list of publicly available reports which bug bounty hunters reported on HackerOne. I’ll invite you to read my write-up, which I found on a private HackerOne program. So, make sure to subscribe to the newsletter to be notified.

  • $4000 bug report: It is a well written report on an error-based SQL injection which affected Starbucks.
  • $2000 vulnerability report: It is a blind SQL injection vulnerability that the ethical hacker found on labs.data.gov.
  • Blind injection affecting the US Department Of Defense.

How to exploit SQL injection manually?

The first thing is to determine if it is an error or blind based injection.

Error based SQL injection

Blind Sql Injection Cheat Sheet Owasp

The most basic test is to trigger an exception by injecting either single or double quotes, unless there is some protection filter in place. From there, just rely on the errors and try to either get unauthorized access or read sensitive data. There is a detailed blog post about this approach in the SQL injection practical examples.

Blind SQL injection

If the application doesn’t return any errors, try to provoke a time delay using a sleep. If it doesn’t work, try to spot any difference in the HTTP response between a SQL query which returns true and another which returns false.

As an ethical hacker, be very cautious when manipulating the SQL query! You should avoid altering or deleting data unless explicitly permitted by your client. Losing data can lead to serious business losses and will harm your reputation.

How to exploit SQL injection using automated tools

Owasp Cheat Sheet Series

You can use automated testing once you find a vulnerability manually. Alternatively, you can use automated scanners to speed up your testing process if you have a large number of user inputs. You can use either OWASP Zap, Burp Suite or Sqlmap to test for this vulnerability automatically. I cover each one of them in this hands-on OWASP Top 10 training.

Owasp Sql Injection Attacks

How to prevent SQL injection?

Sql Injection Cheat Sheet Owasp

As it turns out, fixing this highly impactful security vulnerability is extremely simple. As a developer, the most effective and primary protection against this deadly vulnerability is to use prepared statements. This OWASP SQL injection Prepared Statements Cheat Sheet explains how to use it in all major programming languages.

Another approach would be to use stored procedures, where the SQL queries are stored on a database and no user input is dynamically inserted into them.

You can also use a whitelist to control parts of your SQL query before executing it. For example, if you search a store by category, you may want to validate that the category parameter is included in a list of whitelisted categories. If successful, then you run the SQL query. However, I wouldn’t recommend it as a primary defense. You can use it as a secondary defense mechanism.

Another secondary defense would be to apply protection filters which would sanitize and escape the user inputs. However, this can be bypassed.

Sql

You can find more on this topic on the OWASP prevention Cheat Sheet.

SQL injection common filters bypass

To prevent SQL injection, developers use common filters to check user input. Unfortunately, they can be bypassed. Whether you are As a developer or an ethical hacker, you should be aware of them. So please take your time understanding the idea behind these filters, this will enrich your skills whether you are a developer or an ethical hacker.

That’s it for today! Hopefully you’ve learnt a lot during this episode. If you enjoyed learning from this content, make sure to subscribe to the newsletter. I update all the subscribers on each Friday.