Friday, June 30, 2017

Publish website without roslyn

 Roslyn (compiler) is .NET Compiler Platform, is a set of open-source compilers and code analysis APIs for C# and Visual Basic (VB.NET) languages from Microsoft.


When create a new web project, two nuget packages automatically added to the project. Remove them, then roslyn exe will removed from bin.  Package names are: 

"Microsoft.CodeDom.Providers.DotNetCompilerPlatform" and 
"Microsoft.Net.Compilers".


If you are offline, then goto packages.config and remove it.

issues: if still roslyn folder exists then go to manage Nuget package for solution and remove above 2 packages.


---------------------------------------------Don't remove below:---------

Required components for the Bundling and Minification system.

  • Microsoft.AspNet.Web.Optimization
  • WebGrease
  • Antlr

Monday, June 19, 2017

SignalR

What is ASP.NET SignalR

ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is "real-time web" functionality? It's the ability to have your server-side code push content to the connected clients as it happens, in real-time.
You may have heard of WebSockets, a new HTML5 API that enables bi-directional communication between the browser and server. SignalR will use WebSockets under the covers when it's available, and gracefully fallback to other techniques and technologies when it isn't, while your application code stays the same.
SignalR also provides a very simple, high-level API for doing server to client RPC (call JavaScript functions in your clients' browsers from server-side .NET code) in your ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization.

What can you do with ASP.NET SignalR?

SignalR can be used to add any sort of "real-time" web functionality to your ASP.NET application. While chat is often used as an example, you can do a whole lot more. Any time a user refreshes a web page to see new data, or the page implements Ajax long polling to retrieve new data, is candidate for using SignalR.
It also enables completely new types of applications, that require high frequency updates from the server

Tuesday, June 6, 2017

Security HTTP Headers to Prevent Vulnerabilities, HTTPS Everywhere in ASP.Net MVC application

<system.web>
<httpCookies httpOnlyCookies="true" requireSSL="true" /> 
</system.web>
<system.webServer>
<httpProtocol>
 <customHeaders>
  <remove name="X-Powered-By">
  <add name="X-Frame-Options" value="DENY"/>
  <add name="X-XSS-Protection" value="1; mode=block"/>
  <add name="X-Content-Type-Options" value="nosniff "/>
  <add name="Content-Security-Policy" value="default-src 'self'"/>
  <add name="Strict-Transport-Security" value="max-age=31536000; includeSubdomains" />
 </customHeaders>
<httpProtocol>
</system.webServer>


Security HTTP Headers

  • X-Frame-Options
X-Frame-Options "sameorigin"

  • X-XSS-Protection
X-XSS-Protection "1; mode=block"
  • X-Content-Type-Options
X-Content-Type-Options "nosniff"
  • Strict-Transport-Security
Strict-Transport-Security "max-age=31536000"; includeSubDomains
  • Content-Security-Policy
 Content-Security-Policy "default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';"
  • Access-Control-Allow-Origin
Access-Control-Allow-Origin "https://zinoui.com"

  • Public-Key-Pins
Public-Key-Pins "pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"; pin-sha256=\"E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=\"; max-age=604800; report-uri=\"https://example.net/pkp-report\""
  • Referrer-Policy
Referrer-Policy "origin-when-cross-origin"


OR
  1. For removingX-AspNetMvc-Version header
To remove response X-AspNetMvc-Versionwhich shows information of which ASP.NET MVC version used we have built in property in MVC.

Just set [MvcHandler.DisableMvcResponseHeader = true;] in Global.asaxApplication start event [Application_Start()] this will remove header it won’t be displayed any more.

      2. For removingX-AspNet-Version and Server header
To remove response of Server header which shows information of which web server is begin used and along with that X-AspNet-Version headershows information of which specific Asp.Net Version Used.
Just add an event in [Application_PreSendRequestHeaders()] in global.asax and then to remove header we need to set theproperty as below.
protectedvoidApplication_PreSendRequestHeaders()
{
   Response.Headers.Remove("Server");           //Remove Server Header   
   Response.Headers.Remove("X-AspNet-Version"); //Remove X-AspNet-Version Header
}

HTTPS Everywhere in ASP.Net MVC application

1. Redirect to HTTPS

Redirecting to HTTPS schema is pretty simple in modern MVC. All you need to know about is RequireHttpsAttribute. This is named as Attribute and can be used as an attribute on separate MVC controllers and even actions. And I hate it for that – it encourages for bad practices. But luckily this class is also implements IAuthorizationFilter interface, which means this can be used globally on the entire app as a filter.
Problem with this filter – once you add it to your app, you need to configure SSL on your development machine. If you work in team, all dev machines must be configured with SSL. If you allow people to work from home, their home machines must be configured to work with SSL. And configuring SSL on dev machines is a waste of time. Maybe there is a script that can do that automatically, but I could not find one quickly.
Instead of configuring SSL on local IIS, I decided to be a smart-ass and work around it. Quick study of source code highlighted that the class is not sealed and I can just inherit this class. So I inherited RequireHttpsAttribute and added logic to ignore all local requests:
public class RequreSecureConnectionFilter : RequireHttpsAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        if (filterContext.HttpContext.Request.IsLocal)
        {
            // when connection to the application is local, don't do any HTTPS stuff
            return;
        }

        base.OnAuthorization(filterContext);
    }
}
If you are lazy enough to follow the link to the source code, I’ll tell you all this attribute does is check if incoming request schema used is https (that is what Request.IsSecureConnection does), if not, redirect all GET request to https. And if request comes that is not secured and not GET, throw exception. I think this is a good-aggressive implementation.
One might argue that I’m creating a security hole by not redirecting to https on local requests. But if an intruder managed to do local requests on your server, you are toast anyway and SSl is not your priority at the moment.
I looked up what filterContext.HttpContext.Request.IsLocal does and how it can have an impact on security. Here is the source code:
    public bool IsLocal {
        get {
            String remoteAddress = UserHostAddress;

            // if unknown, assume not local
            if (String.IsNullOrEmpty(remoteAddress))
                return false;

            // check if localhost
            if (remoteAddress == "127.0.0.1" || remoteAddress == "::1")
                return true;

            // compare with local address
            if (remoteAddress == LocalAddress)
                return true;

            return false;
        }
    }
This is decompiled implementation of System.Web.HttpRequestUserHostAddress get client’s IP address. If IP is localhost (IPv4 or IPv6), return true. LocalAddress property returns servers IP address. So basically .IsLocal() does what it says on the tin. If request comes from the same IP the application is hosted on, return true. I see no issues here.
By the way, here are the unit tests for my implementation of the secure filter. Can’t go without unit testing on this one!
And don’t forget to add this filter to list of your global filters
public static class FilterConfig
{
    public void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new RequreSecureConnectionFilter());
        // other filters to follow...
    }
}

2. Cookies

If you think that redirecting to https is enough, you are very wrong. You must take care of your cookies. And set all of them by default to be HttpOnly and SslOnly. Read Troy Hunt’s excellent blog post why you need your cookies to be secured.
You can secure your cookies in web.config pretty simple:
<system.web>
    <httpCookies httpOnlyCookies="true" requireSSL="true"/>
</system.web>
The only issue with that is development stage. Again, if you developing locally you won’t be able to login to your application without https running locally. Solution to that is web.config transformation.
So in your web.config you should always have
<system.web>
    <httpCookies httpOnlyCookies="true" />
</system.web>
and in your web.Release.config file add
<system.web>
    <httpCookies httpOnlyCookies="true" requireSSL="true" lockItem="true" xdt:Transform="Replace" />
</system.web>
This secures your cookies when you publish your application. Simples!

3. Secure authentication cookie

Apart from all your cookies to be secure, you need to specifically require authentication cookie to be SslOnly. For that you need to add requireSSL="true" to your authentication/forms part of web.config. Again, this will require you to run your local IIS with https configured. Or you can do web.config transformation only for release. In your web.Release.config file add this into system.web section
<authentication mode="Forms">
    <forms loginUrl="~/Logon/LogOn" timeout="2880" requireSSL="true" xdt:Transform="Replace"/>
</authentication>

4. Strict Transport Security Header

Strict Transport Security Header is http header that tells web-browsers only to use HTTPS when dealing with your web-application. This reduces the risks of SSL Strip attack. To add this header by default to your application you can add add this section to your web.config:
<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" />
      </customHeaders>
    </httpProtocol>
</system.webServer> 
Again, the same issue as before, developers will have to have SSL configured on their local machines. Or you can do that via web.config transformation. Add the following code to your web.Release.config:
<system.webServer>
    <httpProtocol>
        <customHeaders>
           <add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" xdt:Transform="Insert" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

5. Secure your WebApi

WebApi is very cool and default template for MVC application now comes with WebApi activated. Redirecting all MVC requests to HTTPS does not redirect WebApi requests. So even if you secured your MVC pipeline, your WebApi requests are still available via HTTP.
Unfortunately redirecting WebApi requests to HTTPS is not as simple as it is with MVC. There is no [RequireHttps]available, so you’ll have to make one yourself. Or copy the code below:
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

public class EnforceHttpsHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // if request is local, just serve it without https
        object httpContextBaseObject;
        if (request.Properties.TryGetValue("MS_HttpContext", out httpContextBaseObject))
        {
            var httpContextBase = httpContextBaseObject as HttpContextBase;

            if (httpContextBase != null && httpContextBase.Request.IsLocal)
            {
                return base.SendAsync(request, cancellationToken);
            }
        }

        // if request is remote, enforce https
        if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            return Task<HttpResponseMessage>.Factory.StartNew(
                () =>
                {
                    var response = new HttpResponseMessage(HttpStatusCode.Forbidden)
                    {
                        Content = new StringContent("HTTPS Required")
                    };

                    return response;
                });
        }

        return base.SendAsync(request, cancellationToken);
    }
}
This is a global handler that rejects all non https requests to WebApi. I did not do any redirection (not sure this term is applicable to WebApi) because there is no excuse for clients to use HTTP first.
WARNING This approach couples WebApi to System.Web libraries and you won’t be able to use this code in self-hosed WebApi applications. But there is a better way to implement detection if request is local. I have not used it because my unit tests have been written before I learned about better way. And I’m too lazy to fix this -)
Don’t forget to add this handler as a global:
namespace MyApp.Web.App_Start
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // other configurations...

            // make all web-api requests to be sent over https
            config.MessageHandlers.Add(new EnforceHttpsHandler());
        }
    }
}

.NET Security Cheat Sheet

Data Access

  • Use Parameterized SQL commands for all data access, without exception.
  • Do not use SqlCommand with a string parameter made up of a concatenated SQL String.
  • Whitelist allowable values coming from the user. Use enums, TryParse or lookup values to assure that the data coming from the user is as expected.
    • Enums are still vulnerable to unexpected values because .NET only validates a successful cast to the underlying data type, integer by default. Enum.IsDefined can validate whether the input value is valid within the list of defined constants.
  • Apply the principle of least privilege when setting up the Database User in your database of choice. The database user should only be able to access items that make sense for the use case.
  • Use of the Entity Framework is a very effective SQL injection prevention mechanism. Remember that building your own ad hoc queries in EF is just as susceptible to SQLi as a plain SQL query.
  • When using SQL Server, prefer integrated authentication over SQL authentication.
  • Use Always Encrypted where possible for sensitive data (SQL Server 2016 and SQL Azure),

Encryption

  • Never, ever write your own encryption.
  • Use the Windows Data Protection API (DPAPI) for secure local storage of sensitive data.
  • Use a strong hash algorithm.
    • In .NET (both Framework and Core) the strongest hashing algorithm for general hashing requirements is System.Security.Cryptography.SHA512.
    • In the .NET framework the strongest algorithm for password hashing is PBKDF2, implemented as System.Security.Cryptography.Rfc2898DeriveBytes.
    • In .NET Core the strongest algorithm for password hashing is PBKDF2, implemented as Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2 which has several significant advantages over Rfc2898DeriveBytes.
    • When using a hashing function to hash non-unique inputs such as passwords, use a salt value added to the original value before hashing.
  • Make sure your application or protocol can easily support a future change of cryptographic algorithms.
  • Use Nuget to keep all of your packages up to date. Watch the updates on your development setup, and plan updates to your applications accordingly.

General

  • Lock down the config file.
    • Remove all aspects of configuration that are not in use.
    • Encrypt sensitive parts of the web.config using aspnet_regiis -pe
  • For Click Once applications the .Net Framework should be upgraded to use version 4.6.2 to ensure TLS 1.1/1.2 support.

ASP.NET Web Forms Guidance

ASP.NET Web Forms is the original browser-based application development API for the .NET framework, and is still the most common enterprise platform for web application development.
  • Always use HTTPS.
  • Enable requireSSL on cookies and form elements and HttpOnly on cookies in the web.config.
  • Implement customErrors.
  • Make sure tracing is turned off.
  • While viewstate isn't always appropriate for web development, using it can provide CSRF mitigation. To make the ViewState protect against CSRF attacks you need to set the ViewStateUserKey:
protected override OnInit(EventArgs e) {
    base.OnInit(e); 
    ViewStateUserKey = Session.SessionID;
} 
If you don't use Viewstate, then look to the default master page of the ASP.NET Web Forms default template for a manual anti-CSRF token using a double-submit cookie.
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;
}

protected void master_Page_PreLoad(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       // Set Anti-XSRF token
       ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
       ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
    }
    else
    {
       // Validate the Anti-XSRF token
       if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || 
          (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
       {
          throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
       }
    }
}
  • 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.
    • This is a recommended web.config setup that handles HSTS among other things.
<?xml version="1.0" encoding="UTF-8"?>
 <configuration>
   <system.web>
     <httpRuntime enableVersionHeader="false"/>
   </system.web>
   <system.webServer>
     <security>
       <requestFiltering removeServerHeader="true" />
     </security>
     <staticContent>
       <clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="1.00:00:00" setEtag="true" />
     </staticContent>
     <httpProtocol>
       <customHeaders>
         <add name="Content-Security-Policy" value="default-src 'none'; style-src 'self'; img-src 'self'; font-src 'self'" />
         <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="1; mode=block"/>
         <remove name="X-Powered-By"/>
       </customHeaders>
     </httpProtocol>
     <rewrite>
       <rules>
         <rule name="Redirect to https">
           <match url="(.*)"/>
           <conditions>
             <add input="{HTTPS}" pattern="Off"/>
             <add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
           </conditions>
           <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent"/>
         </rule>
       </rules>
       <outboundRules>
         <rule name="Add HSTS Header" enabled="true">
           <match serverVariable="RESPONSE_Strict_Transport_Security"
               pattern=".*" />
           <conditions>
             <add input="{HTTPS}" pattern="on" ignoreCase="true" />
           </conditions>
           <action type="Rewrite" value="max-age=15768000" />
         </rule>
       </outboundRules>
     </rewrite>
   </system.webServer>
 </configuration>
  • 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 limited XSS protection in ASP.NET and should be left intact as it provides partial prevention of Cross Site Scripting. Complete request validation is recommended in addition to the built in protections.
  • The 4.5 version of the .NET Frameworks includes the AntiXssEncoder library, which has a comprehensive input encoding library for the prevention of XSS. Use it.
  • Whitelist allowable values anytime user input is accepted.
  • Validate the URI format using Uri.IsWellFormedUriString.

Forms authentication

  • Use cookies for persistence when possible. Cookieless Auth will default to UseDeviceProfile.
  • Don't trust the URI of the request for persistence of the session or authorization. It can be easily faked.
  • Reduce the forms authentication timeout from the default of 20 minutes to the shortest period appropriate for your application. If slidingExpiration is used this timeout resets after each request, so active users won't be affected.
  • If HTTPS is not used, slidingExpiration should be disabled. Consider disabling slidingExpiration even with HTTPS.
  • Always implement proper access controls.
    • Compare user provided username with User.Identity.Name.
    • Check roles against User.Identity.IsInRole.
  • Use the ASP.NET Membership provider and role provider, but review the password storage. The default storage hashes the password with a single iteration of SHA-1 which is rather weak. The ASP.NET MVC4 template uses ASP.NET Identity instead of ASP.NET Membership, and ASP.NET Identity uses PBKDF2 by default which is better. Review the OWASP Password Storage Cheat Sheet for more information.
  • Explicitly authorize resource requests.
  • Leverage role based authorization using User.Identity.IsInRole.

ASP.NET MVC Guidance

ASP.NET MVC (Model-View-Controller) is a contemporary web application framework that uses more standardized HTTP communication than the Web Forms postback model. The OWASP Top 10 lists the most prevalent and dangerous threats to web security in the world today and is reviewed every 3 years. This section is based on this. Your approach to securing your web application should be to start at the top threat A1 below and work down, this will ensure that any time spent on security will be spent most effectively spent and cover the top threats first and lesser threats afterwards. After covering the top 10 it is generally advisable to assess for other threats or get a professionally completed Penetration Test.
  • A1 SQL Injection
DO: Using an object relational mapper (ORM) or stored procedures is the most effective way of countering the SQL Injection vulnerability.
DO: Use parameterized queries where a direct sql query must be used.
e.g. In entity frameworks:
   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). NB: You can still accidentally do this with ORMs or Stored procedures so check everywhere.
e.g
   string strQry = "SELECT * FROM Users WHERE UserName='" + txtUser.Text + "' AND Password='" + txtPassword.Text + "'";
   EXEC strQry // SQL Injection vulnerability!
DO: Practise Least Privilege - Connect to the database using an account with a minimum set of permissions required to do it's job i.e. not the sa account
  • A2 Weak Account management
Ensure cookies are sent via httpOnly:
    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)
Find here the code to prevent throttling
DO NOT: Roll your own authentication or session management, use the one provided by .Net
DO NOT: Tell someone if the account exists on LogOn, Registration or Password reset. Say something like 'Either the username or password was incorrect', or 'If this account exists then a reset token will be sent to the registered email address'. This protects against account enumeration. The feedback to the user should be identical whether or not the account exists, both in terms of content and behaviour: e.g. if the response takes 50% longer when the account is real then membership information can be guessed and tested.
  • A3 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'" />
               ...
  • A4 Insecure Direct object references
When you have a resource (object) which can be accessed by a reference (in the sample below this is the id) then you need to ensure that the user is intended to be there
   // 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);
       }
  • A5 Security Misconfiguration
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
DO: (When using TLS) Redirect a request made over Http to https: In 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
}
  • A6 Sensitive data exposure
DO NOT: Store encrypted passwords.
DO: Use a strong hash to store password credentials. Use PBKDF2, BCrypt or SCrypt with at least 8000 iterations and a strong key.
DO: Enforce passwords with a minimum complexity that will survive a dictionary attack i.e. longer passwords that use the full character set (numbers, symbols and letters) to increase the entropy.
DO: Use a strong encryption routine such as AES-512 where personally identifiable data needs to be restored to it's original format. Do not encrypt passwords. Protect encryption keys more than any other asset. Apply the following test: Would you be happy leaving the data on a spreadsheet on a bus for everyone to read. Assume the attacker can get direct access to your database and protect it accordingly.
DO: Use TLS 1.2 for your entire site. Get a free certificate from StartSSL.com or LetsEncrypt.org.
DO NOT: Allow SSL, this is now obsolete
DO: Have a strong TLS policy (see SSL Best Practises), use TLS 1.2 wherever possible. Then check the configuration using SSL Test
DO: Ensure headers are not disclosing information about your application. See HttpHeaders.cs , Dionach StripHeaders or disable via 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="1; mode=block"/>
       <remove name="X-Powered-By"/>
     </customHeaders>
   </httpProtocol>
  • A7 Missing function level access control
DO: Authorize users on all externally facing endpoints. The .Net framework has many ways to authorize a user, use them at method level:
    [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)
  • A8 Cross site request forgery
DO: Send the anti-forgery token with every Post/Put request:
   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()
NB: You will need to attach the anti-forgery token to Ajax requests.
  • A9 Using components with known vulnerabilities
DO: Keep the .Net framework updated with the latest patches DO: Keep your NuGet packages up to date, many will contain their own vulnerabilities. So Run the OWASP Dependency checker against your application as part of your build process and act on any high level vulnerabilities. [OWASP Dependency Checker]
  • A10 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");
           }
       }
Other advice:
  • Protect against Clickjacking and man in the middle attack from capturing an initial Non-TLS request, set the X-Frame-Options and Strict-Transport-Security (HSTS) headers. Full details here
  • Protect against a man in the middle attack for a user who has never been to your site before. Register for HSTS preload
  • Maintain security testing and analysis on Web API services. They are hidden inside MEV sites, and are public parts of a site that will be found by an attacker. All of the MVC guidance and much of the WCF guidance applies to the Web API.

Encrypt/Decrypt the App.Config

Program.cs using System; using System.Diagnostics; using System.IO; namespace EncryptAppConfig {     internal class Program     {         pr...