.NET

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";
context.Database.ExecuteSqlCommand(
    sql,
    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;
process.Start();
  • 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 = "127.0.0.1";

//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();
 }
 else
 {
  //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

//startup.cs
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

e.g

//startup.cs
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

<system.web>
    <httpRuntime enableVersionHeader="false"/>
</system.web>
<system.webServer>
    <security>
        <requestFiltering removeServerHeader="true" />
    </security>
    <httpProtocol>
        <customHeaders>
            <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"/>
        </customHeaders>
    </httpProtocol>
</system.webServer>

e.g Startup.cs

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

app.UseCsp(opts => opts
 .BlockAllMixedContent()
 .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?
LINQ to XMLYes
XmlDictionaryReaderYes
XmlDocument
…prior to 4.5.2No
…in versions 4.5.2+Yes
XmlNodeReaderYes
XmlReaderYes
XmlTextReader
…prior to 4.5.2No
…in versions 4.5.2+Yes
XPathNavigator
…prior to 4.5.2No
…in versions 4.5.2+Yes
XslCompiledTransformYes

LINQ to XML

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.

XmlDictionaryReader

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.

XmlDocument

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;
   xmlDoc.LoadXml(xml);
   Console.WriteLine(xmlDoc.InnerText);
   Console.ReadLine();
 }

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.

XmlNodeReader

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.

XmlReader

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.

XmlTextReader

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.

XPathNavigator

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();

XslCompiledTransform

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

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    [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")]
[HttpGet]
public ActionResult Index(int page = 1)

or better yet, at controller level:

[Authorize]
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()
                        .ToLower(CultureInfo.CurrentCulture)
                        .Replace("http:", "https:");
        Response.Redirect(redirect);
    }
    #endif
}

e.g Startup.cs in the Configure()

  app.UseHttpsRedirection();

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" }))
    {
        @Html.AntiForgeryToken()
        <ul class="nav nav-pills">
            <li role="presentation">
            Logged on as @User.Identity.Name
            </li>
            <li role="presentation">
            <a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>
            </li>
        </ul>
    }

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

[HttpPost]
[ValidateAntiForgeryToken]
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):

[IgnoreAntiforgeryToken]
[HttpDelete]
public IActionResult Delete()
[IgnoreAntiforgeryToken]
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):

[HttpGet]
[ValidateAntiforgeryToken]
public IActionResult DoSomethingDangerous()
[HttpGet]
[ValidateAntiforgeryToken]
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:

[AutoValidateAntiforgeryToken]
public class UserController
[AutoValidateAntiforgeryToken]
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:

```javascript
@inject  Microsoft.AspNetCore.Antiforgery.IAntiforgery antiforgeryProvider
$.ajax(
{
    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:

<system.web>
<httpRuntime targetFramework="4.5"
enableVersionHeader="false"
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):

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <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.

Logging

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;
  app.UseDeveloperExceptionPage();
 }

 //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()));
  });
 });

        app.UseAuthentication();
            app.UseMvc();
        }
}

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;
        }

 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        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
  }
  else
  {
   //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

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);
    }
    else
    {
        return RedirectToAction("Landing", "Account");
    }
}

References