Detect javascript injection in a querystring parameter value - c#

I have a ASP.Net MVC project where we have a requirement to prevent javascript injection. We have a few pages that accept a querystring parameter like the following
../Home/index?company=1234. What I am trying to prevent is something like this ../Home/index?company=%22;alert(24);+%22.
I thought about looking at the querystring parameter values individually to determine if there is invalid data.
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
bool isValidData = false
base.OnActionExecuting(filterContext);
try
{
if (filterContext.ActionParameters != null)
{
foreach (var item in filterContext.ActionParameters)
{
isValidData = ValidateQueryStringData(item.Value); //analyze querystring data
}
if(isValidData == false){
//throw error or take user to error screen
}
}
}
catch (Exception ex)
{
LogError(ex, "Log User Action");
}
I need to build the ValidateQueryStringData function. I'm having trouble determining what data would be invalid. Maybe look for javascript events or objects? I thought about looking for special characters (<,>,(),#,%) but those characters are present in some of the production data. Are there libraries that exist that can detect javascript in a string?

Related

ASP.NET MVC - Some way of calling an ActionView from an Void or an int

The reason is not to check if the account exist. I already have the [Authorize] on the top of the controller. This code below is only a test done to see if it was possible call the RedirectToAction or something like from a void or from a int int this case.
I have a public int GetPersonCode on a controller, and I wanto to put something like this:
public int GetPersonCode()
{
try
{
//This is setted on login
return (int)Session["PersonCode"];
}
catch (Exception e)
{
Log(e);
//Some way to redirect to the login
}
}
There is any way to do this?
Thanks.
It's a bit unclear what you're asking, but if you want to allow the action for authenticated users only, you should annotate your action or even the entire controller with the Authorize attribute and MVC will automatically redirect the user to the authentication page in order for the current session to be able to access the action.
You can also specify roles with the Authorize attribute, via its Roles property.
Update
If you want to open a different view, use RedirectToAction when needed.
Assuming you are trying to check if an account exists, or if a user is logged in (regardless of which) and you simply want to redirect the user to another page if there is an error, you can do as follows:
Change int GetPersonCode() to bool TryGetPersonCode(ref int value). It will look something like this:
public bool TryGetPersonCode(ref int value)
{
try
{
//This is setted on login
value = (int)Session["PersonCode"];
return true; // Success
}
catch (Exception e)
{
Log(e);
return false; // Failed
}
}
Then in the method where you are calling GetPersonCode() do this instead:
int value; // This value will be changed inside 'TryGetPersonCode()'
if (TryGetPersonCode(ref value))
{
// Success, do whatever you need with 'value'
}
else
{
// Failed, 'value' will still be null
// Here you can do your redirect
RedirectToAction("Login Failed Action");
}
This type of functionality is common in the .NET Framework. The boolean return indicates whether or not it worked. If it returns true, your value variable will have been set within the method. Otherwise, the value variable will not have been set and the method will have returned false, indicating something went wrong.
I hope this helps, good luck with whatever you are working on :)

Exception handling design from class libarary

I'm looking for some program design guidance.
I have a class library that handles data in a database. I have a winforms app that is the presentation layer for the user to input and manage data. Say for example the user inputs some data and attempts to save it. From the winforms app I do something like:
MyTool theTool = new MyTool();
MyTool.FirstName = this.Textbox1.Text;
MyTool.LastName = this.Textbox2.Text;
//etc...
int result = MyTool.SaveData(); //result is the ID of the inserted record.
MyTool is a type in my class library. Within this type I would have:
public int SaveData()
{
if (IsReadyForInput())
{
//..open a DB connection and save out the data
//..get the ID of the saved record
}
else
{
throw new ArgumentException("One or more arguments prevented saving the data");
}
return theID
}
private bool IsReadyForInput()
{
if (this.FirstName.Length == 0)
{ return false; }
if (this.LastName.Length == 0)
{return false;}
return true;
}
Now, what I'm interested in is the best design on how exception handling should work. For example the above method is not specific at all so the user doesn't know what's wrong. So I could rewrite this to do something like:
public void SaveData()
{
string errMess = IsReadyForInput();
if (errMess.Length == 0)
{
//..open a DB connection and save out the data
//..get the ID of the saved record
}
else {
throw new ArgumentException(errMess);
}
return theID
}
private string IsReadyForInput()
{
if (this.FirstName.Length == 0)
{ return "Specify a first name"; }
if (this.LastName.Length == 0)
{return "Specify a last name";}
return true;
}
However it just doesn't seem a very elegant (or fast) method to be comparing string lengths to find an error message. I had tried writing something like:
public void SaveData()
{
ValidateInput();
//..open a DB connection and save out the data
return theID
}
private void ValidateInput()
{
if (this.FirstName.Length == 0)
{ throw new ArgumentException("Specify a first name"; }
if (this.LastName.Length == 0)
{throw new ArgumentException("Specify a first name"; }
}
The problem with this is that the exception is actually thrown by ValidateInput when the front end is calling "SaveData", so when the exception reaches the top, to me, it would seem less clear (especially if there are multiple ways of calling "ValidateInput()" from within MyTool).
Additionally I am not sure what the best way to handle the exception on the front end would be because, if an error is thrown, the ID is never returned.
I guess I am just looking for some guidance on how to handle this situation and validation/error handling in general. Thanks for any help.
The first thing I wonder about is whether you need to throw an exception at all when ordinary control flow might be enough:
if (IsReadyForInput())
{
//..open a DB connection and save out the data
//..get the ID of the saved record
}
else
{
//..do whatever you need in case of invalid input
}
The obvious problem with this suggestion is that we are in a method somewhere in your class library, and some of the desired effects (displaying warnings to the user, etc.) happen in the WinForms layer. That, however, suggests a better solution; namely, to do the validation in the WinForms code:
if (IsReadyForInput())
{
int result = theTool.SaveData();
//...and whatever else should happen.
}
else
{
//..do whatever you need in case of invalid input
}
The above approach is simpler and makes the parts of your program less dependent on each other (as MyTool doesn't need to care about validation of user input) when compared to, e.g., throwing an exception or using special return values to signal failure.
Take a look at FluentValidation (http://fluentvalidation.codeplex.com/). I think it's what you're looking for.
With it you can define your validation rules and call its validation methods. It will return a full list of potential validation errors without causing exceptions to be thrown in your code.

When to Throw an Exception? When to Handle an Exception (Service Layer, Controller) where?

I rewritten my question as I think it was too wordy and maybe what I am trying to achieve was lost.
I written this code in notepad so it may have mistakes and some stuff maybe not well thoughout but it is to illustrate what I see my options are.
// I wrap all code send back from service layer to controller in this class.
public class ResponseResult
{
public ResponseResult()
{
Errors = new Dictionary<string, string>();
Status = new ResponseBase();
}
public void AddError(string key, string errorMessage)
{
if (!Errors.ContainsKey(key))
{
Errors.Add(key, errorMessage);
}
}
public bool IsValid()
{
if (Errors.Count > 0)
{
return false;
}
return true;
}
public Dictionary<string, string> Errors { get; private set; }
public ResponseBase Status { get; set; }
}
public class ResponseResult<T> : ResponseResult
{
public T Response { get; set; }
}
public class ResponseBase
{
public HttpStatusCode Code { get; set; }
public string Message { get; set; }
}
Option 1 (what I am using now)
//controller
public HttpResponseMessage GetVenue(int venueId)
{
if (venueId == 0)
{
ModelState.AddModelError("badVenueId", "venue id must be greater than 0");
if (ModelState.IsValid)
{
var venue = venueService.FindVenue(venueId);
return Request.CreateResponse<ResponseResult<Venue>>(venue.Status.Code, venue);
}
// a wrapper that I made to extract the model state and try to make all my request have same layout.
var responseResult = new ResponseResultWrapper();
responseResult.Status.Code = HttpStatusCode.BadRequest;
responseResult.Status.Message = GenericErrors.InvalidRequest;
responseResult.ModelStateToResponseResult(ModelState);
return Request.CreateResponse<ResponseResult>(responseResult.Status.Code, responseResult);
}
// service layer
public ResponseResult<Venue> FindVenue(int venueId)
{
ResponseResult<Venue> responseResult = new ResponseResult<Venue>();
try
{
// I know this check was done in the controller but pretend this is some more advanced business logic validation.
if(venueId == 0)
{
// this is like Model State Error in MVC and mostly likely would with some sort of field.
responseResult.Errors.Add("badVenueId", "venue id must be greater than 0");
responseResult.Status.Code = HttpStatusCode.BadRequest;
}
var venue = context.Venues.Where(x => x.Id == venueId).FirstOrDefault();
if(venue == null)
{
var foundVenue = thirdPartyService.GetVenue(venueId);
if(foundVenue == null)
{
responseResult.Status.Code = HttpStatusCode.NotFound;
responseResult.Status.Message = "Oops could not find Venue";
return responseResult;
}
else
{
var city = cityService.FindCity(foundVenue.CityName);
if(city == null)
{
city = cityService.CreateCity(foundVenue.CityName);
if(city.Response == null)
{
responseResult.Status.Code = city.Status.Code;
responseResult.Status.Message = city.Status.Message;
return responseResult;
}
CreateVenue(VenueId, city.Response, foundVenue.Name);
responseResult.Status.Code = HttpStatusCode.Ok;
// I don't think I would return a success message here as the venue being displayed back to the user should be good enough.
responseResult.Status.Message = "";
reponseResult.Response = foundVenue;
}
}
return responseResult;
}
}
catch (SqlException ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
responseResult.Status.Code = HttpStatusCode.InternalServerError;
responseResult.Status.Message = GenericErrors.InternalError;
// maybe roll back statement here depending on the method and what it is doing.
}
// should I catch this, I know it should be if you handle it but you don't want nasty messages going back to the user.
catch (InvalidOperationException ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
responseResult.Status.Code = HttpStatusCode.InternalServerError;
responseResult.Status.Message = GenericErrors.InternalError;
}
// should I catch this, I know it should be if you handle it but you don't want nasty messages going back to the user.
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
responseResult.Status.Code = HttpStatusCode.InternalServerError;
responseResult.Status.Message = GenericErrors.InternalError;
}
return responseResult;
}
// another service layer.
// it is ResponseResult<City> and not city because I could have a controller method that directly calls this method.
// but I also have a case where my other method in another service needs this as well.
public ResponseResult<City> CreateCity(string CityName)
{
ResponseResult<City> responseResult = new ResponseResult<City>();
try
{
City newCity = new City { Name = "N" };
context.Cities.Add(newCity);
context.SaveChanges();
responseResult.Status.Code = HttpStatusCode.Ok;
responseResult.Status.Message = "City was succesfully added";
}
// same catch statmens like above
catch (SqlException ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
responseResult.Status.Code = HttpStatusCode.InternalServerError;
responseResult.Status.Message = GenericErrors.InternalError;
// maybe roll back statement here depending on the method and what it is doing.
}
return responseResult;
}
As you can see the methods are all wrapped in the status codes as they could be directly called by the controller being public. FindCity() and CreateVenue() could also have this wrapping.
Option 2
public HttpResponseMessage GetVenue(int venueId)
{
try
{
if (venueId == 0)
{
ModelState.AddModelError("badVenueId", "venue id must be greater than 0");
if (ModelState.IsValid)
{
var venue = venueService.FindVenue(venueId);
return Request.CreateResponse<ResponseResult<Venue>>(HttpSatusCode.Ok, venue);
}
// a wrapper that I made to extract the model state and try to make all my request have same layout.
var responseResult = new ResponseResultWrapper();
responseResult.Status.Code = HttpStatusCode.BadRequest;
responseResult.Status.Message = GenericErrors.InvalidRequest;
responseResult.ModelStateToResponseResult(ModelState);
return Request.CreateResponse<ResponseResult>(responseResult.Status.Code, responseResult);
}
catchcatch (SqlException ex)
{
// can't remember how write this and too tried to look up.
return Request.CreateResponse(HttpStatusCode.InternalServerError;, "something here");
}
}
public Venue FindVenue(int venueId)
{
try
{
// how to pass back business logic error now without my wrapper?
if(venueId == 0)
{
// what here?
}
var venue = context.Venues.Where(x => x.Id == venueId).FirstOrDefault();
if(venue == null)
{
var foundVenue = thirdPartyService.GetVenue(venueId);
if(foundVenue == null)
{
// what here?
}
else
{
var city = cityService.FindCity(foundVenue.CityName);
if(city == null)
{
city = cityService.CreateCity(foundVenue.CityName);
if(city == null)
{
// what here?
}
CreateVenue(VenueId, city.Response, foundVenue.Name);
}
}
return venue;
}
}
catch (SqlException ex)
{
// should there be a try catch here now?
// I am guessing I am going to need to have this here if I need to do a rollback and can't do it in the controller
// throw exception here. Maybe this won't exist if no rollback is needed.
}
return null;
}
public City CreateCity(string CityName)
{
// if it crashes something I guess will catch it. Don't think I need to rollback here as only one statement being sent to database.
City newCity = new City { Name = "N" };
context.Cities.Add(newCity);
context.SaveChanges();
return newCity;
}
As you see with option 2, I might still need to wrap it in try catches for rollbacks and I am not sure how to handle advanced business validation.
Also with catching everything in the controller and sending back vanilla objects(without my wrapper) I am unsure how to do fine grain HttpStatus codes(say like notFound,Create and such)
Sorry for the brief response, but here is my general rule - if an exception occurs which you expect might happen, deal with it - either by retrying or telling the user something went wrong and giving them options to fix it.
If an unexpected exception occurs, if it's something you can deal with (e.g a timeout which you can retry) try to deal with it, otherwise get out - just think what any MS app does - e.g. office - you get an apology that something went wrong and the app ends. It's better to end gracefully than to potentially corrupt data and leave things in a real mess.
This is an article with Java-specific concepts and examples, but the broad principles here are the way to go.
Distinguish between fault exceptions, which are catastrophic and unrecoverable, and contingency exceptions, which are very much recoverable. Let the faults "bubble" to the fault barrier, where you handle appropriately. For example, you might log the error, E-mail someone or send a message to a message queue, and present the user with a nice, informative error page.
Whatever you do, be sure to preserve all the exception information from the source.
Hope that helps.
Throw an exception wherever your code determines that something has gone wrong.
You always need to handle exceptions in methods which are called directly by the end-user. This is to cater for unexpected errors which your code doesn't have specific handling for. Your generic handling code would typically log the error and may or may not include letting the user know that an unexpected error has occurred.
But if there are errors which you can expect ahead of time, you'll often want to handle these lower down in the code, nearer to the point at which they occur, so that your application can "recover" from the error and continue.
I think exceptions are useful any time you need to return details of a failure from a method, whilst being able to use the ideal return type for the method you're calling.
You said in your question:
Now for me I try to return error messages back to the the controller
and try not to really catch anything in the controller.
If the service method is supposed to ideally return a Venue object, how do you return this potential error message back to the controller? an out parameter? change the return type to something which has an error message property on it?
If you're doing either of those options, I think you're reinventing the wheel... i.e. creating a way to return exception information when one already exists.
Finally, Exceptions are strongly typed representations of what went wrong. If you return an error message, then that is fine to send back to the user, but if you need to programatically do different things based on the details of the error, then you don't want to be switching on magic string.
For example, wouldn't it be handy to differentiate between authorization errors and not found errors so you can return the most appropriate http status code to the user?
Don't forget that the Exception class has a Message property you can simply return to the user if you want to use it that way
To make sure I understand the question, your are creating a web service and want to know when to handle and when to throw exceptions.
In this situation I would strongly recommend that you catch all exceptions. "Unhandled" exceptions are very bad form. On web sites they result in displays that range from meaningless to dangerous by exposing internal information that you do no want the public to see.
If this is a good sized program I suggest that you create your own MyException class which derives from System.Exception. The purpose of this is provide a place for you to add additional information specific to your application. Here are some typical things I like to add to my MyException classes:
An ID number that will help me find the location in the code where the problem occurred.
A "LogMessage" method that logs the exception, sometimes to the Windows Event Log. Whether or not you log and to which log you write depends on what you want recorded, and the severity of the situation.
An indicator that shows the exception has been logged so the above method will not log twice even if it gets called more than once.
Anything else that might be useful given the circumstance.
I also like to put the text of the messages in an external resource file, like an XML document, and key them to the error number that you assign. This allows you to change the error text to improve clarity without having to redeploy the application.
Catch all exceptions and create a new instance of your MyException type and put the original exception into inner exception property. Below the first level of my application, I always throw one of my MyException instances rather than the original exception.
At the top level (application level), NEVER let an exception go unhandled and never throw your own exception. A better way is to return an error code and message in your data contract. That way the client application will only get what you want them to see. The only exceptions they'll need to worry about are the ones outside your scope, i.e. configuration errors or communication failures. In other words if they are able to invoke your service and the network stays connected you should give them a response they can interpret.
Hope this helps.
PS I didn't include a sample exception as I am sure a little searching will find many. Post if you want me to put up a simple sample.
Use try catch at all levels and bubble it up. Optionally, log the error in a file or database. I use text file - tab delimited. Capture at each level
1. Module Name (Use C# supplied methods to get this)
2. Method Name
3. Code Being Executed (User created - "Connecting to database")
4. Error Number
5. Error Description
6. Code Being Executed (User created - "Accessing database")
7. Error Number for the end user
8. Error Description for the end user
Additionally, I also pass a unique identifier like - Session Id in case of Web, Logged in User Id, User Name (if available)
I always have the Exception catch block. In here I set the error number as -0 and the message from the exception object as the error description. If it is SQL Server related - I capture SQL Exception. This generates an error number - I use that.
I want to extend this some more though.

What is the correct way to TRY to Response.Redirect?

I want to redirect to a url, but be informed if it fails.
As far as I know a simple try-catch block won't work here because a Redirect always throws an exception. Although I can check for that exception (ThreadAbortException), but is this the best way?
EDIT: I'm trying to Redirect to a certain url, and if it doesn't exist - to another url.
Since redirect is client side operation (server simply sends response with code 302 and header location set to redirect destination) you can't expect server side Request.Redirect call to give you any indications if redirect succeeds on client (or even if it will be followed).
You options:
just live with that
if redirect is local you can at least verify if local path exists (or if ysing MVC - if route with given parameters is defined).
if redirect is remote you can try to issue request on the server first and see if response is reasonable (like "not 404").
Unfortunately all server side options to see if destination page exist have serious drawbacks:
checking for Url is potentially slow operation
you will not be albe to pass authentication information/cookes to pages on remote locations
some servers respond with 200 for "page really does not exist, look somewhere else".
I don't think this code will win a prize, but this at least prevents the ThreadAbortException...
Inspired by the KB article
bool redirectOK = false;
try
{
Repsonse.Redirect(url, false);
redirectOK = true;
}
catch(Exception exp)
{
// log/handle/whatever
}
if (redirectOK)
{
// do what even you want for a serverside succeeded redirect
}
else
{
// do what ever you want for a failure to redirect
}
Well, this will check for a 404 error, then direct to the page if there is no error.
if URLExists(theURL){
Response.Redirect(theUrl);
}
else{
//redirect somewhere else
}
public static bool UrlExists(string url)
{
try
{
if (url == "")
{
return false;
}
else
{
new System.Net.WebClient().DownloadData(url);
return true;
}
}
catch (System.Net.WebException e)
{
try
{
if (((System.Net.HttpWebResponse)e.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
return false;
else
throw;
}
catch
{
return false;
}
}
}

Passing Errors (Exception Messages) from Repository to Controller Action in asp.net MVC2

I have been trying to develop an app using the repository pattern like in the Nerd Dinner application however I would like to handle exceptions in the repository and pass the exception messages back to the controller so that I can output the message in a nice page to the user.
How do I pass back this exception message, or even pass that an exception has occured in the repository.
http://www.asp.net/ajaxlibrary/jquery_errors.ashx
In the following example from the above url, "_repository.HasErrors" is used as a check but I want to know what the implementaion of this is in the repository in C# as I dont know how this is implemented and also if its possible to also get the error message as well.
01.// GET: /HandlejQueryErrors/Contact/Create
02.public ActionResult Create()
03.{
04. return View();
05.}
06.
07.// POST: /HandlejQueryErrors/Contact/Create
08.[HttpPost]
09.public ActionResult Create(ContactViewModel viewModel)
10.{
11. var response = new AjaxResponseViewModel();
12.
13. try
14. {
15. var contact = _repository.SaveOrUpdate(viewModel);
16. if (!_repository.HasErrors)
17. {
18. response.Success = true;
19. response.Message = "Your contact was successfully created!";
20. }
21. else
22. {
23. response.Message = "There was an error updating your contact!";
24. }
25. }
26. catch (Exception exception)
27. {
28. response.Success = false;
29. response.Messages exception.Message;
30. }
31.
32. return Json(response);
33.}
Thanks in advance.
You could allow your repository's exceptions to fall through, and override your controller's OnActionExecuted method to handle specific errors for you. Example:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception is RepositoryException)
{
filterContext.ExceptionHandled = true;
filterContext.Result = View("Exception", filterContext.Exception);
}
base.OnActionExecuted(filterContext);
}
So, in general in ASP.NET MVC you need to handle 2 kinds of errors: Validation errors, and System errors.
For System errors, those occurring because of some system rules violation (like foreign key constraint violation in database during insert), you should use try-catche operator and then pass them to the view in some way to show them to the user.
For validation errors, you should read about ASP.NET MVC Validation:
Validation with the Data Annotation Validators - here you can see how to validate simple validation rules using built-in annotation attributes.
Validating with a Service Layer - this is more advanced topic, where you can learn how to validate more complex validation rules (for example for inter-connected properties, etc.)
So, as a conclusion, think of separating the concerns about domain/business functionality from the concerns related to validation. The only common thing they should have (in the perfect scenario) is a view where you show the results of validation.
Personally I (taking 2-nd approach) even do a save in validation, so that Validation implementation knows about domain/business logic and manipulates it to validate all the rules. In the end of validation, if all rules were met, then it tries to save the data, and returns the validation error message in case of non-success. This is also a good start to go further and even localize your custom validation messages.
I hope this helps!
I personally still like the GetRuleViolations() approach started by ScottGu and would simply follow this through on the Repository.
In the controller I would do (pseudo here):
[HttpPost]
public ActionResult ControllerAction(MyViewModel viewModel)
{
ModelState.AddRuleViolations(viewModel.GetRuleViolations);
if (!ModelState.IsValid)
{
return View();
}
// Perform repository action (pseudo code to follow)
_repository.ClearErrorState();
_repository.DoSomething();
ModelState.AddRuleViolation(repository.GetRuleViolations());
if (!ModelState.IsValid)
{
return View();
}
return RedirectToAction("Foo","Bar");
}
class Repository
{
List<RuleViolation> _errors = new List<RuleViolation>();
public void ClearErrorState()
{
_errors.Clear();
}
public void DoSomething(...)
{
try
{
DoSomthingThatFails();
}
catch (Exception ex)
{
_errors.Add(new RuleViolation(null, "Error while saving customer");
_errors.Add(new RuleViolation("SSN", "SSN must be unique"); // This one I struggle with as bad design, tying UI element to data elements is bad, so generally I try to prevent everything when checking the viewmodel and only catch general (unforeseen) errors here.
}
}
public IEnumerable<RuleViolation> GetRuleViolations()
{
return _errors;
}
}

Categories

Resources