2015-04-29 10 views
10

Ho creato un'applicazione di modulo Web ASP.Net utilizzando Visual Studio 2013 e sto utilizzando Dot Net Frame Work 4.5 e desidero accertarmi sito è sicuro da cross-site Request Forgery (CSRF), ho trovato molti articoli che parlano di come questa caratteristica è implementata su applicazioni MVC, ma pochissimi si parla di moduli web, su this StackOverflow question un commento è affermando cheprevenzione di attacchi di falsificazione di richieste cross-site (csrf) nei moduli Web asp.net

"Questa è una vecchia domanda, ma l'ultimo modello di Visual Studio 2012 ASP.NET per i moduli Web include il codice anti-CSRF inserito nella pagina principale . Se non si dispone dei modelli, ecco il codice genera: ..."

ma la mia pagina master non contiene il codice che ha menzionato nella sua risposta, così uno può please help me? è davvero implementato? in caso contrario, si prega di avvisare qual è il modo migliore per farlo?

+0

possibile duplicato di [Prevenzione contraffazione richiesta tra siti] (http: // stackoverflow.it/questions/24675779/prevent-cross-site-request-forgery) – SilverlightFox

+0

@SilverlightFox, Hope not;) –

risposta

10

ViewStateUserKey & Doppia Invia Cookie

A partire da Visual Studio 2012, Microsoft ha aggiunto la protezione incorporata CSRF a nuovi progetti di applicazioni Web Form. Per utilizzare questo codice, aggiungere una nuova applicazione Web Form ASP .NET alla soluzione e visualizzare il codice Site.Master dietro la pagina. Questa soluzione applicherà la protezione CSRF a tutte le pagine di contenuto che ereditano dalla pagina Site.Master.

I seguenti requisiti devono essere soddisfatti per questa soluzione per lavorare:

Tutti i moduli web che fanno modifiche ai dati deve utilizzare la pagina di Site.master. Tutte le richieste di modifica dei dati devono utilizzare ViewState. Il sito Web deve essere libero da tutte le vulnerabilità di Cross-Site Scripting (XSS). Scopri come risolvere Cross-Site Scripting (XSS) utilizzando la Libreria di protezione Web di Microsoft .NET per i dettagli.

public partial class SiteMaster : 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."); 
     } 
    } 
    } 
} 
+0

Sto usando VS2017 e non vedo questo codice in Site.Master.cs (nuovo progetto di applicazione di moduli Web). – joym8

6

Quando si crea un nuovo progetto "Applicazione Web Form" in VS 2013, il sito.master.cs includerà automaticamente il codice XSRF/CSRF nella sezione Page_Init della classe. Se non riesci ancora a ottenere il codice generato, puoi manualmente il codice Copy + Paste. Se si sta utilizzando C#, quindi utilizzare il seguito: -

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

sì, sto usando C#, e ho provato a copiare e superare questa funzione, ma sembra che abbia più errori. Sei sicuro che questo sia il codice generato automaticamente? –

+0

non riconosce: AntiXsrfTokenKey in Request.Cookies [AntiXsrfTokenKey]; e anche non riconoscere queste variabili _antiXsrfTokenValue, master_Page_PreLoad –

+0

@NadaNaeem ho incluso le costanti mancanti. –

15

Si potrebbe provare quanto segue. Nel modulo Web aggiungere:

<%= System.Web.Helpers.AntiForgery.GetHtml() %> 

Questo aggiungerà un campo nascosto e un cookie. Quindi, se si compilare alcuni dati del modulo e post-it al server è necessario un semplice controllo:

protected void Page_Load(object sender, EventArgs e) 
{ 
if (IsPostBack) 
AntiForgery.Validate(); 
} 

AntiForgery.Validate(); genera un'eccezione se il controllo di anti XSFR fallisce.

+0

Qual è lo spazio dei nomi per aggiungere AntiForgery. Ho provato ad includere system.web.helper ma non ha AntiForgery !!!! – sarathkumar

+2

Lo spazio dei nomi è System.Web.Helpers nel pacchetto Nuget di Microsoft.AspNet.WebPages. – Saftpresse99

-4

Si potrebbe utilizzare sotto pezzo di codice, che controllerà la richiesta in cui è venuta da

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

funziona benissimo per me !!!

+1

Questo è sbagliato e pericoloso. Limita solo CSRF allo stesso host e può potenzialmente interrompere le richieste reali se l'intestazione del referer viene rimossa, che è relativamente comune. – Steve

Problemi correlati