Recommendations for OWASP TOP 10 2017

A1- Injection

SQL Injection

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

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

  • Do not concatenate strings anywhere in your code and execute them against your database (Known as dynamic sql).

  • Practice 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

Compliant Code

var sql = @"Update [User] SET FirstName = @FirstName WHERE Id = @Id";
    new SqlParameter("@FirstName", firstname),
    new SqlParameter("@Id", id));

Non-compliant Code

string strQry = "SELECT * FROM Users WHERE UserName='" + txtUser.Text + "' AND Password='" + txtPassword.Text + "'";
EXEC strQry // SQL Injection vulnerability!

OS Injection

Compliant Code

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "validatedCommand";
startInfo.Arguments = "validatedArg1 validatedArg2 validatedArg3";
process.StartInfo = startInfo;
  • Use whitelist validation on all user supplied input. Input validation prevents improperly formed data from entering an information system.

e.g Validating user input using IPAddress.TryParse Method

Compliant Code

//User input
string ipAddress = "";

//check to make sure an ip address was provided
if (!string.IsNullOrEmpty(ipAddress))
 // Create an instance of IPAddress for the specified address string (in
 // dotted-quad, or colon-hexadecimal notation).
 if (IPAddress.TryParse(ipAddress, out var address))
  // Display the address in standard notation.
  return address.ToString();
  //ipAddress is not of type IPAddress

A2 Broken Authentication

  • Use ASP.net Core Identity. ASP.net Core Identity framework is well configured by default, where it uses secure password hashes and an individual salt. Identity uses the PBKDF2 hashing function for passwords, and they generate a random salt per user.

  • Set secure password policy

e.g ASP.net Core Identity

services.Configure<IdentityOptions>(options =>
 // Password settings
 options.Password.RequireDigit = true;
 options.Password.RequiredLength = 8;
 options.Password.RequireNonAlphanumeric = true;
 options.Password.RequireUppercase = true;
 options.Password.RequireLowercase = true;
 options.Password.RequiredUniqueChars = 6;

 options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
 options.Lockout.MaxFailedAccessAttempts = 3;

 options.SignIn.RequireConfirmedEmail = true;

 options.User.RequireUniqueEmail = true;
  • Set a cookie policy


services.ConfigureApplicationCookie(options =>
 options.Cookie.HttpOnly = true;
 options.Cookie.Expiration = TimeSpan.FromHours(1)
 options.SlidingExpiration = true;

A3 Sensitive Data Exposure

  • Do not Store encrypted passwords.

  • Use a strong hash to store password credentials. For hash refer to this section.

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

  • Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it’s original format. Protect encryption keys more than any other asset, please find more information of storing encryption keys at rest. 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. More information can be found here.

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

DO NOT: Allow SSL, this is now obsolete.

More information on Transport Layer Protection can be found here. e.g Web.config

    <httpRuntime enableVersionHeader="false"/>
        <requestFiltering removeServerHeader="true" />
            <add name="X-Content-Type-Options" value="nosniff" />
            <add name="X-Frame-Options" value="DENY" />
            <add name="X-Permitted-Cross-Domain-Policies" value="master-only"/>
            <add name="X-XSS-Protection" value="0"/>
            <remove name="X-Powered-By"/>

e.g Startup.cs

app.UseHsts(hsts => hsts.MaxAge(365).IncludeSubdomains());
app.UseReferrerPolicy(opts => opts.NoReferrer());
app.UseXXssProtection(options => options.FilterDisabled());
app.UseXfo(options => options.Deny());

app.UseCsp(opts => opts
 .StyleSources(s => s.Self())
 .StyleSources(s => s.UnsafeInline())
 .FontSources(s => s.Self())
 .FormActions(s => s.Self())
 .FrameAncestors(s => s.Self())
 .ImageSources(s => s.Self())
 .ScriptSources(s => s.Self())

For more information about headers can be found here.

A4 XML External Entities (XXE)

XXE attacks occur when an XML parse does not properly process user input that contains external entity declaration in the doctype of an XML payload.

Below are the three most common XML Processing Options for .NET.

The following information for XXE injection in .NET is directly from this web application of unit tests by Dean Fleming.

This web application covers all currently supported .NET XML parsers, and has test cases for each demonstrating when they are safe from XXE injection and when they are not.

Previously, this information was based on James Jardine’s excellent .NET XXE article.

It originally provided more recent and more detailed information than the older article from Microsoft on how to prevent XXE and XML Denial of Service in .NET, however, it has some inaccuracies that the web application covers.

The following table lists all supported .NET XML parsers and their default safety levels:

XML ParserSafe by default?
…prior to 4.5.2No
…in versions 4.5.2+Yes
…prior to 4.5.2No
…in versions 4.5.2+Yes
…prior to 4.5.2No
…in versions 4.5.2+Yes


Both the XElement and XDocument objects in the System.Xml.Linq library are safe from XXE injection by default. XElement parses only the elements within the XML file, so DTDs are ignored altogether. XDocument has DTDs disabled by default, and is only unsafe if constructed with a different unsafe XML parser.


System.Xml.XmlDictionaryReader is safe by default, as when it attempts to parse the DTD, the compiler throws an exception saying that “CData elements not valid at top level of an XML document”. It becomes unsafe if constructed with a different unsafe XML parser.


Prior to .NET Framework version 4.5.2, System.Xml.XmlDocument is unsafe by default. The XmlDocument object has an XmlResolver object within it that needs to be set to null in versions prior to 4.5.2. In versions 4.5.2 and up, this XmlResolver is set to null by default.

The following example shows how it is made safe:

 static void LoadXML()
   string xxePayload = "<!DOCTYPE doc [<!ENTITY win SYSTEM 'file:///C:/Users/testdata2.txt'>]>"
                     + "<doc>&win;</doc>";
   string xml = "<?xml version='1.0' ?>" + xxePayload;

   XmlDocument xmlDoc = new XmlDocument();
   // Setting this to NULL disables DTDs - Its NOT null by default.
   xmlDoc.XmlResolver = null;

XmlDocument can become unsafe if you create your own nonnull XmlResolver with default or unsafe settings. If you need to enable DTD processing, instructions on how to do so safely are described in detail in the referenced MSDN article.


System.Xml.XmlNodeReader objects are safe by default and will ignore DTDs even when constructed with an unsafe parser or wrapped in another unsafe parser.


System.Xml.XmlReader objects are safe by default.

They are set by default to have their ProhibitDtd property set to false in .NET Framework versions 4.0 and earlier, or their DtdProcessing property set to Prohibit in .NET versions 4.0 and later.

Additionally, in .NET versions 4.5.2 and later, the XmlReaderSettings belonging to the XmlReader has its XmlResolver set to null by default, which provides an additional layer of safety.

Therefore, XmlReader objects will only become unsafe in version 4.5.2 and up if both the DtdProcessing property is set to Parse and the XmlReaderSetting’s XmlResolver is set to a nonnull XmlResolver with default or unsafe settings. If you need to enable DTD processing, instructions on how to do so safely are described in detail in the referenced MSDN article.


System.Xml.XmlTextReader is unsafe by default in .NET Framework versions prior to 4.5.2. Here is how to make it safe in various .NET versions:

Prior to .NET 4.0

In .NET Framework versions prior to 4.0, DTD parsing behavior for XmlReader objects like XmlTextReader are controlled by the Boolean ProhibitDtd property found in the System.Xml.XmlReaderSettings and System.Xml.XmlTextReader classes.

Set these values to true to disable inline DTDs completely.

XmlTextReader reader = new XmlTextReader(stream);
// NEEDED because the default is FALSE!!
reader.ProhibitDtd = true;

.NET 4.0 - .NET 4.5.2

In .NET Framework version 4.0, DTD parsing behavior has been changed. The ProhibitDtd property has been deprecated in favor of the new DtdProcessing property.

However, they didn’t change the default settings so XmlTextReader is still vulnerable to XXE by default.

Setting DtdProcessing to Prohibit causes the runtime to throw an exception if a <!DOCTYPE> element is present in the XML.

To set this value yourself, it looks like this:

XmlTextReader reader = new XmlTextReader(stream);
// NEEDED because the default is Parse!!
reader.DtdProcessing = DtdProcessing.Prohibit;

Alternatively, you can set the DtdProcessing property to Ignore, which will not throw an exception on encountering a <!DOCTYPE> element but will simply skip over it and not process it. Finally, you can set DtdProcessing to Parse if you do want to allow and process inline DTDs.

.NET 4.5.2 and later

In .NET Framework versions 4.5.2 and up, XmlTextReader’s internal XmlResolver is set to null by default, making the XmlTextReader ignore DTDs by default. The XmlTextReader can become unsafe if if you create your own nonnull XmlResolver with default or unsafe settings.


System.Xml.XPath.XPathNavigator is unsafe by default in .NET Framework versions prior to 4.5.2.

This is due to the fact that it implements IXPathNavigable objects like XmlDocument, which are also unsafe by default in versions prior to 4.5.2.

You can make XPathNavigator safe by giving it a safe parser like XmlReader (which is safe by default) in the XPathDocument’s constructor.

Here is an example:

XmlReader reader = XmlReader.Create("example.xml");
XPathDocument doc = new XPathDocument(reader);
XPathNavigator nav = doc.CreateNavigator();
string xml = nav.InnerXml.ToString();


System.Xml.Xsl.XslCompiledTransform (an XML transformer) is safe by default as long as the parser it’s given is safe.

It is safe by default because the default parser of the Transform() methods is an XmlReader, which is safe by default (per above).

The source code for this method is here.

Some of the Transform() methods accept an XmlReader or IXPathNavigable (e.g., XmlDocument) as an input, and if you pass in an unsafe XML Parser then the Transform will also be unsafe.

A5 Broken Access Control

Weak Account management

  • Ensure cookies are sent via httpOnly:

    CookieHttpOnly = true,
  • Reduce the time period a session can be stolen in by reducing session timeout and removing sliding expiration:

    ExpireTimeSpan = TimeSpan.FromMinutes(60),
    SlidingExpiration = false

    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:

    <httpCookies requireSSL="true" xdt:Transform="SetAttributes(requireSSL)"/>
        <forms requireSSL="true" xdt:Transform="SetAttributes(requireSSL)"/>
  • Protect LogOn, Registration and password reset methods against brute force attacks by throttling requests (see code below), consider also using ReCaptcha.

    [AllowXRequestsEveryXSecondsAttribute(Name = "LogOn",
    Message = "You have performed this action more than {x} times in the last {n} seconds.",
    Requests = 3, Seconds = 60)]
    public async Task<ActionResult> LogOn(LogOnViewModel model, string returnUrl)
  • 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 behavior: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested.

Missing function-level access control

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

[Authorize(Roles = "Admin")]
public ActionResult Index(int page = 1)

or better yet, at controller level:

public class UserController

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

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

Non-compliant Code

public ActionResult Edit(int id)
  var user = _context.Users.FirstOrDefault(e => e.Id == id);
  return View("Details", new UserViewModel(user);

Compliant Code

public ActionResult Edit(int id)
  var user = _context.Users.FirstOrDefault(e => e.Id == id);
  // Establish user has right to edit the details
  if (user.Id != _userIdentity.GetUserId())
        HandleErrorInfo error = new HandleErrorInfo(
            new Exception("INFO: You do not have permission to edit these details"));
        return View("Error", error);
  return View("Edit", new UserViewModel(user);

A6 Security Misconfiguration

Debug and Stack Trace

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

<compilation xdt:Transform="RemoveAttributes(debug)" />
<trace enabled="false" xdt:Transform="Replace"/>
  • Do not use default passwords

  • When using TLS, redirect a request made over Http to https:

e.g Global.asax.cs

protected void Application_BeginRequest()
    #if !DEBUG
    // SECURE: Ensure any request is returned over SSL/TLS in production
    if (!Request.IsLocal && !Context.Request.IsSecureConnection) {
        var redirect = Context.Request.Url.ToString()
                        .Replace("http:", "https:");

e.g Startup.cs in the Configure()


Cross-site request forgery

  • Do not send sensitive data without validating Anti-Forgery-Tokens (.NET / .NET Core).

  • Send the anti-forgery token with every POST/PUT request:

Using .NET Framework

    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm",
                            @class = "pull-right" }))
        <ul class="nav nav-pills">
            <li role="presentation">
            Logged on as @User.Identity.Name
            <li role="presentation">
            <a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>

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

public ActionResult LogOff()

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

Compliant Code

/// <summary>
    Remove any remaining cookies including Anti-CSRF cookie
/// </summary>
public void RemoveAntiForgeryCookie(Controller controller)
    string[] allCookies = controller.Request.Cookies.AllKeys;
    foreach (string cookie in allCookies)
        if (controller.Response.Cookies[cookie] != null &&
            cookie == "__RequestVerificationToken")
            controller.Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);

Using .NET Core 2.0 or later

Starting with .NET Core 2.0 it is possible to automatically generate and verify the antiforgery token.

If you are using tag-helpers, which is the default for most web project templates, then all forms will automatically send the anti-forgery token. You can check if tag-helpers are enabled by checking if your main _ViewImports.cshtml file contains:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

IHtmlHelper.BeginForm also sends anti-forgery-tokens automatically.

Unless you are using tag-helpers or IHtmlHelper.BeginForm, you must use the requisite helper on forms as seen here:

<form action="RelevantAction">@Html.AntiForgeryToken()</form>

To automatically validate all requests other than GET, HEAD, OPTIONS and TRACE you need to add a global action filter with the AutoValidateAntiforgeryToken attribute inside your Startup.cs as mentioned in the following article:

services.AddMvc(options =>
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());

If you need to disable the attribute validation for a specific method on a controller you can add the IgnoreAntiforgeryToken attribute to the controller method (for MVC controllers) or parent class (for Razor pages):

public IActionResult Delete()
public class UnsafeModel : PageModel

If you need to also validate the token on GET, HEAD, OPTIONS or TRACE - requests you can add the ValidateAntiforgeryToken attribute to the controller method (for MVC controllers) or parent class (for Razor pages):

public IActionResult DoSomethingDangerous()
public class SafeModel : PageModel

In case you can’t use a global action filter, add the AutoValidateAntiforgeryToken attribute to your controller classes or razor page models:

public class UserController
public class SafeModel : PageModel

Using .Net Core 2.0 or .NET Framework with AJAX

You will need to attach the anti-forgery token to AJAX requests.

If you are using jQuery in an ASP.NET Core MVC view this can be achieved using this snippet:

@inject  Microsoft.AspNetCore.Antiforgery.IAntiforgery antiforgeryProvider
    type: "POST",
    url: '@Url.Action("Action", "Controller")',
    contentType: "application/x-www-form-urlencoded; charset=utf-8",
    data: {
        id: id,
        '__RequestVerificationToken': '@antiforgeryProvider.GetAndStoreTokens(this.Context).RequestToken'

If you are using the .NET Framework, you can find some code snippets [here](https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks#anti-csrf-and-ajax).

More information can be found [here](Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.md) for Cross-Site Request Forgery.

A7 Cross-Site Scripting (XSS)

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:

<httpRuntime targetFramework="4.5"
encoderType="Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary"
maxRequestLength="4096" />

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):

            <add name="Content-Security-Policy"
                value="default-src 'none'; style-src 'self'; img-src 'self';
                font-src 'self'; script-src 'self'" />

More information can be found here for Cross-Site Scripting.

A8 Insecure Deserialization

  • Do not accept Serialized Objects from Untrusted Sources

  • Validate User Input Malicious users are able to use objects like cookies to insert malicious information to change user roles. In some cases, hackers are able to elevate their privileges to administrator rights by using a pre-existing or cached password hash from a previous session.

  • Prevent Deserialization of Domain Objects

  • Run the Deserialization Code with Limited Access Permissions If a deserialized hostile object tries to initiate a system processes or access a resource within the server or the host’s OS, it will be denied access and a permission flag will be raised so that a system administrator is made aware of any anomalous activity on the server.

A9 Using Components with Known Vulnerabilities

  • Keep the .Net framework updated with the latest patches

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

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

A10 Insufficient Logging & Monitoring

  • Ensure all login, access control failures and server-side input validation failures can be logged with sufficient user context to identify suspicious or malicious accounts.

  • Establish effective monitoring and alerting so suspicious activities are detected and responded to in a timely fashion.

  • Do not log generic error messages such as: csharp Log.Error("Error was thrown"); rather log the stack trace, error message and user ID who caused the error.

  • Do not log sensitive data such as user’s passwords.


What Logs to Collect and more information about Logging can be found on this cheat sheet.

.NET Core comes with a LoggerFactory, which is in Microsoft.Extensions.Logging. More information about ILogger can be found here.

How to log all errors from the Startup.cs, so that anytime an error is thrown it will be logged.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 if (env.IsDevelopment())
  _isDevelopment = true;

 //Log all errors in the application
 app.UseExceptionHandler(errorApp =>
  errorApp.Run(async context =>
      var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
      var exception = errorFeature.Error;

      Log.Error(String.Format("Stacktrace of error: {0}",exception.StackTrace.ToString()));


e.g Injecting into the class constructor, which makes writing unit test simpler. It is recommended if instances of the class will be created using dependency injection (e.g. MVC controllers). The below example shows logging of all unsuccessful log in attempts.

public class AccountsController : Controller
        private ILogger _Logger;

        public AccountsController( ILogger logger)
            _Logger = logger;

        public async Task<IActionResult> Login(LoginViewModel model)
            if (ModelState.IsValid)
                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
   //Log all successful log in attempts
   Log.Information(String.Format("User: {0}, Successfully Logged in", model.Email));
   //Code for successful login
   //Log all incorrect log in attempts
   Log.Information(String.Format("User: {0}, Incorrect Password", model.Email));


Logging levels for ILogger are listed below, in order of high to low importance:


Monitoring allow us to validate the performance and health of a running system through key performance indicators.

In .NET a great option to add monitoring capabilities is Application Insights.

More information about Logging and Monitoring can be found here.

Other Security vulnerabilties

Unvalidated redirects and forwards

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

public async Task<ActionResult> LogOn(LogOnViewModel model, string returnUrl)
    if (ModelState.IsValid)
        var logonResult = await _userManager.TryLogOnAsync(model.UserName, model.Password);
        if (logonResult.Success)
            await _userManager.LogOnAsync(logonResult.UserName, model.RememberMe);
            return RedirectToLocal(returnUrl);
private ActionResult RedirectToLocal(string returnUrl)
    if (Url.IsLocalUrl(returnUrl))
        return Redirect(returnUrl);
        return RedirectToAction("Landing", "Account");