makaleler / Diğer Konular / Siteler Arası Talep Sahteciliği (CSRF)

Siteler Arası Talep Sahteciliği (CSRF)

20.05.2017 02:02:52

ASP.NET Siteler Arası Talep Sahteciliği (CSRF) önleme

Merhabalar Arkadaşlar, (Not:Lütfen öneri ve sorularınızı yorum olarak atınız. Teşekkürler şimdiden)

Siteler Arası Talep Sahteciliği (CSRF), kimlik doğrulaması olan web uygulamasında istenmeyen ve yetki dışı eylem gerçekleştirmeye çalışan saldırı türüdür.

CSRF saldırısı yapılan post isteği arasına girerek Session'ı ve post değişkenleriyle ele geçirir. Ele geçirdiği değişkenler ile sahte bir form hazırlar. Hazırladığı bu form ile uygulamada yetki dışı olmayan işlemleri gerçekleştirmeye çalışır. Bu saldırı genelde uygulamada bulunan mesaj yazma, bir kayıt ekranı gibi benzeri kısımlarında olmaktadır.

CSRF saldırılarına karşı korunmanın en etkili yolu formdaki gizli bir parametre gibi çerezlere eklenmeyen bir ek token eklemektir. Bu ek token gerekli bilgileri içermelidir. Ve bir kullanıcı başka bir kullanıcıya verilen token'i tespit edemeyecek şekilde rastgele sayı üretici kullanılarak oluşturulmaktadır.

Token oluşumu, kullanıcı oturum açtığında gerçekleşmelidir.Oturum açma isteği sonunda bu token'i doğrulanması sağlanmalıdır.

ASP.NET uygulamasında Anti Csrf'i sağlayan noktayı aşağıdaki kod ile sağlayabiliriz. Bu kodu masterpage sayfasının load'ına eklersek yukarıdaki gibi oturum gerçekleştiğinde doğrulama yapılmasını sağlamaktadır. Bu kodları eklemek sadece C# tarafında gerçekleşen işlemler için geçerli olacaktır. Eğer sayfanın yapısı ajax ve gerçekleştirilen işlemler .ashx dosyasında gerçekleşiyorsa bu işlemi referer ve request url kontrolü yaparak gerçekleştirebiliriz. Çünkü yukarıda bahsettiğim araya girip bir form oluşturduğunda onu http://baskadomain.com/gizliformadi.aspx [baskadomain.com] gibi bir domainden gerçekleştirecektir. Bu işlemi engellemek de sadece o uygulamaya kendi alan adından gelen isteklere izin ver diyerek bir white list oluşturabiliriz.

İlk olarak masterpage'e koyacağımız token oluşturup doğrulamasını gerçekleştiren kodu aşağıda paylaşacağım.


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

Aşağıda refer ve request url kontrolü yapılan kod parçasını paylaşacağım.

 if ((context.Request.UrlReferrer == null || context.Request.Url.Host != context.Request.UrlReferrer.Host))
        {
            context.Response.Redirect("~/errorNotFound", false);
            return;
        }


ASP.NET uygulamalarında güvenlik ile ilgili dikkat edilmesi gerekenlere linkinden ulaşabilirsiniz.

İyi çalışmalar.

yazar okanyurt

Yorumlar

Bu içerik için sizde yorum yapabilirsiniz!
rumuzsuz
rumuzsuz
13.10.2017 00:52:46

Merhabalar, Bu konu hakkında gayet açıklayıcı bir yazı olmuş.Yazınız için teşekkürler.

anasayfa | makaleler | haberler | dosyalar | linkler | hakkımızda