MVC sees the contribution that caused the exception

Sometimes we get some robots who like to post bad information on our website (they try some kind of reflection attack), but good luck for us, the attempts are stopped by checking the default input that you get using MVC.

This is good and that’s it, but now we want to see what the robots really send, and we would like to register this information. Unfortunately, when a person receives an HttpRequestValidationException , the abusive input is truncated to the point of uselessness ala;

A potentially dangerous.... (field = <a href=.....)

I try to use an action filter to detect these exceptions, and then I create a log of all violating input data so that we can see what they are trying to send.

 public void OnException(ExceptionContext filterContext) { HttpRequestValidationException hex = filterContext.Exception as HttpRequestValidationException; if (hex == null) { return; } // Get the data. This will explode throwing the same exception (`HttpRequestValidationException). Isn't there a way that we can get our hands on the information? string data = filterContext.HttpContext.Request.Form["field"]; .... 

It seems strange and annoying to me, because it seems that now I have no way to find out what my attackers are actually doing. Isn't there a way to get information from form data without getting exceptions?

+6
source share
3 answers

Here is the final solution I came across. Works like a charm and does not require interaction with the file system.

  // Grab the contents of the request. Stream s = filterContext.RequestContext.HttpContext.Request.InputStream; byte[] data = new byte[s.Length]; s.Read(data, 0, (int)s.Length); string rawData = Encoding.UTF8.GetString(data); // And process it into something nice and readable. IEnumerable<string> fields = (from x in rawData.Split('&') select HttpUtility.UrlDecode(x)); string formatted = string.Join(Environment.NewLine, fields); 
0
source

Yes, you can. Use HttpRequest.SaveAs to save the entire (buffered) HTTP request to disk, which you can then read.

+5
source

The problem is that actually calling Request.Form will do the validation (again). Then I would use Request.InputStream . You may need to rewind the stream before reading again:

Request.InputStream.Position = 0

-1
source

Source: https://habr.com/ru/post/974124/


All Articles