2009-08-24 17 views
16

Possiedo un sito Web di .NET. È necessario pubblicare sulla mia applicazione MVC che si trova attualmente all'interno del sito Webform come applicazione separata.Generazione di AntiForgeryToken in WebForms

L'applicazione Webform deve inviare POST alcuni valori sensibili all'applicazione MVC.

C'è un modo per generare un AntiForgeryToken() nella mia applicazione WebForms in modo che possa essere passato con il post del modulo.

Altrimenti qualcuno sa di un altro codice anti falso personalizzato che mi consentirà di fare qualcosa di simile a AntiForgeryValidation di MVC.

risposta

8

L'implementazione da soli non è troppo difficile.

  • generare un GUID
  • Mettetela in un campo nascosto
  • anche metterlo in sessione o cookie (in quest'ultimo caso, con un po 'di protezione anti-manomissione)
  • All'inizio della lavorazione del modulo confronta il campo e il token memorizzato.

(Se si guarda l'implementazione di MVC, c'è ben poco di più. Alcuni metodi di supporto è tutto ciò che serve.)

+1

eventuali codici per mostrare come fare questo? –

+2

@ShekharPankaj Vedere [Cheat Sheet di sicurezza OWASP .NET] (https://www.owasp.org/index.php/.NET_Security_Cheat_Sheet#ASP.NET_Web_Forms_Guidance). Assicurati di averlo compreso prima di integrarti (ovvero da cosa ti protegge e, cosa più importante, da cosa non ti protegge da http://security.stackexchange.com/q/59470). – tne

2

WebForms ha un analogo abbastanza simile in Page.ViewStateUserKey. Per setting that to a per-user value (la maggior parte sceglie HttpSessionState.SessionId), WebForms convaliderà il ViewState come parte di the MAC check.

overrides OnInit(EventArgs e) { 
    base.OnInit(e); 
    ViewStateUserKey = Session.SessionId; 
} 

ci sono scenari in cui ViewStateUserKey will not help. Principalmente, si riducono a fare cose pericolose con le richieste GET (o in Page_Load senza controllare IsPostback), o disabilitando ViewStateMAC.

1

È possibile utilizzare la riflessione per ottenere i metodi MVC utilizzati per impostare il cookie e l'input del modulo di corrispondenza utilizzato per la convalida MVC. In questo modo puoi avere un'azione MVC con gli attributi [AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken] che puoi pubblicare da una pagina generata da WebForms.

Vai a questa risposta: Using an MVC HtmlHelper from a WebForm

7

Questa è una vecchia questione, ma il modello di ASP.NET ultimo Visual Studio 2012 per moduli web include contro codice CSRF cotto nella pagina master. Se non si dispone di modelli, ecco il codice che genera:

Protected Sub Page_Init(sender As Object, e As System.EventArgs) 


    ' The code below helps to protect against XSRF attacks 
    Dim requestCookie As HttpCookie = Request.Cookies(AntiXsrfTokenKey) 
    Dim requestCookieGuidValue As Guid 
    If ((Not requestCookie Is Nothing) AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue)) Then 
     ' 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 

     Dim responseCookie As HttpCookie = New HttpCookie(AntiXsrfTokenKey) With {.HttpOnly = True, .Value = _antiXsrfTokenValue} 
     If (FormsAuthentication.RequireSSL And Request.IsSecureConnection) Then 
      responseCookie.Secure = True 
     End If 
     Response.Cookies.Set(responseCookie) 
    End If 

    AddHandler Page.PreLoad, AddressOf master_Page_PreLoad 
End Sub 

Private Sub master_Page_PreLoad(sender As Object, e As System.EventArgs) 


    If (Not IsPostBack) Then 
     ' Set Anti-XSRF token 
     ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey 
     ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty) 
    Else 
     ' Validate the Anti-XSRF token 
     If (Not DirectCast(ViewState(AntiXsrfTokenKey), String) = _antiXsrfTokenValue _ 
      Or Not DirectCast(ViewState(AntiXsrfUserNameKey), String) = If(Context.User.Identity.Name, String.Empty)) Then 
      Throw New InvalidOperationException("Validation of Anti-XSRF token failed.") 
     End If 
    End If 
End Sub 
+1

Post eccellente, ma hai perso 3 righe in cui 'AntiXsrfTokenKey' e' AntiXsrfUserNameKey', e '_antiXsrfTokenValue' è dichiarato. Potrebbe essere utile aggiornare per alcuni :-) – EvilDr

+0

@IanIppolito Questo codice convaliderà le richieste che sono dirette al gestore?Perché in quel momento penso che questo codice non verrà eseguito. –

+0

Ciao signore, sto usando VS2013 e .Net FrameWork 4.5 per creare la mia app di modulo web ASP.net, ma la mia pagina principale non contiene questo codice generato automaticamente, come faccio a sapere se il mio sito è sicuro da CSRF? –

3

Il C# versione di Ian Ippolito risposta qui:

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

    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 
} 
+0

È necessario convalidare con l'identità utente dal contesto? Lo stato della vista rimarrà allo stato di quella pagina mentre il Contesto continua tra le pagine. Se la modifica dell'identità (sfogliando con più schede) nel momento in cui viene eseguita la convalida genererà un'eccezione poiché il ViewState non sarà cambiato. – Tristan

Problemi correlati