This site is the archived OWASP Foundation Wiki and is no longer accepting Account Requests.
To view the new OWASP Foundation website, please visit https://owasp.org

Difference between revisions of ".NET Security Cheat Sheet"

From OWASP
Jump to: navigation, search
m
(Added Troy's feedback.)
Line 10: Line 10:
  
 
Individual frameworks can be kept up to date using NuGet. As Visual Studio prompts for updates, build it into your lifecycle.
 
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.
  
 
==.NET Framework Guidance==
 
==.NET Framework Guidance==
Line 22: Line 24:
 
* 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.
 
* 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 an indirect reference map. Don't allow users to see the primary key of a database row.
 
* Use an indirect reference map. Don't allow users to see the primary key of a database row.
 +
* Use of the Entity Framework is a very effective SQLi prevention mechanism. Remember that building your own ad hoc queries in EF is just as susceptible to SQLi as a plain SQL query.
  
 
=== Encryption ===
 
=== Encryption ===
* Never, ever write your own encryption.
+
* Never, ever write your own encryption. Use the DPAPI for easy access to common algorithms.
 
* When using a hashing function, use a salt value added to the original value before hashing.
 
* When using a hashing function, use a salt value added to the original value before hashing.
 
* Use a strong hash algorithm.  
 
* Use a strong hash algorithm.  
 
** In .NET 4.5 the strongest hashing algorithm is System.Security.Cryptography.SHA512.
 
** In .NET 4.5 the strongest hashing algorithm is System.Security.Cryptography.SHA512.
 
** Make sure your application can support a change in algorithm.
 
** Make sure your application can support a change in algorithm.
 +
* 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 ===
 
=== General ===
Line 42: Line 46:
  
 
* Always use HTTPS.
 
* Always use HTTPS.
 +
* Enable requireSSL on cookies and form elements and HttpOnly on cookies in the web.config.
 +
* Implement custom errors.
 +
* Make sure tracing is turned off.
 +
* While viewstate isn't always appropriate for web development, using it provides CSRF mitigation. 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.
 +
 +
        private const string AntiXsrfTokenKey = "__AntiXsrfToken";
 +
        private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
 +
        private string _antiXsrfTokenValue;
 +
 +
        protected void Page_Init(object sender, EventArgs e)
 +
        {
 +
            // The code below helps to protect against XSRF attacks
 +
            var requestCookie = Request.Cookies[AntiXsrfTokenKey];
 +
            Guid requestCookieGuidValue;
 +
            if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
 +
            {
 +
                // Use the Anti-XSRF token from the cookie
 +
                _antiXsrfTokenValue = requestCookie.Value;
 +
                Page.ViewStateUserKey = _antiXsrfTokenValue;
 +
            }
 +
            else
 +
            {
 +
                // Generate a new Anti-XSRF token and save to the cookie
 +
                _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
 +
                Page.ViewStateUserKey = _antiXsrfTokenValue;
 +
 +
                var responseCookie = new HttpCookie(AntiXsrfTokenKey)
 +
                {
 +
                    HttpOnly = true,
 +
                    Value = _antiXsrfTokenValue
 +
                };
 +
                if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
 +
                {
 +
                    responseCookie.Secure = true;
 +
                }
 +
                Response.Cookies.Set(responseCookie);
 +
            }
 +
 +
            Page.PreLoad += master_Page_PreLoad;
 +
        }
 +
 +
* Consider HSTS in IIS.
 +
** In the Connections pane, go to the site, application, or directory for which you want to set a custom HTTP header.
 +
** In the Home pane, double-click HTTP Response Headers.
 +
** In the HTTP Response Headers pane, click Add... in the Actions pane.
 +
** In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.
 +
* Remove the version header.
 +
 +
    <httpRuntime enableVersionHeader="false" />
 +
 +
* Also remove the Server header.
 +
 +
    HttpContext.Current.Response.Headers.Remove("Server");
 +
 +
  
 
=== HTTP validation and encoding ===
 
=== HTTP validation and encoding ===
Line 55: Line 114:
 
* Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.
 
* Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.
 
* Reduce the session time from the default of 20 minutes. If slidingExpiration is used this timeout starts after the last request, so active users won't be affected.
 
* Reduce the session time from the default of 20 minutes. If slidingExpiration is used this timeout starts after the last request, so active users won't be affected.
* If you don't require SSL, disable slidingExpiration.  
+
* Disable slidingExpiration.  
 
* Always implement proper access controls.
 
* Always implement proper access controls.
 
** Compare user provided username with User.Identity.Name.
 
** Compare user provided username with User.Identity.Name.
 
** Check roles against User.Identity.IsInRole.
 
** Check roles against User.Identity.IsInRole.
* Use the native membership provider.
+
* Use the ASP.NET membership provider and role provider, but review the password storage. The default storage is rather weak. The ASP.NET MVC4 template uses PBKDF2, and is better. Review the OWASP password guidance for more information.
* Explicitly authorize resource requests, using User.Identity.Name.
+
* Explicitly authorize resource requests.
 
* Leverage role based authorization using User.Identity.IsInRole.
 
* Leverage role based authorization using User.Identity.IsInRole.
  
Line 69: Line 128:
 
* Always use HTTPS.
 
* Always use HTTPS.
 
* Use the Syncronizer token pattern. In Web Forms, this is handled by ViewState, but in MVC you need to use ValidateAntiForgeryToken.
 
* Use the Syncronizer token pattern. In Web Forms, this is handled by ViewState, but in MVC you need to use ValidateAntiForgeryToken.
 +
* Remove the version header.
 +
 +
    MvcHandler.DisableMvcResponseHeader = true;
 +
 +
* Also remove the Server header.
 +
 +
    HttpContext.Current.Response.Headers.Remove("Server");
 +
 
* Decorate controller methods using PrincipalPermission to prevent unrestricted URL access.
 
* Decorate controller methods using PrincipalPermission to prevent unrestricted URL access.
 
* Make use of IsLocalUrl() in logon methods.
 
* Make use of IsLocalUrl() in logon methods.
Line 99: Line 166:
 
         // gimmee da codez
 
         // gimmee da codez
 
     }
 
     }
 +
 +
* 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 my an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.
  
 
==XAML Guidance==
 
==XAML Guidance==

Revision as of 02:49, 5 April 2013

DRAFT CHEAT SHEET - WORK IN PROGRESS

Introduction

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

The .NET Framework

The .NET Framework is Microsoft's principal platform for line of business 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 http://windowsupdate.microsoft.com/ 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.

.NET Framework Guidance

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 line of business 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.
  • 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 an indirect reference map. Don't allow users to see the primary key of a database row.
  • Use of the Entity Framework is a very effective SQLi prevention mechanism. Remember that building your own ad hoc queries in EF is just as susceptible to SQLi as a plain SQL query.

Encryption

  • Never, ever write your own encryption. Use the DPAPI for easy access to common algorithms.
  • When using a hashing function, use a salt value added to the original value before hashing.
  • Use a strong hash algorithm.
    • In .NET 4.5 the strongest hashing algorithm is System.Security.Cryptography.SHA512.
    • Make sure your application can support a change in algorithm.
  • 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

  • Always check the MD5 hashes of the .NET Framework assemblies to prevent the possibility of rootkits in the framework. Altered assemblies are possible and simple to produce. Checking the MD5 hashes will prevent using altered assemblies on a server or client machine. See File:Presentation - .NET Framework Rootkits - Backdoors Inside Your Framework.ppt
  • 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

ASP.NET Web Forms Guidance

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

  • Always use HTTPS.
  • Enable requireSSL on cookies and form elements and HttpOnly on cookies in the web.config.
  • Implement custom errors.
  • Make sure tracing is turned off.
  • While viewstate isn't always appropriate for web development, using it provides CSRF mitigation. 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.
       private const string AntiXsrfTokenKey = "__AntiXsrfToken";
       private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
       private string _antiXsrfTokenValue;
       protected void Page_Init(object sender, EventArgs e)
       {
           // The code below helps to protect against XSRF attacks
           var requestCookie = Request.Cookies[AntiXsrfTokenKey];
           Guid requestCookieGuidValue;
           if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
           {
               // Use the Anti-XSRF token from the cookie
               _antiXsrfTokenValue = requestCookie.Value;
               Page.ViewStateUserKey = _antiXsrfTokenValue;
           }
           else
           {
               // Generate a new Anti-XSRF token and save to the cookie
               _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
               Page.ViewStateUserKey = _antiXsrfTokenValue;
               var responseCookie = new HttpCookie(AntiXsrfTokenKey)
               {
                   HttpOnly = true,
                   Value = _antiXsrfTokenValue
               };
               if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
               {
                   responseCookie.Secure = true;
               }
               Response.Cookies.Set(responseCookie);
           }
           Page.PreLoad += master_Page_PreLoad;
       }
  • Consider HSTS in IIS.
    • In the Connections pane, go to the site, application, or directory for which you want to set a custom HTTP header.
    • In the Home pane, double-click HTTP Response Headers.
    • In the HTTP Response Headers pane, click Add... in the Actions pane.
    • In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.
  • Remove the version header.
   <httpRuntime enableVersionHeader="false" /> 
  • Also remove the Server header.
   HttpContext.Current.Response.Headers.Remove("Server");


HTTP validation and encoding

  • Do not disable validateRequest in the web.config or the page setup. This value enables the AntiXSS library in ASP.NET and should be left intact to present cross site scripting.
  • Whitelist allowable values anytime user input is accepted. The regex namespace is particularly useful for checking to make sure an email address or URI is as expected.
  • Always encode output to the browser using Server.HtmlEncode.
  • Validate the URI format using Uri.IsWellFormedUriString.

Authorization and 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 session time from the default of 20 minutes. If slidingExpiration is used this timeout starts after the last request, so active users won't be affected.
  • Disable slidingExpiration.
  • 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 is rather weak. The ASP.NET MVC4 template uses PBKDF2, and is better. Review the OWASP password guidance for more information.
  • Explicitly authorize resource requests.
  • Leverage role based authorization using User.Identity.IsInRole.

ASP.NET MVC Guidance

ASP.NET MVC is the new hotness from Microsoft, employing the popular MVC pattern used by frameworks like Ruby on Rails.

  • Always use HTTPS.
  • Use the Syncronizer token pattern. In Web Forms, this is handled by ViewState, but in MVC you need to use ValidateAntiForgeryToken.
  • Remove the version header.
   MvcHandler.DisableMvcResponseHeader = true;
  • Also remove the Server header.
   HttpContext.Current.Response.Headers.Remove("Server");
  • Decorate controller methods using PrincipalPermission to prevent unrestricted URL access.
  • Make use of IsLocalUrl() in logon methods.
   if (MembershipService.ValidateUser(model.UserName, model.Password)) 
   { 
       FormsService.SignIn(model.UserName, model.RememberMe); 
       if (IsLocalUrl(returnUrl)) 
       { 
           return Redirect(returnUrl); 
       } 
       else 
       { 
           return RedirectToAction("Index", "Home"); 
       } 
   } 
  • Use the AntiForgeryToken on every form post to prevent CSRF attacks. In the HTML:
   <% using(Html.Form(“Form", "Update")) { %>
       <%= Html.AntiForgeryToken() %>
   <% } %>

and on the controller method:


   [ValidateAntiForgeryToken]
   public ViewResult Update()
   {
       // gimmee da codez
   }
  • 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 my an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.

XAML Guidance

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


Windows Forms Guidance

  • Use partial trust when possible. Partially trusted Windows applications make the attack surface of an application much smaller. 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 Zed Attack Proxy.

Authors and Primary Editors


Other Cheatsheets

OWASP Cheat Sheets Project Homepage