關於我

我的相片
用心思考、保持熱情,把工作上的經驗作分享與紀錄。希望能夠跟大家一起不斷的成長~

ASP.NET 4.0 加強 Request Validation

再使用ASP.NET MVC 時,有需求做線上Html編輯的功能。

結果在存檔時,一直發生下方錯誤訊息,將解決過程記錄下來!

擷取 

1.一般在ASP.NET 2.0 很直覺得先將該網頁的ValidateRequest="false"屬性加上。

擷取2

加上後,信心滿滿的認為已經解決了..結果一跑測試錯誤依舊發生..

2.便再進一步心想乾脆直接在Web.Config設定看看

擷取3

執行後錯誤還是一樣發生。

3.這時已經想不出其他原因了,便上網Google一下,很多文章都提到使用ASP.Net MVC時遇到此情況,可在Action處加上ValidateRequest="false"的屬性。變測試了一下這方法。

擷取4

測試後依舊不行 Orz

4.最後終於還是在Google上找到一篇重點了!!

可參考此篇文章,http://stackoverflow.com/questions/2019843/a-potentially-dangerous-request-form-value-in-mvc-2-asp-net-4-0

裡面提到 This is a documented breaking change in ASP.NET 4. See this whitepaper 

我將其中於ASP.NET 4.0 對於Request Validation 更新的說明部分截錄出來,如下:

ASP.NET Request Validation

The request validation feature in ASP.NET provides a certain level of default protection against cross-site scripting (XSS) attacks. In previous versions of ASP.NET, request validation was enabled by default. However, it applied only to ASP.NET pages (.aspx files and their class files) and only when those pages were executing.

In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request.

As a result, request validation errors might now occur for requests that previously did not trigger errors. To revert to the behavior of the ASP.NET 2.0 request validation feature, add the following setting in the Web.config file:

<httpRuntime requestValidationMode="2.0" />

However, we recommend that you analyze any request validation errors to determine whether existing handlers, modules, or other custom code accesses potentially unsafe HTTP inputs that could be XSS attack vectors.

看到這裡,今天遇到的此問題的答案應該已經明瞭了!

原來是ASP.NET 4.0在Request驗證上,變得更嚴謹了!

以往Validation Request只對Asp.net 頁面的.aspx和codebeside .cs作用,一定要該網頁被執行,驗證才會做防護。

但於ASP.Net 4.0 將驗證防護,加強至Http BeginRequest時,便開始對Request做驗證!

因此包括WebService 甚至是自定義的HttpHandles、HttpModules都可做到驗證功能!

但這樣的驗證,很有可能讓一些既有程式發生驗證錯誤,

例如今天的Html編輯器需求,就一定會觸發到此驗證錯誤。

所以在ASP.NET 4.0可在Web.config中,設定要求執行時,驗證模式要使用2.0時的模式。

<httpRuntime requestValidationMode="2.0" />

擷取5

當然原文是不建議啦!!畢竟這樣就增加網站被攻擊的風險了!

 

另外想到,這樣的變更,如以後專案有需求要升級到ASP.NET 4.0。

也必須特別注意此問題!

沒有留言:

張貼留言