ASP.NET MVC 防偽令牌不安全
當向沒有 ssl 的伺服器發出請求時,我實際上可以看到 MVC3 框架以純文字形式生成的驗證令牌密鑰。
此密鑰儲存在名為:RequestVerificationToken_Lw_ 的 cookie 中
在混合安全環境中,實際上可以在對非 ssl 站點的初始請求中以純文字形式看到此令牌。此令牌在使用者會話期間也是靜態的。那麼當它很容易被攻擊者竊取時,擁有這個令牌有什麼用,因為 cookie 以純文字形式被扔掉。
不應該將此 cookie 標記為安全且永遠不會以純文字形式發送嗎?或者至少在每個請求上都重新生成,這樣安全資訊就不會從 ssl 通道中洩漏出來?
我說的是 MVC 3
AntiForgeryWorker類中的這個塊private string GetAntiForgeryTokenAndSetCookie(HttpContextBase httpContext, string salt, string domain, string path) { string forgeryTokenName = AntiForgeryData.GetAntiForgeryTokenName(httpContext.Request.ApplicationPath); AntiForgeryData token = (AntiForgeryData) null; HttpCookie httpCookie = httpContext.Request.Cookies[forgeryTokenName]; if (httpCookie != null) { try { token = this.Serializer.Deserialize(httpCookie.Value); } catch (HttpAntiForgeryException ex) { } } if (token == null) { token = AntiForgeryData.NewToken(); string str = this.Serializer.Serialize(token); HttpCookie cookie = new HttpCookie(forgeryTokenName, str) { HttpOnly = true, Domain = domain }; if (!string.IsNullOrEmpty(path)) cookie.Path = path; httpContext.Response.Cookies.Set(cookie); //Ma, Why isn't this marked as "SECURE" } return this.Serializer.Serialize(new AntiForgeryData(token) { Salt = salt, Username = AntiForgeryData.GetUsername(httpContext.User) }); }
為了防止 CSRF 攻擊,最佳解決方案是始終使用 SSL。是的,如果沒有 SSL,nonce(正如它所稱的那樣)很容易受到 MITM 攻擊。當使用 cookie 儲存 nonce 時,cookie必須標記為 HTTP-only。這可以防止 JavaScript 讀取 cookie。除了 cookie 之外,您還應該將 nonce 呈現為
<input type="hidden" value="nonce">所有 s 中的標記。<form>任何有權訪問瀏覽器本身的人都可以讀取 nonce,而防止重放攻擊的唯一方法是讓 nonce 在伺服器第一次驗證後第一次過期。但是,當使用者使用後退按鈕並使用相同的 nonce 重新送出請求時,這種方法可能會導致糟糕的使用者體驗。因為您使用的是 ASP.NET MVC 的內置反 CSRF 保護機制,所以將其行為更改為只允許使用一次 nonce 可能並不容易。(編輯:感謝下面的 Levi 告訴我 ASP.NET MVC 實際上使這變得非常簡單)
如果您想更好地控制生成和驗證隨機數,那麼我建議滾動您自己的實現,就像我對 JuniorRoute 框架所做的那樣。事實上,隨意看看JuniorRoute 的原始碼,看看我是如何實現它的。Stack Overflow 文章的程式碼太多了。
那是您那裡的煽動性問題標題。
內置的 MVC 防偽功能與應用程序配置的一樣安全。
<httpCookies requireSSL="true" />如果在 Web.config 中設置,所有寫入 Response.Cookies 的 cookie 都將自動標記為“安全”修飾符(請參閱 MSDN 文件)。如果設置了此開關,MVC 的防偽 cookie 也會獲得此行為。將其與其他功能(例如在響應中設置 HSTS 標頭)結合使用,您實際上是在保證瀏覽器永遠不會通過純文字通道發送敏感數據。
此外,防偽系統確實允許將自定義數據儲存在令牌中,並且您可以在令牌驗證時收到回調以驗證自定義數據。有關詳細資訊,請參閱AntiForgeryConfig.AdditionalDataProvider。