Thursday, December 21, 2017

Secure you Asp .NET by Web.config & Global.ascx?

Add to Global.ascx

protected void Application_BeginRequest(object sender,EventArgs e)

    {

        //to remove x frame
        Response.AddHeader("X-Frame-Options", "DENY");
        var application = sender as HttpApplication;
        if (application != null && application.Context != null)
        {
        //to remove server header like iis 8.5
        application.Context.Response.Headers.Remove("Server");
        }
    }

Add to Web.Config

<system.webServer>


  <!--this section will add / remove the headers from Response-->
<httpProtocol>

   <customHeaders>
   <add name="Content-Security-Policy" value="default-src https: data: 'unsafe-inline' 'unsafe-eval'" />
   <add name="X-Content-Type-Options" value="nosniff" />
   <add name="X-XSS-Protection" value="1; mode=block" />
   <!-- avoid clickjacking-->
   <add name="X-Frame-Options" value="SAMEORIGIN" />
   <!--will remove header like ASP .NET version-->
   <remove name="X-Powered-By"/>
   </customHeaders>
</httpProtocol>



<security >

     <requestFiltering>
      <!--will not allow below http methods in application-->
      <verbs>
        <add verb="TRACE" allowed="false" />
        <add verb="HEAD" allowed="false" />
        <add verb="OPTIONS" allowed="false" />
      </verbs>        
      </requestFiltering>
</security>



</system.webServer>


Add to Web.Config

  <system.web>

 <customErrors mode="On" defaultRedirect="~/WebPagesError/ErrorPage.aspx"  >
       
    </customErrors>

    <!--Encrypt ViewState  -->
    <pages viewStateEncryptionMode="Always" validateRequest="true" enableViewState="true" enableViewStateMac="true"  controlRenderingCompatibilityVersion="3.5"/>
    
    
    <!--request should be httponly -->
    <httpCookies httpOnlyCookies="true"  />

    <!--preventing response to give system info like iis/asp .net etc  -->
    <httpRuntime enableVersionHeader="false" />
    <machineKey validation="3DES"/>
    

  </system.web>



SessionID Validation?

Step 1:


 protected void Page_Load(object sender, EventArgs e)
    {


if (!IsPostBack )
        {          
            #region for session validation
            Guid guid = Guid.NewGuid();
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null)
                {
                    HttpCookie cookie = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"];
                    cookie.Value = guid.ToString();
                    HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-2.0);
                    HttpContext.Current.Request.Cookies.Remove("ASP.NET_SessionId");
                    HttpContext.Current.Request.Cookies.Add(cookie);
                }
            }
}

Step 2:  Add to Global.ascx  

if you have any logout button then add it to Button Click event to remove session. otherwise only add this section to Global.ascx




 void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

        Session.Clear();
        Session.Abandon();
        Guid guid = Guid.NewGuid();

        if (HttpContext.Current != null)
        {
            if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null)
            {
                string text1 = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value;
                HttpCookie cookie = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"];
                cookie.Value = guid.ToString();
                HttpContext.Current.Request.Cookies.Set(cookie);
                string text2 = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value;
            }
            if (HttpContext.Current.Response.Cookies["ASP.NET_SessionId"] != null)
            {
                HttpCookie cookie2 = HttpContext.Current.Response.Cookies["ASP.NET_SessionId"];
                cookie2.Value = guid.ToString();
                HttpContext.Current.Response.Cookies.Set(cookie2);
                string text3 = HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Value;
            }
            HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-2.0);
            HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-2.0);
        }


    }

Prevent CSRF attack?


public partial class MasterPage : System.Web.UI.MasterPage
{

Step 1:

    #region CSRF Prevention 
    private const string AntiXsrfTokenKey = "__AntiXsrfToken";
    private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
    private string _antiXsrfTokenValue;
    
    protected void Page_Init(object sender, EventArgs e)
    {
        //First, check for the existence of the Anti-XSS cookie
        var requestCookie = Request.Cookies[AntiXsrfTokenKey];
        Guid requestCookieGuidValue;

        //If the CSRF cookie is found, parse the token from the cookie.
        //Then, set the global page variable and view state user
        //key. The global variable will be used to validate that it matches in the view state form field in the Page.PreLoad
        //method.
        if (requestCookie != null   && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
        {
            //Set the global token variable so the cookie value can be
            //validated against the value in the view state form field in
            //the Page.PreLoad method.
            _antiXsrfTokenValue = requestCookie.Value;

            //Set the view state user key, which will be validated by the
            //framework during each request
            Page.ViewStateUserKey = _antiXsrfTokenValue;
        }
        //If the CSRF cookie is not found, then this is a new session.
        else 
            //if(requestCookie==null)
        {
            //Generate a new Anti-XSRF token
            _antiXsrfTokenValue = Guid.NewGuid().ToString("N");

            //Set the view state user key, which will be validated by the
            //framework during each request
            Page.ViewStateUserKey = _antiXsrfTokenValue;

            //Create the non-persistent CSRF cookie
            var responseCookie = new HttpCookie(AntiXsrfTokenKey)
            {
                //Set the HttpOnly property to prevent the cookie from
                //being accessed by client side script
                HttpOnly = true,

                //Add the Anti-XSRF token to the cookie value
                Value = _antiXsrfTokenValue
            };

            //If we are using SSL, the cookie should be set to secure to
            //prevent it from being sent over HTTP connections
            if (FormsAuthentication.RequireSSL &&    Request.IsSecureConnection)
                responseCookie.Secure = true;

            //Add the CSRF cookie to the response
            Response.Cookies.Set(responseCookie);
        } 
    }   
    #endregion

Step 2:

  protected void Page_Load(object sender, EventArgs e)
    {
        #region CSRF
        //During the initial page load, add the Anti-XSRF token and user
        //name to the ViewState
        if (!IsPostBack)
        {
            //Set Anti-XSRF token
            ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;

            //If a user name is assigned, set the user name
            ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
        
        }
       
        //During all subsequent post backs to the page, the token value from
        //the cookie should be validated against the token in the view state
        //form field. Additionally user name should be compared to the
        //authenticated users name
        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.");
            }
        }



Secure you Asp .NET by Web.config & Global.ascx?

Add to Global.ascx protected void Application_BeginRequest(object sender,EventArgs e)     {         //to remove x frame         Resp...