<pages validateRequest="false" /> and <httpRuntime requestValidationMode="2.0" /> not working - asp.net

I've inherited an MVC asp.net app using framework 4.0.
I'm getting the dreaded "A potentially dangerous Request.Form value was detected from the client" error and all my research leads me to believe that this should fix it:
<system.web>
<httpRuntime requestValidationMode="2.0" />
<pages validateRequest="false" />
</system.web>
However, I've added that to my web.config and still get the error. I'm at the end of my rope here, what am I missing?

In addition to what you did you also have to decorate your methods with the ValidateInput attribute.
[ValidateInput(false)]
public ActionResult MyActionMethod(string myParameter)
{
// Method implementation goes here...
}
There is an alternative though, you can implement your own request validator and bind that in your web.config if you want to handle validation for your entire site. Take a look at this blog post on how to fully implement it.
Basically, create a class that inherits from RequestValidator and then hook it up on the web.config.
<httpRuntime requestValidationType=”Globals.CustomRequestValidation”/>
Hopefully this helps!

Take another approach. In the httpRuntime, point to your custom validation class. This way have the complete control over incoming requests as the validator is fired upon each single request, at the beginning of the processing pipeline.
In particular, if you implement your validator to return true, you will unconditionally accept all incoming requests.
http://msdn.microsoft.com/en-us/library/system.web.util.requestvalidator.aspx

The simplest way is to remove the characters you want from the validation system.
Here is the requestPathInvalidCharacters attribute from the httpRuntime element with its default value.
<httpRuntime requestPathInvalidCharacters="<,>,*,%,&,:,\" />
<!-- the unescaped characters are: < > * % & : \ -->
Remove the characters you want to authorize and the request will work.

Related

Sending binary data though POST

I'm using system.text.utf8encoding.utf8.getstring to convert a byte array to a string and then am sending it to my asp.net program through a regular web request as a POST value. Every now and then, I get an exception
"A potentially dangerous Request.Form value was detected from the
client "
Is it possible to get rid of that?
EDIT: never mind, I started using webclient.uploaddata to send and receiving by request.binaryread instead, this method doesn't seem to have this problem.
try to Add below code put to your web.config file.
<system.web>
<pages validateRequest="false" />
</system.web>

Why do some 'potentially dangerous Request.Path' HttpExceptions ignore httpErrors settings?

I have a .Net website with custom error pages configured using the web.config httpErrors section:
<httpErrors errorMode="Custom" existingResponse="Replace">
<clear/>
<error statusCode="400" path="/page-not-found/" responseMode="ExecuteURL" />
<error statusCode="404" path="/page-not-found/" responseMode="ExecuteURL" />
<error statusCode="500" path="/error/" responseMode="ExecuteURL" />
</httpErrors>
and
<httpRuntime requestValidationMode="2.0" targetFramework="4.5" />
When I visit http://www.example.com/< the site displays the correct "page not found" page, however if I visit http://www.example.com/<a it displays a YSOD with a 500 status code response header.
I have Elmah hooked up and both URLs predictably throw exactly the same error System.Web.HttpException: A potentially dangerous Request.Path value was detected from the client (<).
But why are the two URLs not handled the same? Why is one rewritten to my custom error page, and the other not? I would expect the same behaviour from any exception.
Edit:
I should have mentioned up front that this was an Umbraco project. I thought that this wasn't a contributing factor but I created a barebones .Net project with no dependencies and this worked as expected, i.e. both URLs obeyed the httpErrors configuration. So this must be something Umbraco specific, probably a module.
The validate helper method first calls validation for input and then paths.
The default values that are set in the default configuration for the validate helper method when validating input from the default web.config setting located at "syste.web/httRuntime" requestPathInvalidCharactersArray attribute are:
<,>,*,%,&,:,\,?
source: https://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.requestpathinvalidcharacters(v=vs.110).aspx
As you can see "<" is being treated as an invalid PATH whereas "<a" would be treated as invalid INPUT and that is why you get two behaviors.
If you're curious as to how I figured this out, I just looked at the source code for the validate helper method and followed it back to the source.
[EDIT]
The ValidateInputIfRequiredByConfig Method shows it throwing a 400
[EDIT 2]
public NameValueCollection QueryString
{
get
{
this.EnsureQueryString();
if (this._flags[1])
{
this._flags.Clear(1);
this.ValidateHttpValueCollection(this._queryString, RequestValidationSource.QueryString);
}
return this._queryString;
}
}
Calls to this property hit the ValidateHttpValueCollection can validate the querystring if the validation source is Querystring, which it is in this property.
In this method there is a method called ValidateString. In ValidateString it determines if it's a valid string or not and if not it throws a HttpRequestValidationException
After a fair amount of digging, I can see that this was actually caused by a 3rd party module called ClientDependency. Removal of this and the normal behaviour returned but obviously in this case the backoffice will not function properly.
A patch on the project is required and I've submitted this.
Update:
This bug in ClientDependency has been fixed as of v1.8.3

Google Adwords tracking cookie triggers ASP.NET Request Validation exception

Sorry for my English.
I have a strange problem.
When user click adword link, Google write tracking cookie like that
1813234232.1302674912.30.51.utmgclid=CcgezrsXjagCFcs-zAod_h2oCQ|utmccn=(not set)|utmcmd=(not set)|utmctr= CAA:89 AB0=40#B%20>:
In keyword section(utmctr) there is bad braskets, that cause request validation exception
A potentially dangerous Request.Cookies value was detected from the client (__utmz="...0=40#B%20> at System.Web.HttpRequest.ValidateCookieCollection(HttpCookieCollection cc)
Is there any way to solve this problem without turning off request validation?
Edited
I'm probably found obvious solution: write own request validation module http://jefferytay.wordpress.com/2010/04/15/creating-your-own-custom-request-validation/
By default asp.net validate and check the data for potential attacts.
You can disable this automatic validation by set validateRequest="false" ether on page
<%# Page validateRequest="false" %>
ether on web.config that affect all pages.
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
The only think that you need to check by your self after that, is if someone enters any script data to your inputs. Your inputs then need to check out when you render them on the page, and when you enter them on the database.

IIS7 Overrides customErrors when setting Response.StatusCode?

Having a weird problem here. Everybody knows that if you use web.config's customErrors section to make a custom error page, that you should set your Response.StatusCode to whatever is appropriate. For example, if I make a custom 404 page and name it 404.aspx, I could put <% Response.StatusCode = 404 %> in the contents in order to make it have a true 404 status header.
Follow me so far? Good. Now try to do this on IIS7. I cannot get it to work, period. If Response.StatusCode is set in the custom error page, IIS7 seems to override the custom error page completely, and shows its own status page (if you have one configured.)
Has anyone else seen this behavior and also maybe know how to work around it? It was working under IIS6, so I don't know why things changed.
Note: This is not the same as the issue in ASP.NET Custom 404 Returning 200 OK Instead of 404 Not Found
Set existingResponse to PassThrough in system.webServer/httpErrors section:
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
Default value of existingResponse property is Auto:
Auto tells custom error module to do the right thing. Actual error text seen by clients will be affected depending on value of fTrySkipCustomErrors returned in IHttpResponse::GetStatus call. When fTrySkipCustomErrors is set to true, custom error module will let the response pass through but if it is set to false, custom errors module replaces text with its own text.
More information: What to expect from IIS7 custom error module
The easiest way to make the behavior consistent is to clear the error and use Response.TrySkipIisCustomErrors and set it to true. This will override the IIS global error page handling from within your page or the global error handler in Application_Error.
Server.ClearError();
Response.TrySkipIisCustomErrors = true;
Typically you should do this in your Application_Error handler that handles all errors that your application error handlers are not catching.
More detailed info can be found in this blog post:
http://www.west-wind.com/weblog/posts/745738.aspx
Solved: It turns out that "Detailed Errors" needs to be on in order for IIS7 to "passthrough" any error page you might have. See http://forums.iis.net/t/1146653.aspx
I'm not sure if this is similar in nature or not, but I solved an issue that sounds similar on the surface and here's how I handled it.
First of all, the default value for existingResponse (Auto) was the correct answer in my case, since I have a custom 404, 400 and 500 (I could create others, but these three will suffice for what I'm doing). Here are the relevant sections that helped me.
From web.config:
<customErrors mode="Off" />
And
<httpErrors errorMode="Custom" existingResponse="Auto" defaultResponseMode="ExecuteURL">
<clear />
<error statusCode="404" path="/errors/404.aspx" responseMode="ExecuteURL" />
<error statusCode="500" path="/errors/500.aspx" responseMode="ExecuteURL" />
<error statusCode="400" path="/errors/400.aspx" responseMode="ExecuteURL" />
</httpErrors>
From there, I added this into Application_Error on global.asax:
Response.TrySkipIisCustomErrors = True
On each of my custom error pages I had to include the correct response status code. In my case, I'm using a custom 404 to send users to different sections of my site, so I don't want a 404 status code returned unless it actually is a dead page.
Anyway, that's how I did it. Hope that helps someone.
This issue has been a major headache. None of the suggestions previously mentioned alone solved it for me, so I'm including my solution. For the record, our environment/platform uses:
.NET Framework 4
MVC 3
IIS8 (workstation) and IIS7 (web server)
Specifically, I was trying to get an HTTP 404 response that would redirect the user to our custom 404 page (via the Web.config settings).
First, my code had to throw an HttpException. Returning a NotFoundResult from the controller did not achieve the results I was after.
throw new HttpException(404, "There is no class with that subject");
Then I had to configure both the customErrors and httpError nodes in the Web.config.
<customErrors mode="On" defaultRedirect="/classes/Error.aspx">
<error statusCode="404" redirect="/classes/404.html" />
</customErrors>
...
<httpErrors errorMode="Custom" existingResponse="Auto" defaultResponseMode="ExecuteURL">
<clear />
<error statusCode="404" path="/classes/404.aspx" responseMode="ExecuteURL" />
</httpErrors>
Note that I left the existingResponse as Auto, which is different than the solution #sefl provided.
The customErrors settings appeared to be necessary for handling my explicitly thrown HttpException, while the httpErrors node handled URLs that fell outside of the route patterns specified in Globals.asax.cs.
P.S. With these settings I did not need to set Response.TrySkipIisCustomErrors
TrySkipIisCustomErrors is only a part of a puzzle. If you use Custom Error Pages but you also want to deliver some RESTful content based on 4xx statuses then you have a problem. Setting web.config's httpErrors.existingResponse to "Auto" does not work, because .net seems to always deliver some page content to IIS, therefore using "Auto" causes all (or at least some) Custom Error Pages to be not used. Using "Replace" won't work too, because response will contain your http status code, but its content will be empty or filled with Custom Error Page. And the "PassThrough" in fact turns the CEP off, so it can't be used.
So if you want to bypass CEP for some cases (by bypassing I mean returning status 4xx with some content) you will need additional step: clean the error:
void Application_Error(object sender, EventArgs e)
{
var httpException = Context.Server.GetLastError() as HttpException;
var statusCode = httpException != null ? httpException.GetHttpCode() : (int)HttpStatusCode.InternalServerError;
Context.Server.ClearError();
Context.Response.StatusCode = statusCode;
}
So if you want to use REST response (i.e. 400 - Bad Request) and send some content with it, you will just need to set TrySkipIisCustomErrors somewhere in action and set existingResponse to "Auto" in httpErrors section in web.config. Now:
when there's no error (action returns 4xx or 5xx) and some content is returned the CEP is not used and the content is passed to client;
when there's an error (an exception is thrown) the content returned by error handlers is removed, so the CEP is used.
If you want to return status with empty content from you action it will be treated as an empty response and CEP will be shown, so there's some room to improve this code.
By default IIS 7 uses detailed custom error messages so I would assume that Response.StatusCode will equal 404.XX rather than just 404.
You can configure IIS7 to use the simpler error message codes or modify your code handling the more detailed error messages that IIS7 offers.
More info available here:
http://blogs.iis.net/rakkimk/archive/2008/10/03/iis7-enabling-custom-error-pages.aspx
Further investigation revealed I had it the wrong way around - detailed messages aren't by default but perhaps they've been turned on, on your box if you're seeing the different error messages that you've mentioned.

How do I modify the timeout of an aspx page?

Is there a way to manually increase / decrease the timeout of a specific aspx page?
In the web.config:
<configuration>
<location path="~/Default.aspx">
<system.web>
<httpRuntime executionTimeout="1000"/>
</system.web>
</location>
</configuration>
The one thing to remember with this is that the timeout feature here will only invalidate the Session Timeout, but the user will still remain on whatever page they are on. This may cause issues with the flow of the application. As a rememdy, I keep the following in my Web.config file:
<appSettings>
<!-- Application Timeout is 10 minutes -->
<add key="SessionTimeoutMilliseconds" value="600000"/>
</appSettings>
In addition, my master page has the following code in my code behind file:
' Register Javascript timeout event to redirect to the login page after inactivity
Page.ClientScript.RegisterStartupScript(Me.GetType, "TimeoutScript", _
"setTimeout(""top.location.href = '/EAF/Login.aspx'""," & _
ConfigurationManager.AppSettings("SessionTimeoutMilliseconds") & ");", True)
and you should be all set on both ends.
If you are talking about the amount of time it takes before the page returns a timeout, then mnour's example - you may want to look at the machine.config file as well. If you talking about a session timing out, then you will need to use a JS timer that posts back when it reaches 0.

Resources