DotNet Security Cheat Sheet¶

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.

The .NET Framework constitutes a collection of APIs that facilitate the usage of an advanced type system, managing data, graphics, networking, file operations, and more - essentially covering the vast majority of requirements for developing enterprise applications within the Microsoft ecosystem. It is a nearly ubiquitous library that is strongly named and versioned at the assembly level.

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

Security Announcements¶

Receive security notifications by selecting the "Watch" button at the following repositories:

.NET General Guidance¶

This section contains general guidance for .NET applications. This applies to all .NET applications, including ASP.NET, WPF, WinForms, and others.

The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every few years and updated with the latest threat data. This section of the cheat sheet is based on this list. 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 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.

A01 Broken Access Control¶

Weak Account management¶

Ensure cookies are sent with the HttpOnly flag set to prevent client side scripts from accessing the cookie:

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 an example of a full startup code snippet.

Ensure cookies are sent over HTTPS in production. This should be enforced in the config transforms:

 requireSSL="true" />  requireSSL="true" />  

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 times in the last seconds.", Requests = 3, Seconds = 60)] public async TaskActionResult> LogOn(LogOnViewModel model, string returnUrl) 

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 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¶

DO: 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 ), you need to ensure that the user is intended to have access to that resource.

// Insecure public ActionResult Edit(int id)  var user = _context.Users.FirstOrDefault(e => e.Id == id); return View("Details", new UserViewModel(user); > // Secure 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); > 

A02 Cryptographic Failures¶

General cryptography guidance¶

Hashing¶

DO: Use a strong hashing algorithm.

Passwords¶

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

Encryption¶

DO: Use a strong encryption algorithm such as AES-512 where personally identifiable data needs to be restored to it's original format.

DO: Protect encryption keys more than any other asset. Find more information about storing encryption keys at rest in the Key Management Cheat Sheet.

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

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

More information on Transport Layer Protection can be found in the Transport Layer Security Cheat Sheet.

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

  enableVersionHeader="false"/>    removeServerHeader="true" />    name="X-Content-Type-Options" value="nosniff" />  name="X-Frame-Options" value="DENY" />  name="X-Permitted-Cross-Domain-Policies" value="master-only"/>  name="X-XSS-Protection" value="0"/>  name="X-Powered-By"/>    
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()) ); 

More information about headers can be found at the OWASP Secure Headers Project.

Encryption for storage¶

The following code snippet shows an example of using AES-GCM to perform encryption/decryption of data. It is strongly recommended to have a cryptography expert review your final design and code, as even the most trivial error can severely weaken your encryption.

A few constraints/pitfalls with this code:

// Code based on example from here: // https://www.scottbrady91.com/c-sharp/aes-gcm-dotnet public class AesGcmSimpleTest  public static void Main()  // Key of 32 bytes / 256 bits for AES var key = new byte[32]; RandomNumberGenerator.Fill(key); // MaxSize = 12 bytes / 96 bits and this size should always be used. var nonce = new byte[AesGcm.NonceByteSizes.MaxSize]; RandomNumberGenerator.Fill(nonce); // Tag for authenticated encryption var tag = new byte[AesGcm.TagByteSizes.MaxSize]; var message = "This message to be encrypted"; Console.WriteLine(message); // Encrypt the message var cipherText = AesGcmSimple.Encrypt(message, nonce, out tag, key); Console.WriteLine(Convert.ToBase64String(cipherText)); // Decrypt the message var message2 = AesGcmSimple.Decrypt(cipherText, nonce, tag, key); Console.WriteLine(message2); > > public static class AesGcmSimple  public static byte[] Encrypt(string plaintext, byte[] nonce, out byte[] tag, byte[] key)  using(var aes = new AesGcm(key))  // Tag for authenticated encryption tag = new byte[AesGcm.TagByteSizes.MaxSize]; // Create a byte array from the message to encrypt var plaintextBytes = Encoding.UTF8.GetBytes(plaintext); // Ciphertext will be same length in bytes as plaintext var ciphertext = new byte[plaintextBytes.Length]; // perform the actual encryption aes.Encrypt(nonce, plaintextBytes, ciphertext, tag); return ciphertext; > > public static string Decrypt(byte[] ciphertext, byte[] nonce, byte[] tag, byte[] key)  using(var aes = new AesGcm(key))  // Plaintext will be same length in bytes as Ciphertext var plaintextBytes = new byte[ciphertext.Length]; // perform the actual decryption aes.Decrypt(nonce, ciphertext, tag, plaintextBytes); return Encoding.UTF8.GetString(plaintextBytes); > > > 

Encryption for transmission¶

The following code snippet shows an example of using Eliptic Curve/Diffie Helman (ECDH) together with AES-GCM to perform encryption/decryption of data between two different sides without the need the transfer the symmetric key between the two sides. Instead, the sides exchange public keys and can then use ECDH to generate a shared secret which can be used for the symmetric encryption.

Again, it is strongly recommended to have a cryptography expert review your final design and code, as even the most trivial error can severely weaken your encryption.

Note that this code sample relies on the AesGcmSimple class from the previous section.

A few constraints/pitfalls with this code:

public class ECDHSimpleTest  public static void Main()  // Generate ECC key pair for Alice var alice = new ECDHSimple(); byte[] alicePublicKey = alice.PublicKey; // Generate ECC key pair for Bob var bob = new ECDHSimple(); byte[] bobPublicKey = bob.PublicKey; string plaintext = "Hello, Bob! How are you?"; Console.WriteLine("Secret being sent from Alice to Bob: " + plaintext); // Note that a new nonce is generated with every encryption operation in line with // in line with the AES GCM security byte[] tag; byte[] nonce; var cipherText = alice.Encrypt(bobPublicKey, plaintext, out nonce, out tag); Console.WriteLine("Ciphertext, nonce, and tag being sent from Alice to Bob: " + Convert.ToBase64String(cipherText) + " " + Convert.ToBase64String(nonce) + " " + Convert.ToBase64String(tag)); var decrypted = bob.Decrypt(alicePublicKey, cipherText, nonce, tag); Console.WriteLine("Secret received by Bob from Alice: " + decrypted); Console.WriteLine(); string plaintext2 = "Hello, Alice! I'm good, how are you?"; Console.WriteLine("Secret being sent from Bob to Alice: " + plaintext2); byte[] tag2; byte[] nonce2; var cipherText2 = bob.Encrypt(alicePublicKey, plaintext2, out nonce2, out tag2); Console.WriteLine("Ciphertext, nonce, and tag being sent from Bob to Alice: " + Convert.ToBase64String(cipherText2) + " " + Convert.ToBase64String(nonce2) + " " + Convert.ToBase64String(tag2)); var decrypted2 = alice.Decrypt(bobPublicKey, cipherText2, nonce2, tag2); Console.WriteLine("Secret received by Alice from Bob: " + decrypted2); > > public class ECDHSimple  private ECDiffieHellmanCng ecdh = new ECDiffieHellmanCng(); public byte[] PublicKey  get  return ecdh.PublicKey.ToByteArray(); > > public byte[] Encrypt(byte[] partnerPublicKey, string message, out byte[] nonce, out byte[] tag)  // Generate the AES Key and Nonce var aesKey = GenerateAESKey(partnerPublicKey); // Tag for authenticated encryption tag = new byte[AesGcm.TagByteSizes.MaxSize]; // MaxSize = 12 bytes / 96 bits and this size should always be used. // A new nonce is generated with every encryption operation in line with // the AES GCM security model nonce = new byte[AesGcm.NonceByteSizes.MaxSize]; RandomNumberGenerator.Fill(nonce); // return the encrypted value return AesGcmSimple.Encrypt(message, nonce, out tag, aesKey); > public string Decrypt(byte[] partnerPublicKey, byte[] ciphertext, byte[] nonce, byte[] tag)  // Generate the AES Key and Nonce var aesKey = GenerateAESKey(partnerPublicKey); // return the decrypted value return AesGcmSimple.Decrypt(ciphertext, nonce, tag, aesKey); > private byte[] GenerateAESKey(byte[] partnerPublicKey)  // Derive the secret based on this side's private key and the other side's public key byte[] secret = ecdh.DeriveKeyMaterial(CngKey.Import(partnerPublicKey, CngKeyBlobFormat.EccPublicBlob)); byte[] aesKey = new byte[32]; // 256-bit AES key Array.Copy(secret, 0, aesKey, 0, 32); // Copy first 32 bytes as the key return aesKey; > > 

A03 Injection¶

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. More Information can be found in the Query Parameterization Cheat Sheet.

E.g., using Entity Framework:

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

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

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

string sql = "SELECT * FROM Users WHERE UserName='" + txtUser.Text + "' AND Password='" + txtPassword.Text + "'"; context.Database.ExecuteSqlCommand(sql); // SQL Injection vulnerability! 

DO: Practice Least Privilege - connect to the database using an account with a minimum set of permissions required to do its job, not the database administrator account.

OS Injection¶

General guidance about OS Injection can be found in the OS Command Injection Defense Cheat Sheet.

DO: Use System.Diagnostics.Process.Start to call underlying OS functions.

var process = new System.Diagnostics.Process(); var startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.FileName = "validatedCommand"; startInfo.Arguments = "validatedArg1 validatedArg2 validatedArg3"; process.StartInfo = startInfo; process.Start(); 

DO NOT: Assume that this mechanism will protect against malicious input designed to break out of one argument and then tamper with another argument to the process. This will still be possible.

DO: Use allowlist validation on all user supplied input wherever possible. Input validation prevents improperly formed data from entering an information system. For more information please see the Input Validation Cheat Sheet.

e.g Validating user input using IPAddress.TryParse Method

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

DO: Try to only accept characters which are simple alphanumeric.

DO NOT: Assume you can sanitize special characters without actually removing them. Various combinations of \ , ' and @ may have an unexpected impact on sanitization attempts.

DO NOT: Rely on methods without a security guarantee.

e.g. .NET Core 2.2 and greater and .NET 5 and greater support ProcessStartInfo.ArgumentList which performs some character escaping but the object includes a disclaimer that it is not safe with untrusted input.

DO: Look at alternatives to passing raw untrusted arguments via command-line parameters such as encoding using Base64 (which would safely encode any special characters as well) and then decode the parameters in the receiving application.

LDAP injection¶

Almost any characters can be used in Distinguished Names. However, some must be escaped with the backslash \ escape character. A table showing which characters that should be escaped for Active Directory can be found at the in the LDAP Injection Prevention Cheat Sheet.

Note: The space character must be escaped only if it is the leading or trailing character in a component name, such as a Common Name. Embedded spaces should not be escaped.

More information can be found in the LDAP Injection Prevention Cheat Sheet.

A04 Insecure Design¶

Insecure design refers to security failures in the design of the application or system. This is different than the other items in the OWASP Top 10 list which refer to implementation failures. The topic of secure design is therefore not related to a specific technology or language and is therefore out of scope for this cheat sheet. See the Secure Product Design Cheat Sheet for more information.

A05 Security Misconfiguration¶

Debug and Stack Trace¶

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

 xdt:Transform="RemoveAttributes(debug)" />  enabled="false" xdt:Transform="Replace"/> 

DO NOT: Use default passwords

DO: Redirect a request made over HTTP to HTTPS:

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

 app.UseHttpsRedirection(); 

Cross-site request forgery¶

DO NOT: Send sensitive data without validating Anti-Forgery-Tokens (.NET / .NET Core).

DO: 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 offa> 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.

/// /// SECURE: Remove any remaining cookies including Anti-CSRF cookie ///  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¶

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.

If you are not 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 and 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 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 $.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.

A06 Vulnerable and Outdated Components¶

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

DO: Keep your NuGet packages up to date

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

DO: Include SCA (software composition analysis) tools in your CI/CD pipeline to ensure that any new vulnerabilities in your dependencies are detected and acted upon.

A07 Identification and Authentication Failures¶

DO: 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 generates a random salt per user.

DO: Set secure password policy

e.g ASP.NET Core Identity

//Startup.cs services.ConfigureIdentityOptions>(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; >); 

DO: Set a cookie policy

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

A08 Software and Data Integrity Failures¶

DO: Digitally sign assemblies and executable files

DO: Use Nuget package signing

DO: Review code and configuration changes to avoid malicious code or dependencies being introduced

DO NOT: Send unsigned or unencrypted serialized objects over the network

DO: Perform integrity checks or validate digital signatures on serialized objects received from the network

DO NOT: Use the BinaryFormatter type which is dangerous and not recommended for data processing. .NET offers several in-box serializers that can handle untrusted data safely:

A09 Security Logging and Monitoring Failures¶

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

DO: 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"); . Instead, 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 in the Logging Cheat Sheet.

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

Here's 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.GetIExceptionHandlerFeature>(); var exception = errorFeature.Error; Log.Error(String.Format("Stacktrace of error: ",exception.StackTrace.ToString())); >); >); app.UseAuthentication(); app.UseMvc(); > > 

E.g. injecting into the class constructor, which makes writing unit test simpler. This 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 login attempts.

public class AccountsController : Controller  private ILogger _Logger; public AccountsController(ILogger logger)  _Logger = logger; > [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async TaskIActionResult> 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: , Successfully Logged in", model.Email)); //Code for successful login //. > else  //Log all incorrect log in attempts Log.Information(String.Format("User: , Incorrect Password", model.Email)); > > . > 

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.

A10 Server-Side Request Forgery (SSRF)¶

DO: Validate and sanitize all user input before using it to make a request

DO: Use an allowlist of allowed protocols and domains

DO: Use IPAddress.TryParse() and Uri.CheckHostName() to ensure that IP addresses and domain names are valid

DO NOT: Follow HTTP redirects

DO NOT: Forward raw HTTP responses to the user

OWASP 2013 & 2017¶

Below are vulnerabilities that were included in the 2013 or 2017 OWASP Top 10 list that were not included in the 2021 list. These vulnerabilities are still relevant but were not included in the 2021 list because they have become less prevalent.

A04:2017 XML External Entities (XXE)¶

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

This article discusses the most common XML Processing Options for .NET.

Please refer to the XXE cheat sheet for more detailed information on preventing XXE and other XML Denial of Service attacks.

A07:2017 Cross-Site Scripting (XSS)¶

DO NOT: Trust any data the user sends you. Prefer allowlists (always safe) over denylists.

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:

Then set in config:

  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 are absolutely sure 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 they should not be able to access (e.g. malicious scripts):

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

A08:2017 Insecure Deserialization¶

DO NOT: Accept Serialized Objects from Untrusted Sources

DO: 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.

DO: Prevent Deserialization of Domain Objects

DO: Run the Deserialization Code with Limited Access Permissions If a deserialized hostile object tries to initiate a system process 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.

More information about Insecure Deserialization can be found in the Deserialization Cheat Sheet.

A10:2013 Unvalidated redirects and forwards¶

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

public async TaskActionResult> 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"); > > 

Other advice¶

Sample project¶

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.

Guidance for specific topics¶

This section contains guidance for specific topics in .NET.

Configuration and Deployment¶