How to handle PrincipalPermission Security exceptions - c#

I have a simple method that is secured
[PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
protected void lnkClearCache_Click(object sender, EventArgs e)
{
...
}
If this is clicked without the role, it generates a System.Security.SecurityException: Request for principal permission failed. as expected.
I use ELMAH to handle logging for my errors, and I have a custom ELMAH event in my global.asax to transfer to the error pages in ways that preserve status codes which works correctly.
private void ErrorLog_Logged(object sender, ErrorLoggedEventArgs args)
{
var customErrorsSection = GetCustomErrorsSection();
var error = args.Entry;
string statusCode = error.Error.StatusCode.ToString();
if (statusCode == "0" && error is security exception)
statusCode = "403";
var errorSection = customErrorsSection.Errors[statusCode];
string redirectUrl = errorSection == null ?
customErrorsSection.DefaultRedirect : errorSection.Redirect;
RespondWithServerError(error.Id, redirectUrl, statusCode);
}
This works all well and fine and redirects to my error page which works properly, however instead of displaying the content as expected. I immediately get a second request for the error page but this time using the value of customErrorsSection.DefaultRedirect that does not come from my code in any way that I can see.
As far as I can tell it's almost as if when .NET raises an exception for PrincipalPermission and then lets the entire request complete, then after the request is complete it throws away the application response and instead responds with the default custom error.
When I'm debugging I do break on 2 separate exceptions for PrincipalPermission, whether this is a just a rethrow by .NET I'm not sure but my .NET code never sees the 2nd throw, nor does ELMAH. I always end up with a single response, single error logged, but that the url that finally renders to the browser is the default url and not 403 url that I specifically server.transferred to. If I browse to a /location that is secure I properly get the 403 error page.

I don´t excactly know where the problem is. But i´´m using something similar and for me this solution (minimized) works great.
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim er = HttpContext.Current.Error
If er.GetType.Equals(GetType(System.Security.SecurityException)) Then
HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl & "?ReturnUrl=" & HttpContext.Current.Request.Path)
End If
End Sub
That´s out of global.asax
But on some places I don´´t redirect, and just using try and catch the securityexception to display the user, that he is not allowed to perform such action.

Related

Response is not being written after Response.End() when request departs from asp:multiview or ajax

I wrote a HttpModule to intercept, evaluate and authorize requests, checking if logged user has appropriate access to the url being requested, in a pretty old legacy system written in ASP.NET 2.0(Web pages, not Web app), whose customer does not want to port to a newer framework. Restrictions have been loaded and cached at login time.
Everything works fine, except when some page contains an <asp:MultiView> component or when there is a button that launch an ajax method. When one of these situations occur, and user doesn't have rights to access that url, an alert box pops up with an "Unknown error" message, that came from a ThreadAbortException thrown by Response.End() method.
The question is: Why does my "Unauthorized" message is being overwritten by "Unknown Error" from the exception, only on these two situations?
Is there a way of doing an Url Authorization system, using database and caching and without cluttering Web.config with roles like those older ASP.NET samples?
// My module init method.
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
// PreRequestHandlerExecute is the first stage at ASP.NET Pipeline
// where we could get a fulfilled Session variable
}
private void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
// additional request filtering/validation/etc.
LoggedUser user = (LoggedUser)application.Session["user"];
string path = context.Request.Path;
// more checks and rules...
if (!checkUserAuthorization(path, user))
{
context.Response.Write("<script>alert('Unauthorized. Contact your manager.');</script>");
context.Response.Write("<script>window.history.back();</script>");
context.Response.StatusCode = 403;
context.Response.End();
}
}
EDIT: What I've already tried (with no goal):
Response.OutputStream.Close();
Response.Flush();
HttpApplication.CompleteRequest();
it's by design. you must ignore it and add a catch for that exception.
try {
context.Response.End();
}
catch{}
Foreword
After a lot of research, finally I got it. Considering ASP.NET 2.0, concerning AJAX operations, the project I'm working uses a Microsoft component called "Atlas", which in turn got renamed to ASP.NET AJAX. At the time this system was written, the developers used the beta ASP.NET AJAX (codename "Atlas") to address all ajax and partial rendering needs.
I needed to dig deeper in source code (thanks to Reflector), to understand and inspect from where does that "Unknown Error" comes.
Inside the Microsoft.Web.Atlas, there is a file named Microsoft.Web.Resources.ScriptLibrary.*.Atlas.js (where * could be Debug or Release) which is rendered at runtime through a WebResource.axd "proxy".
This javascript file have a bug, because it expects to ASP.NET request always return an HTTP 200 (OK) response code, which in my code it's not happening (I'm returning a 403 Forbidden code at my module).
Code
From Microsoft.Web.Resources.ScriptLibrary.*.Atlas.js taken from WebResource.axd:
this._onFormSubmitCompleted = function(sender, eventArgs) {
var isErrorMode = true;
var errorNode;
var delta;
if (sender.get_statusCode() == 200) {
delta = sender.get_xml();
if (delta) {
errorNode = delta.selectSingleNode("/delta/pageError");
if (!errorNode) {
isErrorMode = false;
}
}
}
if (isErrorMode) {
if (errorNode) {
pageErrorMessage = errorNode.attributes.getNamedItem('message').nodeValue;
}
else {
pageErrorMessage = 'Unknown error';
}
this._enterErrorMode(pageErrorMessage);
return;
}
// Code continues.
}
From this code, we can see that since response code is not an 200 OK, that errorNode variable won't be set, and this if (errorNode) statement will always be false.
In this case, I was left with two options: Always return HTTP 200 and modify all pages that have an <atlas:ScriptManager> with and add an ErrorTemplate tag on each, or supersede that script with one that consider non-HTTP 200 responses, loading it below </form> tag at the Master page.
There is a lot of tutorials on how to do a proper error handling when using ScriptManager and UpdatePanels (an official one here), by subscribing to the AsyncPostBackError event), but this beta version (Atlas) simply don't have this event.

Server cannot set status after HTTP headers have been sent - ELMAH

I have been receiving this error through ELMAH. Even though the program completes it's intended actions, I still receive this error through ELMAH and I'd like to know why and to fix it. I've gone through other threads and tried to use those suggestions but nothing I've read so far doesn't seem to work.
It's intended action is to create an excel document and then redirect the user to the page they were just on.
ActionResult:
public ActionResult ExportClaimNumberReport(int ClientID, string ClaimNo) {
ClaimNumberViewModel model = ClaimNumberReport(ClientID, ClaimNo);
CreateExcelFile.CreateExcelDocument(
model.ReportData.ToList(),
model.ReportDescription + (".xlsx"),
HttpContext.ApplicationInstance.Response);
ViewBag.client = client;
Response.Buffer = true;
Response.Redirect(Request.UrlReferrer.ToString());
if (!Response.IsRequestBeingRedirected) {
Response.Redirect("/Error/ErrorHandler");
}
return RedirectToAction("ErrorHandler", "Error");
}
If you need anymore info, just let me know
You will get the error because you are doing 2 redirects.
Once here
Response.Redirect(Request.UrlReferrer.ToString());
And then again here:
return RedirectToAction("ErrorHandler", "Error");
So the first redirect will write a redirect header to the response stream, then the second would try to do it again, but obviously you can't send http headers to the browser twice so it throws an exception. However the user won't notice because by the time the exception is thrown the browser has already been told to redirect elsewhere.
What you want to do is just call the Redirect method as the return statement from your controller action.
So replace all this:
Response.Redirect(Request.UrlReferrer.ToString());
if (!Response.IsRequestBeingRedirected) // this would always be false anyway
{
Response.Redirect("/Error/ErrorHandler");
}
return RedirectToAction("ErrorHandler", "Error");
With this:
return Redirect(Request.UrlReferrer.ToString())
Although why you are redirecting the browser back to the referring page is unclear.

Exception from MVC API to MVC site gives error

I have created an MVC (4) Web API which works fine. It has a simple login-method that throws an exception when the user cannot be found.
Besides the API I created a simple website that calls the API by HttpClient:
public T ExecutePost<T>(string apiUrl, IEnumerable<KeyValuePair<string, string>> postData) {
HttpContent content = null;
if (postData != null)
content = new FormUrlEncodedContent(postData);
var a = _client.PostAsync(apiUrl, content).ContinueWith(httpResponseMessage =>
JsonConvert.DeserializeObject<T>(httpResponseMessage.Result.Content.ReadAsStringAsync().Result)
);
return a.Result;
}
You can call this method as
ExecutePost<User>("url_to_controller_action_api", list_with_keys_and_values_to_post)
When this method calls the API with the postData-fiels username and password (both are correct and known by the system) an object called User will be returned... Works like a charm.
When I call this method with the wrong username and/or password, the API throws an exception (User not found), but the method ExecutePost throws an exception aswell and the web page shows a nice, yellow-isch, red-letter page with errors that the normal user does not understand. The reason is easy: The data sent back from the API is not the same as the data that can be put in the object User.
So, what I would like to do is deserialize the exception, from the API, in an object called Error and return that to the controller of the MVC website, so I can put the error "User not found" on the page with the correct design of the site.
What is the best way to do this? Try-catch in all actions? Doesn't feel right to me... So suggestions are more than welcome.
Most things I found were API-side stuff, but I want to fetch and handle the exception on the site-side.
Thanks in advance
On your Web API when you detect an invalid login, make sure that an HttpResponseException gets thrown with a status code of 401 (HttpStatusCode.Unauthorized).
//login failed:
var resp = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent("Invalid Username or password")
};
throw new HttpResponseException(resp);
In your calling code, you can then first check if httpResponseMessage.StatusCode==HttpStatusCode.OK before you attempt to deserialise the response into a User.
var a = _client.PostAsync(apiUrl, content).ContinueWith(httpResponseMessage => {
if (httpResponseMessage.Status!=HttpStatus.OK)
{
string ErrorMessage = httpResponseMessage.Result.Content.ReadAsStringAsync();
//and whatever you want to do with that error message here
}
else
{
try
{
var user = JsonConvert.DeserializeObject<T>(httpResponseMessage.Result.Content.ReadAsStringAsync().Result);
}
catch(Exception ex)
{
//honest to goodness unrecoverable failure on the webapi.
//all you can do here is fail gracefully to the caller.
}
}//endif (Status OK)
}//end anonymous function
);
If it's not a 200 then you can execute a second check to see if it's a 401 (and have some specific handling for invalid login) or a more general 500 (something went wrong on the server), etc, and get the actual error message of the exception ("Invalid Username or password") to send back to the client:
var errorMessage = httpResponseMessage.Content.ReadAsStringAsync().Result;
Finally, even if it is 200 then you should still try...catch the deserialisation operation so you can gracefully handle any issues with the returned data, if for whatever reason the data can't be turned into a User object.

Application_Error no longer triggers when published to IIS

OK I have the following code in my Global.asax file:
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objError = Server.GetLastError().GetBaseException();
Response.Redirect(
String.Format(
"/Error/{0}/{1}",
((HttpException)objError).GetHttpCode(),
Request.RawUrl));
}
To provide neat and tidy error urls like "/Error/404/TheNameOfTheRequestedPage". This works fine from VS 2008, but once published to my local machine, I get the default error page:
Error Summary
HTTP Error 404.0 - Not Found
The resource you are looking for has
been removed, had its name changed, or
is temporarily unavailable
Anyone know how to do this? I've chosen not to use system.web/customErrors because I don't have access to Server.GetLastError() from there (or at least it's never worked for me) and I want to get the http code.
This is most likely related to you triggering an IIS Http Error which is defined in the web.config under the nodes
<system.webServer>
<httpErrors>
</httpErrors>
<system.webServer>
If the issue is you're returning an a response code for 404 and getting the IIS 404 page the issue is you need to do
Response.TrySkipIisCustomErrors = true;
Before you let the response finish otherwise IIS will intercept the error.
This is completely beyond unintuitive especially if you set the status code yourself. I tried to figure a way to file a bug on Microsoft Connect that manually setting a http error code does not automatically set TrySkipIisCustomErrors but could not seem to figure out any relevant product to submit it to.
I had a similar problem, and a call to Server.ClearError() before the redirect did solve the problem.
In your case I would write
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objError = Server.GetLastError();
if(objError is HttpException){
//Need to clear the error, otherwise the buil-in redirect would occure
Server.ClearError();
Response.Redirect(
String.Format(
"/Error/{0}/{1}",
((HttpException)objError).GetHttpCode(),
Request.RawUrl));
}
}
Notice that Server.GetLastError().GetBaseException() returns the base exception, which isn't always the HttpException, the one you are looking for is just GetLastError().

How to catch ConfigurationErrorsException for violating maxRequestLength?

I am limiting file size users can upload to the site from Web.config. As explained here, it should throw a ConfigurationErrorsException if size is not accepted. I tried to catch it from the action method or controller for upload requests but no luck. Connection is resetted and I can't get it to show an error page.
I tried catching it in BeginRequest event but no matter what I do the exception is unhandled.
Here's the code:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
try
{
if (context.Request.ContentLength > maxRequestLength)
{
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
// Check if body contains data
if (workerRequest.HasEntityBody())
{
// get the total body length
int requestLength = workerRequest.GetTotalEntityBodyLength();
// Get the initial bytes loaded
int initialBytes = 0;
if (workerRequest.GetPreloadedEntityBody() != null)
initialBytes = workerRequest.GetPreloadedEntityBody().Length;
if (!workerRequest.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer = new byte[512];
// Set the received bytes to initial bytes before start reading
int receivedBytes = initialBytes;
while (requestLength - receivedBytes >= initialBytes)
{
// Read another set of bytes
initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);
// Update the received bytes
receivedBytes += initialBytes;
}
initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes);
}
}
}
}
catch(HttpException)
{
context.Response.Redirect(this.Request.Url.LocalPath + "?action=exception");
}
}
But I still get this:
Maximum request length exceeded.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Maximum request length exceeded.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Update:
What method raises the exception anyway? If I read the request it raises exception If I don't read it at all, I get "101 Connection Reset" in browser. What can be done here?
You cant catch error in action method becouse exception comes earlier, but you can catch it here
protected void Application_Error() {
var lastError = Server.GetLastError();
if(lastError !=null && lastError is HttpException && lastError.Message.Contains("exceed")) {
Response.Redirect("~/errors/RequestLengthExceeded");
}
}
Actualy when file size exceeds limits HttpException error arise.
There is also IIS limit on content - wich can't be catched in application. IIS 7 throws
HTTP Error 404.13 - Not Found The
request filtering module is configured
to deny a request that exceeds the
request content length.
You can google it, there is a lot of information about this iis error.
There is no way to do it right without a client-side help. You cannot determine if the request is too long unless you read all of it. If you read each request to the end, anyone come and keep your server busy. If you just look at content length and drop the request, other side is going to think there is a connection problem. It's nothing you can do with error handling, it's a shortcoming of HTTP.
You can use Flash or Javascript components to make it right because this thing can't fail nicely.
I am not 100% on this, but I think it might help if you tried changing:
context.Response.Redirect(this.Request.Url.LocalPath + "?action=exception");
to
Server.Transfer(this.Request.Url.LocalPath + "?action=exception,false)
My thinking is that the the over-max-request-length Request is still being processed in the Redirect call but if you tell it to ditch the form data, it will become under the max request length and then it might behave differently.
No guarantees, but its easy to check.
catch (Exception ex)
{
if (ex is HttpException && (ex as HttpException).WebEventCode == 3004)
{
//-- you can now inform the client that file uploaded was too large.
}
else
throw;
}
I have a similar issue in that I want to catch the 'Maximum request length exceeded' exception within the Application_Error handler and then do a Redirect.
(The difference is that I am writing a REST service with ASP.Net Web API and instead of redirecting to an error page, I wanted to redirect to an Error controller which would then return the appropriate response).
However, what I found was that when running the application through the ASP.Net Development Server, the Response.Redirect didn't seem to be working. Fiddler would state "ReadResponse() failed: The server did not return a response for this request."
My client (Advanced REST Client for Chrome) would simply show "0 NO RESPONSE".
If I then ran the application via a local copy of IIS on my development machine then the redirect would work correctly!
I'm not sure i can definitively say that Response.Redirect does not work on the ASP.Net Development Server but it certainly wasn't working in my situation.
So, I recommend trying to run your application through IIS instead of IIS Express or the Development Server and see if you get a different result.
See this link on how to Specify the Web Server for Web Projects in Visual Studio:
http://msdn.microsoft.com/en-us/library/ms178108(v=vs.100).aspx

Categories

Resources