Tuesday, April 29, 2014

XSS attack into ASP.Net MVC 4 site via Javascript comment

Introduction

Till this moment I strongly believe that, software security can not be achieved. I am telling this within my 6 academic + 8 professional years of experience with computer systems. I did building computer systems as well as hacking the same. Whenever I architect a system most of the time I was able to forecast the holes too. But since timely release of the application takes more priority in most of the cases, I have no way except building the systems with security holes. 
"Computer software security is always a concept like perfection"
Hacking a desktop based software is more easy because we can always see the source code which helps to understand how its being executed. Sorry to the new generation developers who born into the managed world. When the old generation says source code its always assembly language which cannot be obfuscated or protected. Assembly language is enough to understand how the system works.

Web systems are easy to build as it requires primary knowledge of HTML and one scripting language. Now a days with the penetration of Node.JS, one can create web sites with only HTML & Javascript knowledge without even knowing how the web works on request-response mechanism. If a hacker finds out a security hole in a desktop system and make use of it, the impact will be normally less. For example if somebody hacks the serial key mechanism, only some people are going to use it, unless he puts that in internet. But think about a web system, if attacker succeeds in hacking a bank web site, the impact will be huge.

XSS is one type of the web attack.In short we can define that as below

"Injecting script into the system as if, it is input data and getting the same script executed on other user's browser"

I know this is not easy to digest at the first glance. If you need more details, visit the below links.
Below is one sort of XSS attack which uses the query string to inject script and makes it available inside a script block.
http://buffered.io/posts/xss-flaws-via-mvc-model-binding-and-request.querystring-inconsistencies/

One more special case is to exploit the javascript encoding and passes the javascript via innerHTML property of html elements.
http://weblogs.asp.net/jgalloway/archive/2011/04/28/preventing-javascript-encoding-xss-attacks-in-asp-net-mvc.aspx

XSS via commented JS which has ASP.Net MVC RAZOR token

Normally in MVC people may not use the old query string technique.Also the sites will be having the ASP.Net request validation enabled. The ASP.Net request validation scans all the requests for any possible script tags and throws exception on the same.

What if the script came through an Action method without script tag and renders with the help of a commented line and get executed without even an HTML event? Again, the Action method can be invoked both by get requests and post requests.

We are going to discuss how such a situation can occur.

The victim Web application / ASP.Net site

In most of the cases the security holes are opened by the programmers unknowingly. Lets take an example of a simple web site. Here the programmer wants to implement a contact page where the contact person's name comes via an action method.

@model MvcExceptionHandlingDemo.Models.Contact
@{
    ViewBag.Title = "Contact";
}
 
<hgroup class="title">
    <h1>@ViewBag.Title.</h1>
    <h2>@ViewBag.Message</h2>
    @using (Html.BeginForm())
    {
        @Html.LabelFor(s => s.Name)    @Html.TextBoxFor(s => s.Name)
        <input type="submit" value="Change" />
    }
</hgroup>

        public ActionResult Contact(string name)
        {
            ViewBag.Message = name;
            if (ViewData.Model == null)
            {
                ViewData.Model=new Contact(){Name=name};
            }
            return View();
        }
        [HttpPost]
        public ActionResult Contact(Contact c)
        {
            ViewBag.Message = c.Name;
            if (ViewData.Model == null) ViewData.Model = c;
            return View();
        }

One of his intention was to show the social profile of that person by using some web services which accepts name. So wrote a javascript function. But later he commented the js code because he was not able to find suitable web API which gives the social profiles.

<script type="text/javascript">
    function dispProfile() {
        //var s = '@ViewBag.Message';
    }
</script>

How to conduct attack

The base for this attack is the option of rendering text into javascript which is commented. The MVC framework doesn't know about the javascript comment. So it will do its duty which is nothing but rendering the value in @ViewBag.Message property.

What string we should inject as script in this scenario is little tricky.
  1. We need to close the existing js function. 
  2. Then we can have our script. Since it is outside of the function it will get executed when page loads.
  3. Finally we need to have a dummy function with only starting '{' to make sure the script is in correct syntax
Below is one sample javascript which we can inject

';
}
alert(2024);
function dummy(){
//

This will make sure dispProfile() function closed properly. and write the attack script (Here it is alert(2024);) and starts a new dummy function to make the syntax proper.Otherwise the dispProfile() function will be in open state. So after the injection the rendered script will be as follows.

 <script>
    function dispProfile() {
        //var s = '&#39;;
}
alert(2024);
function dummy(){
//';
    }
</script>

One more thing to remember is how to inject this script .One of the option is to exploit the Contact action method with msg parameter. If we normally inject any script tag the ASP.Net request validation system will throw error. But here we are not injecting the script tag as it is. Instead some fragments of script. The script as its cannot be added to URL. For that we need to use the URLEncoded string of the script. Encoded URL can be

http://localhost:50471/Home/Contact?msg=%27%3B%0A%7D%0Aalert(2024)%3B%0Afunction%20dummy()%7B%0A%2F%2F

There are so many online URL encoding and decoding sites. Those can be used to do the encoding.

How to prevent

In this case the problem is commented code. The intention of the programmer is to stop the functionality of dispProfile() but he forgot the fact that its containing RAZOR token. He should have commented RAZOR code as well. In other words here same program is handled by 2 execution engines. RAZOR & Javascript. So when commented it should be commented for both the engines.

Sample application can be downloaded from the below link.

Monday, April 21, 2014

How to remove Antlr3.Runtime & WebGrease from your ASP.Net MVC web application

What is Antlr3.Runtime & WebGrease

As of a new programmer those are the dll which increase the size of their project. Before we remove these dlls we should know what are those dlls and their duties? Those are the dlls used for Bundling and Minification. By default the Visual Studio adds those nuget packages in the newly created MVC web application.

http://westdiscgolf.blogspot.in/2012/06/aspnet-mvc-4-webapi-rc-what-on-earth-is.html
http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

When should we remove Antlr3.Runtime & WebGrease

Next thing we need to understand when we should remove those and why we need to remove? If you are creating a production application, never remove as those libraries will increase the performance of our application. We may not require if we are doing any of the following.
  • Creating a PoC and mailing the same which don't deal with minification and bundling.
  • Creating a sample for blogging.

Removing Antlr3.Runtime.dll & WebGrease.dll packages

Method 1 - nuget uninstallation

Below are the steps proper steps if we have the solutions in proper condiction
  • Open nuget package manager console or UI.
  • Execute the command Uninstall-package 'package name'.The order of removal is as follows
    • Microsoft.AspNet.Web.Optimization
    • WebGrease
    • Antlr
  • Follow the common steps for method 1 & 2

Method 2 - Manual removal

Use these steps if you are not able to make it via nuget.
  • Manually remove the reference to the Antlr3.Runtime.dll, WebGrease.dll & Microsoft.AspNet.Web.Optimization from solution explorer
  • Follow the common steps for method 1 & 2

Common steps for Method 1& 2

  • Remove or exclude the App_Start\BundleConfig.cs file.
  • Remove the method call BundleConfig.RegisterBundles(BundleTable.Bundles); from Global.asax.cs
  • Remove the import using System.Web.Optimization; from all code files.
  • Remove the @Scripts.Render() and @Styles.Render method calls from your view files
  • It will make the application fail, if we are using scripts and styles. You need to explicitly add the styles and scripts to the application For example to render styles add the below line.
  • <link rel="stylesheet" href="@Url.Content("~/Content/site.css")">
  • Remove the "System.Web.Optimization" entry from views\web.config file->
    <system.web.webPages.razor> -> <namespaces>
    
  • Clean the solution and delete everything in \bin folder

Method 3 - Remove the packages folder and bin folder and ask the user to sync nuget packages

As you see the problem its about sending the sample code to other user and his easiness to run the same. If the target developer knows about nuget, let him install the nuget packages before running the sample. This is the actual solution provided the target developer have enough internet connectivity to sync nuget packages.

I have tried this in MVC 4 & 5 from VS2010 & VS 2013 without any issues.
Happy coding.

Tuesday, April 15, 2014

Code for yourself before you code for others

I got a strike from the quote "Code for yourself before you code for others" when I attended Google IO Extended 2012 event. Even though I was developing tools for me, I never took that as serious in determining success of a Software engineer. After 2 years of experiments related the quote, I could see that this is something important for a software professional. Now I am utilizing this quote for hunting talent for my current company.

Usually in software services companies (I would like to call as code factories), the ultimate aim is to deliver the project with working features. If the delivery mode is "code delivery" there are chances that there will be an acceptable level of quality. But in the other way "features delivery", we can never expect quality in the code. The features will be working. That's all. In such companies the hiring pattern is as follows. I know the point here is about code for ourselves, but through this I can show the importance of, one coding for himself.

Hire worker people to increase head count

This happens in big companies in below situations
  • Show their strength for marketing and to get more projects
  • Show that they are stable, still growing and not affected by recession etc.
This also happens during the period a small company tries to become a medium company or when medium company is becoming large.

Type of People

In this type of recruitment companies normally goes to campus to recruit people from even non computer science branches such as Civil, Agriculture,Accounting etc...who sometimes doesn't know how to shut down the computer.
 
But the main focus in this hiring will be common sense of the candidates, so that they can be moulded as workers who at least don't harm the software systems.
 
If we think from the candidate perspective, these people will not be having particular aim in their life except to get equal status of others and earn money. When they complete their schools, they just listen to others(relatives & friends) words and select Electronics or Mechanical engineering, instead of hearing their own mind. Their mind may be telling them to become an accountant. But as the factor of common sense and adaptability is more, they will get more marks in the exams even though they don't know anything practically about their main stream subject. Believe or not I had multiple situations where people who scored more than 80% marks in Electrical engineering department don't know, why they are not getting electric shock, when they use tester to touch wires. These people again take others words and attend the interview conducted by software development companies.
 
Also these people won't read much about theory part computer science. If they know RegEx & parsing, I would say its really great. One of the benefit for them is they can switch to any other job at any time as they don't have the bonding with computer science. This is really helpful during recession days.
 
As these type of people don't have any particular aim except money, these people can be moulded to work on anything, provided they get right instructions.

Hire own people (Relatives & Friends)

This happens in most of the companies. The manager / higher level executives inject their own people into the company with their influence in 95% cases and rest through proper channel. They do it due to various reasons
  • His friend is really good in particular technology and the company needs the talent
  • He wants a strong team who can take his orders without fail or complaints.
  • His relative / friend is not getting job in other companies after he was fired from previous job or passed out of college.
  • He needs a spy in the team so that he can know the heart beat of the team.
  • He want to take his person to abroad. Let this be the way.

Type of people

95% of the people who are hired in this way will not be meeting the hiring criteria and will be a burden to their colleagues which in turn reduce the team's productivity and demotivate the loyal people. If these candidates are really skilled they should have joined in other companies. That itself shows these people are not worth.
 
The real trouble will be to the middle level leads to whom these hired people are reporting. He cannot keep the person in the team as he is not capable of doing the tasks, but afraid to escalate as he is backed by the manager. This in turn increase pressure to the rest of the team in meeting the deliveries. The pressure eventually makes the loyal and talented people, leaving the project or company.

Hire the talent to think & innovate

Worker people alone cannot run the company. There needs some smart people to think and take decisions and finding those people is really a tough job for interviewers. Within the 30-45 minutes how to identify whether the candidate is really talented or not? The future of the company relies in the hands of these people as these people are going to think and take decisions for the company.
 
I faced the challenge so many times. Earlier I used to give various scenarios and ask them to think about alternatives. If you are an interviewer, you don't need to worry about these type of questions. Just take one of the scenario in your project and explain them in a different way. If they think smart and provide better solution than what you implemented, you can even refine your solution :) .But don't get into trouble.
 
Now I have added one more criteria to the list and its nothing but "The solutions they developed for themselves". If they have solved their own problems successfully, 50% we can say he suits to the talent criteria.

Type of people

Here comes the passion. These people will be passionate about software engineering. They will not be just programmers of particular language. They try to understand what the user needs and think about various solutions and picks up the best one. They will be continuous learners and brave enough to remove or add new tools & technologies into the project. The toughest part is they don't compromise quality to meet delivery timeline.
 
In short if a company have at least one person like this, it can have 50 worker people.

Monday, April 7, 2014

Showing different RAZOR Views based on the Model type in ASP.Net MVC

Problem

In real time, there will be scenarios where we need to display different model classes differently in the Views. Normally, if the controller is aware of the Model type and knows the corresponding View, it can return the proper ViewResult object via its Action() methods. But what should we do, if we have an GenericBusinessObject ie an Entity which have its properties in a dictionary or enclosed in XElement and we need to switch the View based on the type of Generic Entity?

My current project have an offline processing feature which is controlled via queues. When somebody needs to process a long running task they put their request into the queue and the queue monitor mechanism dequeue the requests whenever there is space to process that request. This is a general framework where the track developer needs to write code for queuing the request which accepts the parameter in the form of xml. The parameter decide how the processing server process that particular request. The track developer also needs to write code for the actual processing by implementing certain interfaces. Simply saying the queuing system just makes the processing delayed until the processing servers have enough capacity to process the request and the details about how to process and related logic is decoupled from the queue framework as the operation detail is passed as xml.

This system also has monitoring web application as well where the production engineers can see how many queue items are waiting in the queue, how many failed etc...The web site also have provision to see the queue request parameter xml which is viewable only to the application support engineers. A trained application support engineer can identify, what a particular queue request is intended for, by analysing the queue requests parameter. This monitoring site is implemented using ASP.Net MVC 4 with a page to see all queue requests. Things were easy until we get a requirement to display different pages based on the queue request type, so that the application support engineers don't need to analyse the xml to know what is the intention of the queue request.

To understand the issue in a simple scenario, lets take Person object with 2 properties. PersonType and Properties. Definition is given below.

    public class Person
    {
        [Display(Name = "First Name")]
        public string PersonType { getset; }
        public XElement Properties { getset; }
    }

The Properties is kept as xml as it is having dynamic schema or in simple words variable number of properties. If the PersonType is Employee the Properties can include FirstName & Company.For Student type it can have FirstName,School & Marks. 
The MVC site is supposed to call a web service to get person  object list and display all the unique person types from the obtained person list. When the user clicks on the PersonType link it should display Person objects corresponding to the person type. If the type is known such as Student display 3 columns and if its unknown just show the Person type. The URL might look like as below
site.com/Person/List?personType=Employee
or
site.com/Person/List?personType=Student

Challenges

  • If we just return the model from Action method, it cannot render as it don't know the View corresponding to the Model.
  • If we put if/switch condition based on the PersonType in the List.cshtml and render the <Table> accordingly the List.cshtml will grow to large size.
  • We can have same if/switch based on PersonType and render partial views which will limit the size of the List.cshtml. But again the partial view need to have logic for parsing the XML and display accordingly.

Solution

The better solution, I could think of is "having an abstraction for parsing the xml to create concrete model classes and give to View for just display" instead of view working on Model to find out what is relevant. So the logic of parsing xml is done in the Action and it returns typed model class object to the corresponding views. When we say abstraction, its just and interface which returns the typed objects and the corresponding view name. The implemented classes will have the logic of parsing the xml to convert to typed objects. Only consideration is about having a base class for view model classes which are returned from the interface methods or properties.

It is not the perfect solution. We can argue on merits of having partial views v/s this provider mechanism. But its worth looking at this provider mechanism as well. Below is the relevant code for this approach.

    public class ViewModelBase
    {
    }
//Typed class for student.It will differ for employee
    public class StudentViewModel:ViewModelBase
    {
        public IEnumerable<StudentModel> Students { getset; }
    }
    public class StudentModel
    {
        [Display(Name = "First Name")]
        public string FirstName { getset; }
        [Display(Name = "School")]
        public string School { getset; }
        [Display(Name = "Marks")]
        public string Marks { getset; }
    }
    public class DefaultViewModel : ViewModelBase
    {
        //Reuse the Person itself instead of DefaultModel
        public IEnumerable<Person> Persons { getset; }
    }
/////////////////Classes related to provider model.
    public interface IViewModelProvider
    {
        ViewModelBase GetViewModel(IList<Person> persons);
        string ViewName { get; }
    }
    internal partial class StudentViewModelProvider : IViewModelProvider
    {
        ViewModelBase IViewModelProvider.GetViewModel(IList<Models.Person> persons)
        {
            StudentViewModel studVMList = new StudentViewModel() { };
            studVMList.Students = persons.Select(p=>new StudentModel(){
                FirstName = p.Properties.Attribute("FirstName").Value,
                School = p.Properties.Attribute("School").Value,
                Marks = p.Properties.Attribute("Marks").Value
            });
            return studVMList;
        }
        string IViewModelProvider.ViewName
        {
            get { return "Student"; }
        }
    }
    public class DefaultViewModelProvider : IViewModelProvider
    {
        ViewModelBase IViewModelProvider.GetViewModel(IList<Models.Person> persons)
        {
            DefaultViewModel personVMList = new DefaultViewModel() { };
            personVMList.Persons = persons;
            return personVMList;
        }
        string IViewModelProvider.ViewName
        {
            get { return "Index"; }
        }
    }
/////////////MVC Specific
    public class PersonController : Controller
    {
        public ActionResult List(string personType)
        {
            IEnumerable<Person> persons = DataRepository.GetPersonsByType(personType);
            IViewModelProvider provider = ViewModelProviderFactory.GetProvider(personType);
            ViewModelBase viewModel = provider.GetViewModel(persons.ToList());
            return View(provider.ViewName, viewModel);
        }
    }

Hope this is clear. Sample can be downloaded from the below location.