如何防止所有网页中的CSRF /会话ID验证攻击? [英] How to prevent CSRF / session ID validation attack in all webpages ?

查看:85
本文介绍了如何防止所有网页中的CSRF /会话ID验证攻击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在我的asp .net网络应用中修复CSRF /会话ID验证攻击。



问题是手动更改会话ID / CSRF令牌服务器接受没有验证的请求和发送回复。



我尝试过:



对于CSRF我在下面试过,







I have to fix CSRF / Session ID Validation attack in my asp .net web appliction.

problem is when manually change the session id / CSRF Token server accept the request without validation and send response.

What I have tried:

For CSRF I Tried Below,



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


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

        Page.PreLoad += master_Page_PreLoad;
    }







protected void master_Page_PreLoad(object sender, EventArgs e)
  {
      //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.");
      }
  }







会话ID验证








For Session ID Validation


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
            application.Context.Response.Headers.Remove("Server");
        }


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

    }










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

推荐答案

见这些:

< a href =https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery>防止ASP.NET核心中的跨站点请求伪造(XSRF / CSRF)攻击Microsoft Docs [ ^ ]



防止ASP.NET Web API中的跨站点请求伪造(CSRF)攻击Microsoft Docs [ ^ ]



如何使用Microsoft .Net ViewStateUserKey和Double Submit Cookie修复跨站点请求伪造(CSRF) [ ^ ]
See These:
Preventing Cross-Site Request Forgery (XSRF/CSRF) Attacks in ASP.NET Core | Microsoft Docs[^]

Preventing Cross-Site Request Forgery (CSRF) Attacks in ASP.NET Web API | Microsoft Docs[^]

How To Fix Cross-Site Request Forgery (CSRF) using Microsoft .Net ViewStateUserKey and Double Submit Cookie[^]


这篇关于如何防止所有网页中的CSRF /会话ID验证攻击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆