Computers, Programming, Technology, Music, Literature

Archive for the ‘Asp.Net MVC’ Category

Beefing Up Security In ASP.NET Part 2 Dot Net Bangalore 4th meet up on August 08 2015

leave a comment »

Written by gmaran23

August 10, 2015 at 7:14 pm

Programmatically encrypting sections in a web.config file

leave a comment »

 

During the talk “Beefing Up Security in ASP.NET – Part 2 at Dot Net Bangalore 4th meet up Aug 08 2015 “ someone asked how to encrypt web.config programmatically. Here’s an extract from a snippet I have used in the past. The below code should help you with the libraries you need to call, it is not complete, some parts of the code are removed. Copy & Paste may not work Sad smile

public static void EncryptConfigurationSection(string configurationSection)
{
    Configuration configurationFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    AppSettingsSection section = (AppSettingsSection)configurationFile.GetSection(configurationSection);

    if (!section.SectionInformation.IsProtected)
    {
        section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
        section.SectionInformation.ForceSave = true;
        config.Save(ConfigurationSaveMode.Full);
    }
}

 

 

Someone also asked if there is a way to specifically encrypt a particular attribute alone. I am afraid that is not possible out of the box. You could look at one of my RSCryptoServiceProvider implementation here to get started

https://ssiscipherboy.codeplex.com/SourceControl/latest#SSISCipherPackageSourceCode/SSISCipherUtil/AppCode/Cryptography/RSACipher.cs

Written by gmaran23

August 8, 2015 at 8:00 pm

Beefing Up Security In ASP.NET Dot Net Bangalore 3rd meet up on May 16 2015

leave a comment »

Let your IIS worker process crash with StackOverflowException

with one comment

 

This article was originally published for www.prowareness.com and could be located at http://www.prowareness.com/blog/let-your-iis-worker-process-crash-with-stackoverflowexception/

 

Months back I posted a screenshot at https://renouncedthoughts.wordpress.com/2013/12/05/system-stackoverflowexception-in-mscorlib-dll/, finally got time to write it down.

 

There was a Login page, that did some sort of authorization check beyond authenticating the user, and displayed an Access Denied page for those who weren’t lucky enough. This was all done by the ASP.NET MVC with ASPX view engine. So there’s things like Views, Partial Views, RenderPartial, and so on. The application also was heavily ajax enabled, so partial views really seemed to fit in at many places that did not want to include a master page content in the response text. There was a view file called AccessDenied.aspx that barked at unauthorized users. Things were working fine, and one day something broke, IIS was crashing without any meaningful error message. I lied, actually it did give a meaningful error message that was like – An unhandled exception of type ‘System.StackOverflowException’ occurred in mscorlib.dll. And the Call Stack showed some recursive function call. That is all there was to it.

Let’s look at a POC sample application below. Download the source from github – https://github.com/gmaran23/ASPXViewEngineCrash, Hit F5.

 

clip_image002[11]

 

When you click the AccessDeniedForCrash page, the below is what you see. An unhandled exception of type ‘System.StackOverflowException’ occurred in mscorlib.dll. If you look at the Call Stack window, there would be a lot of repeated method calling method.

 

clip_image002[13]

 

Let’s look at what happens when a view is requested, as in how the view engine probes the known locations to find the view definition. Click ViewDoesNotExist, and you would see an error page, that actually tells you the file locations that ASPX view engine probed to find a matching view. Pay attention to the search order where a .aspx file is searched first, and then the .ascx file.

clip_image002[15]

Now, if you go back to the StackOverflowExceptionInASPXViewEngine solution, there are two files called AccessDeniedForCrash.ascx and AccessDeniedForCrash.aspx under ~/Views/Home.

 

clip_image002[19]

 

The following code inside AccessDeniedForCrash.aspx calls the partial view AccessDeniedForCrash.ascx.

 

<asp:Content ID="Content3" ContentPlaceHolderID="FeaturedContent" runat="server">
            <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <% Html.RenderPartial("AccessDeniedForCrash"); %>
            </hgroup>
        </div>
    </section>
</asp:Content>

 

A typical programming practice right? You define sub routines, and you keep calling them as and when required. Reusability! You have created a partial view here (AccessDeniedForCrash.ascx), and kept calling the partial view inside the main view (AccessDeniedForCrash.aspx). But it was the ASPX view engine’s probing method that caused the recursive method call. The view engine reached AccessDeniedForCrash.aspx, as it came through the HomeController’s action method AccessDeniedForCrash. It tried to find a partial view AccessDeniedForCrash.ascx,  but always ended up with AccessDeniedForCrash.aspx because of the file search order; you know the rest of the story about recursion without an exit condition.

So, is this a programming error? or the framework error? or the ‘programmer did not understand the framework well’ error?

 

 

You may also like – https://renouncedthoughts.wordpress.com/2013/12/05/system-stackoverflowexception-in-mscorlib-dll/

Written by gmaran23

June 30, 2014 at 7:16 pm

Access Control through ASP.Net MVC Custom Action Filters

leave a comment »

 

A slightly different version of this article was originally published for www.prowareness.com and could be located at http://www.prowareness.com/blog/access-control-through-asp-net-mvc-custom-action-filters/

HttpModule being the gatekeeper ASP.Net, one level down is the Action Filters for ASP.Net MVC. While managing large scale applications, it would not always seem very rational to create new Controllers for every functionality sometimes. You may also want to restrict access to specific controllers or specific action methods, and if you worked it through you would end up with a code snipped like below. An if else condition everywhere you wanted access control.

        [HttpGet]
        public ActionResult CustomizeEmails()
        {
            if (Context.Login.IsAdministrator)
            {
                var viewModel = new CustomizeEmailViewModel();
                return View(viewModel);
            }
            else
            {
                return AccessDeniedView();
            }
        }

        [HttpGet]
        public ActionResult CustomizeUserHomePage()
        {
            if (Context.Login.IsAdministrator)
            {
                var viewModel = new CustomizeUserHomePageViewModel();
                return View(viewModel);
            }
            else
            {
                return AccessDeniedView();
            }
        }


Which is obviously redundant and does not reflect on code reusability principle. So you may choose to create a custom HttpModule for access control during the initial ASP.Net request pipeline, of if that is not a possible solution in your case (or like the one above in ASP.Net MVC), then you must be looking at building a custom action filter. Once you have that in place, you could decorate your required action methods with your access control custom filter, or the entire controller, or as a global action filter (post ASP.Net MVC 3) so that the action filter would get invoked on every controller in the application.

Below is the code snippet showing the bare minimal implementation of a custom action filter for access control. In case the current request does not come from an Administrator, then it redirects him to an AccessDenied action method in the CompanyController.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebClient.Filters
{
    public class AdminOnlyAction : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //Cast the filterContext.Controller to the controller that has the access control information 
            //In my case it happened to be a BaseController
            var baseController = ((BaseController)filterContext.Controller);

            if (!baseController.Context.Login.IsAdministrator)
            {
                filterContext
                    .HttpContext
                    .Response
                    .RedirectToRoute(new { controller = "Company", action = "AccessDenied" });
            }

            base.OnActionExecuting(filterContext);
        }
    }
}

 

The if else statements in the first snippets would take a little more elegant, and neat form.

        [HttpGet]
        [AdminOnlyAction]
        public ActionResult CustomizeEmails()
        {
                var viewModel = new CustomizeEmailViewModel();
                return View(viewModel);
        }

        [HttpGet]
        [AdminOnlyAction]
        public ActionResult CustomizeUserHomePage()
        {
                var viewModel = new CustomizeUserHomePageViewModel();
                return View(viewModel);
        }


Thus you would have a simple, elegant, and powerful access control mechanism via a custom action filter. If you like this kind of cleanliness in non MVC projects, please take a look at POSTSHARP as well.

Written by gmaran23

March 12, 2014 at 8:11 pm

System.StackOverflowException in mscorlib.dll

with one comment

 

Update – 30 June 2014: The original reason for this exception is posted here – https://renouncedthoughts.wordpress.com/2014/06/30/let-your-iis-worker-process-crash-with-stackoverflowexception/

 

This is just a picture down there. The last time I got this exception, it was a missing exit condition on a recursive loop in a Java program that a friend of mine was writing. I have got one from C# compiler, while I tried build a Console project couple of years ago. Restarting Visual studio fixed that one. Never really had a chance to take a screenshot, cause I think these are things that you don’t encounter often unless you explicitly tried for a demonstration. So here it is, archived.

 

image

 

You may also like – https://renouncedthoughts.wordpress.com/2014/06/30/let-your-iis-worker-process-crash-with-stackoverflowexception/ 

Written by gmaran23

December 5, 2013 at 12:37 am

Writing @helper like inline helper method for ASPX view engine

leave a comment »

 

This article was originally published for www.prowareness.com and could be located at http://www.prowareness.com/blog/writing-helper-like-inline-helper-method-for-aspx-view-engine/

When I started my MVC course with ASP.NET MVC 3, I got introduced to the @helper syntax with the Razor view engine. In case you didn’t know what an @helper syntax is, you may read more about it here. It is common that during training sessions, certain features of a technology may not appeal to you until you really use it, or until you have someone who puts that in perspective for you. So, I was dealing with an MVC application with ASPX view engine and I had a situation where I thought if I had Razor view engine, I could use the @helper syntax, and here’s what I ended up with.

 

The @helper syntax within Razor enables you to easily create re-usable helper methods that can encapsulate output functionality within your view templates.  They enable better code reuse, and can also facilitate more readable code. – Source

 

In this post, I will show you can write a Razor style @helper method for ASPX view engine. Some people like to call it the Inline helper method If you look at the end result of the helper method in Razor view engine and ASPX view engine, it not aesthetically similar or lucid, but it solves the purpose – you get re-usability within the view. There are alternative ways of achieving the same thing using a Html helper of a server method within the view, but I ended with this approach.

In the ASPX view engine, if you declare and initialize a variable, if would show up in the intelli-sense. In the same way, if you try declaring an Action delegate, it would show up in the intelli-sense.

 

image

 

And that’s the trick. Declare an Action delegate, initialize with an anonymous delegate. You are done.

    <% 
        Action<int> DisplayPrice2 = (price) =>
        {
            if (price < 5)
            {%>
    <span>FREE!</span>
    <%}
            else
            {%>
    <%: String.Format("{0:C2}", price)%>
    <%}
            };            
    %>

    <h2>Products (ASPX View Engine - with inline helper)</h2>
    <%foreach (var product in Model)
      {%>
    <li>
        <span class="producttitle">
            <%: product.Name %>
        </span>
        <span class="description">
            <%: product.Description%>
        </span>
        <span class="price">
            <% DisplayPrice2(product.Price); %>
        </span>
    </li>
    <%} %>

 

Note that when you initialize the Action delegate, you could either use the explicit delegate keyword or just a lambda.

Download: Sample projects including the source code for @helper sample in Razor view engine, and the Action delegate way of doing it in the ASPX view engine is downloadable at the SkyDrive location – http://sdrv.ms/15ykUXD

Written by gmaran23

September 27, 2013 at 6:19 pm

Posted in .Net, Asp.Net MVC, C#

Tagged with , ,

DI – Unity.Mvc3 and Object reference not set to an instance of an object.

leave a comment »

 

This article was originally published for www.prowareness.com and could be located at http://www.prowareness.com/blog/di-unity-mvc3-and-object-reference-not-set-to-an-instance-of-an-object/

 

When you use Unity.Mvc3 or Unity.Mvc4 for DI, odds are you might not even run in to the below exception/stack trace.

   at Unity.Mvc3.UnityDependencyResolver.get_ChildContainer()
   at Unity.Mvc3.UnityDependencyResolver.GetService(Type serviceType)
   at System.Web.Mvc.BuildManagerViewEngine.DefaultViewPageActivator.Create(ControllerContext controllerContext, Type type)
   at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)

 

But you’d never know what kind of system you are dealing with. By name, these dlls – Unity.Mvc3, and Unity.Mvc4 – imply that they need to be used with MVC applications; which means, they are many things related to a web page or web request that this dll might possibly expect, for instance, the web context, the authorization context, routing context and so on.

We were dealing with a system where we tried using Unity.Mvc3 for dependency injection, and a very few parts of existing functionalities started failing with the below stack trace.


image


This exception occurred because we invoke a background worker from the UI (to run a long running Task), and when the background worker finishes, it would call in RenderViewToString, and update the UI. During the second part a System.NullReferenceException was thrown. With the given stack trace it was evident that this was happening due to the Unity.Mvc3 at  Unity.Mvc3.UnityDependencyResolver.get_ChildContainer().

Searching internet yielded no results. We went and looked at the Unity.Mvc3 source code at and found that property named ChildContainer was expecting a HttpContext and our BackgroundWorker didn’t have that for obvious reasons. Hence the Object reference not set to an instance of an object.

image

http://unitymvc3.codeplex.com/SourceControl/latest#Unity.Mvc3/UnityDependencyResolver.cs


Credits to Brijesh, where he had it spot on when he saw the word HttpContext. We ended up removing Unity.Mvc3 completely and used the infamous custom dependency resolver implementing the System.Web.Mvc.IDependencyResolver interface.

Written by gmaran23

September 27, 2013 at 9:58 am

How Forms Authentication implements a secure timeout on the cookie?

leave a comment »

It does not take a genius to alter the timeout on a cookie that is stored on the browser’s memory. Third party browser add-ins and developer tool bars or HTTP interceptors are easiest ways to begin with. ASP.Net’s Forms Authentication and it’s SetAuthCookie method handles the time out in a secure way. By secure way I mean the time out value of the cookie is actually embedded in the value of the cookie itself.

Now we all know that the authenticated user’s name is part of the AuthCookie value, but it is interesting to know that the time out for the session cookie is handled the same way too. And the normal rules of cookie value encryption and MAC verification apply.

Read through the entire blog – http://brockallen.com/2012/06/04/membership-is-not-the-same-as-forms-authentication/

A few important notes below:

Forms Authentication issues a cookie and embeds the username inside the cookie. Upon subsequent requests to the server Forms reads the cookie, validates it, extracts the username and assigns the username to User.Identity.Name (as well as Thread.CurrentPrincipal.Identity.Name).

To implement the cookie-based scheme securely Forms Authentication does several things:

1) Protects the cookie by encrypting and MACing it. This provides protection against people reading the cookie (including the user) and tampering with the value (including the user).

2) Provides a secure timeout on the cookie. Forms does not rely upon the normal cookie timeout — the user could easily change this. Instead Forms embeds the cookie timeout in the encrypted/MAC’d cookie value.

3) Sets the cookie as HTTP-only. This prevents client-side JavaScript from accessing the cookie (Session, to its credit, does this as well).

4) Allows the cookie to be marked as SSL-only. This, unfortunately, is not the default nor required (but I think it should for both… well, at least the default).

Written by gmaran23

March 27, 2013 at 10:22 pm

Html Encoding and [ MvcHtmlString.Create, Html.Raw, and @ ]

leave a comment »

There is also an answer at stackoverflow that is on the similar lines – http://stackoverflow.com/questions/22491437/how-can-i-enter-quotes-to-white-list-on-htmlencode/22536280#22536280

 

What returns an encoded output by default, try it out yourself with the sample code below.

 

Code: Paste it in any .cshtml file.


@{
    string xssScript = "<script type='text/javascript'>alert('XssScript');</script>";
    string htmlEncodedXssScript = HttpUtility.HtmlEncode(xssScript);
    string doubleHtmlEncocedXssScript = HttpUtility.HtmlEncode(htmlEncodedXssScript);
}

<p>MvcHtmlString.Create</p>
<ol>
<li>@MvcHtmlString.Create(xssScript) </li>
<li>@MvcHtmlString.Create(htmlEncodedXssScript) </li>
<li>@MvcHtmlString.Create(doubleHtmlEncocedXssScript) </li>
</ol>

<p>Html.Raw</p>
<ol>
<li>@Html.Raw(xssScript) </li>
<li>@Html.Raw(htmlEncodedXssScript) </li>
<li>@Html.Raw(doubleHtmlEncocedXssScript) </li>
</ol>

<p>@@</p>
<ol>
<li>@xssScript </li>
<li>@htmlEncodedXssScript </li>
<li>@doubleHtmlEncocedXssScript </li>
</ol>

 

Sample Output:

image

 

Questions to ponder –

1. http://stackoverflow.com/questions/2293357/what-is-an-mvchtmlstring-and-when-should-i-use-it

2. http://stackoverflow.com/questions/10331019/difference-between-mvchtmlstring-create-and-html-raw

Written by gmaran23

January 10, 2013 at 12:02 am