Razor – Suraj | Coding Passion Tue, 09 Oct 2018 07:03:49 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 Validation & Security in MVC application /validation-security-in-mvc-application/ /validation-security-in-mvc-application/#respond Sun, 06 Sep 2015 16:32:15 +0000 /?p=407 Introduction

Validations in any application is so critical now a days that developers ought to be on their toes while developing any such critical and sensitive applications. Hackers are now in every corner of the society, avoid them restrict them to post non sense data into your applications. The attacks are so vulnerable that security guard of any application is mandatory.
security1
The security checks and implementations should be alert and active in the application to counter the attacks. Lets start learning about different types of validations we can have in our MVC application.

Server-Side Validation

Lets begin with simple server side validations. Server side validation are required when we post something to the server with an expectation for the response,usually while posting form data. The form data post is generally very vulnerable. The attacks are quite easier for the attacker here. Thus, we need to check on the server if we are receiving valid data or not on our end. Thus, server side validation can to some extent prevent nonsense input data. Lets discuss how to do validation explicitly using view model. Lets discuss how:
Explicitly means, we would be checking on server side after form post by the user, if the data input are valid input or not, then we post back the user with the validation message as response.
Suppose we have a model for the Registration of a user to an application. The model goesas below:

public class RegistrationViewModel(){
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string TelNo { get; set; }
}

Thus in the view/UI user will be displayed with the above labels and respective text boxes for input. The razor engine view page in the application looks like:

@model ServerSideValidationDemo.Models.RegistrationViewModel
@{
 ViewBag.Title = "Registration Page";
}

@using (Html.BeginForm())
{

    • @Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName, new { maxlength = 50 }) @Html.ValidationMessageFor(m => m.FirstName)
  • @Html.LabelFor(m => m.LastName) @Html.PasswordFor(m => m.LastName, new { maxlength = 50 }) @Html.ValidationMessageFor(m => m.LastName)

 

  • @Html.LabelFor(m => m.Address1) @Html.PasswordFor(m => m.Address1, new { maxlength = 50}) @Html.ValidationMessageFor(m => m.Address1)

 

  • @Html.LabelFor(m => m.Address2) @Html.TextAreaFor(m => m.Address2, new { maxlength = 200 }) @Html.ValidationMessageFor(m => m.Address2)

 

  • @Html.LabelFor(m => m.TelNo) @Html.TextBoxFor(m => m.MobileNo, new { maxlength = 10 }) @Html.ValidationMessageFor(m => m.MobileNo)

 

 

}

Thus, the above snippet would bring the user the UI where the users would post their input and click submit. In the razor view page, you can see the HTML Helper ValidationMessageFor. This helper displays the Validation message returned after validation from the server as response, at the respective model property. Like for example, we want the user to enter the Model property First name as mandatory, then after validation the helper would display the validation message beside the First Name Text Box.
Now lets have a look at the Action snippet to which the post would call after Submit click.

[HttpPost]
public ActionResult UserRegistration(RegistrationViewModel registerModel){
     if (string.IsNullOrEmpty(registerModel.FirstName))
         {
             ModelState.AddModelError("FirstName", "Please enter your first name");
         }
     if (!string.IsNullOrEmpty(registerModel.TelNo))
         { 
             Regex telNoRegex= new Regex("^9\d{9}$");
             if (!telNoRegex.IsMatch(registerModel.TelNo))
             ModelState.AddModelError("TelNo", "Please enter correct format of Telephone Number");
         }
     if(ModelState.IsValid){
         return View("Sucess");  //Returns user to success page
         }
      else {
         return View();  //Returns user to the same page back again
        }
 }

Before explaining the above snippet, lets understand how this will be called after Submit click.
@using (Html.BeginForm()), this does the trick even without specifying the Action and controller. This actually internally calls the Post method of the current url, i.e. looks for the HttpPost attribute to the respective action name of the current url. Thus, in this way the post method of UserRegistration gets called and this also post the required view model to the action, fetching the values input by the user.
After the Action Result method gets called, there is check for the properties explicitly. Here, we check if the user has input into the First name or not. If the user skipd the First Name textbox and submits, then we post the user with the validation message saying “Please enter the first name”. This validation check will not let the user post the input, unless he adds the first name. Similarly, the telephone number is also validated with the regular expression(for the indian telephone number) given.
This was all about the validation being done explicitly.
Now, since we are developing an MVC application, it provides pre defined attributes which can be used to validate our post data. The attributes are called Data-Annotations attribute. Lets look at their usages below:
The use of data annotations can be extensively done in order to avoid heavying the controller post action,explicitly checking for each property. The data annotations attribute in a view model would look like below:

public class RegistrationViewModel(){
    [Required]
    [Display(Name = "First name")]
    [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    [Required(ErrorMessage = "Please Enter Telephone Number")]
    [Display(Name = "Tele Phone")]
    [RegularExpression(""^9\d{9}$"", ErrorMessage = "Please Enter Correct format of Telephone No.")]
    public string TelNo { get; set; }
}

The view model above uses Data Annotations attributes and all the required validations for the properties are provided. Lets discuss one by one:

    1. Required:- This attribute forces the user to enter the value for that specific property and then submit the form, else diplays “The FirstName is required.”. Mark here, the previous message would be a default error message where as for the Tele phone number, the custom error message would be displayed.
    2. Display(Name = ):- This attribute sets the label for the model property. We just need to specify
      @Html.LabelFor(m=>m.TeleNo). This would display the specified custom label for the property, here it would display Tele Phone
    3. RegularExpression:- This attribute is very handy specially when we have properties like Email Address, Tele Phone Numbers and specific expressions for passwords in the forms. We just specify the expression in the attribute and it validates the input from user and states if it is valid or else displays the error message.

Thus, here the view page would go like the same as above. And when we submit, the action post method called would be different i.e. much less code. Lets have a look at the action below:-

[HttpPost]
 public ActionResult UserRegistration(RegistrationViewModel registerModel){
    if (ModelState.IsValid)
      {
         return View("Success");//Return to the success 
      }
    else
      {
         return View();//Return back to the same view 
      }
 }

Thus, the data annotations here made it so simple and easy.
Here then comes another security vulnerability, i.e. Cross-Site Request Forgery Attacks, which can be easily attacked using the simple Fiddler. When we post any data, we can easily manipulate the data posted by one user using the fiddler and damp into the application and even ruin it. This is indeed very dangerous. Lets see how to prevent Cross site forgery attacks

Preventing Cross Site forgery Attacks

In MVC applications, while posting the form data, it is quite simple to prevent such request if understood properly. MVC provides the attribute [ValidatAntiForgeryToken] on the respective action. Lets see the flow in the snippet first.
First we need to place the AntiForgeryToken helper in the razor view page like:

@using(Html.Form("UserRegistration", "Register")) { 
    @Html.AntiForgeryToken() 
    //Then here normal rest form as mentioned above    
 }

Then in the controller “Register” for the action “UserRegistration”(POST) add the attribute like below:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UserRegistration(RegistrationViewModel registerModel){
   //ModeState Valid check and rest code goes here
}

Ok, so we have seen what two simple steps we need to do. Now lets understand how it does. What happens exactly when we do not place these attributes. How vulnerable our controller is and to what extent an attacker can affect the application. Suppose we are on an Edit page, where a user soughts to edit few of his login information. Now an attacker from over a third party domain and host a simple HTML that would post some information to the same Edit action, the user were to. Then, some how the user if navigates to the Html page set up by the attacker, the user unknowingly is posting unwanted data to the server and normal saving to the database. Here the attacker may be replacing the email ids or any other vulnerable information to his own and retrieving the user’s data. BOOM! This is crash, rather a crap!
Thus, what we need to do here, we need to check if the request to the server action is coming from the same domain, the user has logged in ! for this we need to have some header or property which will be mapped when a request is made and if matches then post else let the authentication fail.
This is actually what the attribute does. The ValidateAntiForgeryToken actually sets a cookie to the incoming reuest called __RequestVerificationToken, and the same __RequestVerificationToken is set for the domain in which the user is logged in. Thus, when a request is made from the same domain, the request header cookie should match and let the user post the data, but when a request is made from the third party domain, then the request is rejected since the __RequestVerificationToken will never match, just failing the authentication and preventing the Cross Site Forgery by any attacker.
Now here there is another problem. If any how the attacker gets to know the Anti Forgery Token, then what!! again crap! No there is a way out here as well. The attribute has ability to add a unique/different Salt every time so that the same token is not reused everywhere.

@Html.AntiForgeryToken("SALT") //The salt can be any sort of string(homogeneous mixture :))

[ValidateAntiForgeryToken("SALT")]

Another concept that is vulnerable to such attacks and may breach the security in the application is SQL Injection Lets discuss this in brief. 🙂

SQL Injection Attacks & Prevention Techniques

What exactly is SQL Injection attack? thinkzoo
SQL Injection is an attack to fool and manipulate the application database. This is done through the malicious input from the user during post methods and if the posted data is not validated before being executed as sql query. This is really very dangerous which can let attackers get all the sensitive data or even delete the records from all tables, truncating them, just by posting a simple query to drop instead of actual data.
In this, the objective of the attacker is to post their query into the application and let the server run and give him the response if not handled in the server end. Lets see how:
Suppose we have a sql query to select the names of houses and display. The query would be like:

var sqlTobeExecuted = "SELECT HouseID, HouseName"+
    "FROM House " +
    "WHERE Address LIKE '" + searchInputParam +"%';
SqlDataAdapter da = new SqlDataAdapter(sqlTobeExecuted , DbCommand);

The above query is not parameterized and is a simple query in string format to get the house details. Now suppose the attacker posts the searchInputParam (which originally comes from the textbox input of the user) as

‘ UNION SELECT id,name FROM sysobjects;–

Mark the statement what becomes after that is passed to the string query,

SELECT HouseID,HouseName FROM House
WHERE Address LIKE ” UNION SELECT id,name FROM sysobjects;–%’

The first apostrophe in the searchInputParam closes the Like parameter in the SQL query and the double dashes “–” comment out the rest of the query. Thus that gives the list of all the HouseNames and also all the tables present in the database . Even they can also get the ids of the sysObjects and use the Ids to retrieve the column names of the database table they want. Suppose there is a table named Users. Oviously the table would have all the user details. Thus, with the id and the table name the attacker can retrieve the column names of the Users table using the below query:

‘ UNION SELECT name FROM syscolumns WHERE id = “USERID”;–

Thus,the whole of the database can be exposed to malicious users at a single click.
To prevent this,

      • Encrypt the essential and sensitive data like password, credit card info and other details. So that to some extent if by any how they get the details they cannot decrypt it. Use one way hashing to encrypt the record data.
      • Using parameterized queries instead of strings, in order to avoid directly injecting the values from the User input to the query as we saw in the above section. A parameterized query would prevent the malicious input and it would look like below:
        var commandToBeExecuted = "SELECT HouseID, HouseName FROM House"+
            "WHERE Address  Like @Address";
        SqlCommand cmd = new SqlCommand(commandToBeExecuted , conn);
        cmd.Parameters.Add("@Address",address);

        As we see in the above query we avoid passing directly the string input, instead we are using parameters into the SQL query, which would prevent such attacks.
      • use of parameterized Stored Procedures, which also prevent and prove to be a good solution to these mallicious attacks of injection. Also it is advisable to not trust them completely/blindly so it is always better to check for the sensitive data from user inputs and then execute the Stored procedure. This can be done, where the developer can think there are chances of vulnerability.
      • Entity Framework & LINQ, it is interesting to note here is while using LINQ to entity, the query generation does not use the string based approach, rather it uses the object model API, thus being not susceptible to SQL injection attacks.

Authentication & Authorization

These two are very very very…important in any application and these are two different concepts all together but are used to solve the same thing,i.e. Security. When we develop an secure application, the Login is highly essential. Thus, properly authenticating users to the application & authorizing users to particular section of the application is challenging. Usually Forms Authentication is implemented across MVC applications. In the web.config file, the following configuration is set:

Only this will not set the authentication. You need more set up be done. This would involve a lot of configuration. WebSecurity in MVC makes it easy and secure to be implemented. It provides tables and hashing as well. The hashing it provides is one way and very secure. You can learn more about implementing Web Security in MVC from
Web Security In MVC
Thus after setting this authentication, then the important thing is Authorization, which can be provided on controller level, action level, which can be customized in order to check for the access levels along with the sessions. Only Authorize attribute would let the check for the session, we can customized to check for the roles and access levels for the screens as well.

[Authorize]
 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }

In the above snippet, the entire controller has been authorized. That is each method inside the controller will be first authorized.

public class HomeController : Controller
    {
      public ActionResult Index()
        {
            return View();
        }
       [Authorize]
       public ActionResult GetHome(){
         return View()
       }
    }

Here, only the action method GetHome is authorized, not the whole controller.
Thus, Authentication and Authorization are very important factors that ought to be taken into consideration.

More security considerations in MVC

Straight from the OWASP scurity points,
Its advisable to hide the MVC versions as well as Asp.Net versions we use, never expose the versions through the headers.

X-AspNet-Version 4.0.30319
X-AspNetMvc-Version 5.0

We need to hide the versions which appears in the Network tab of the developer table.
Lets know how to remove the versions of Asp.Net and Asp.Net Mvc from the headers.

    • Asp.net Version:-To hide the X version of the Asp.Net we use the below Web.Config change.

      The above will hide the Asp.net versions.
    • Asp.Net MVC Versions:- To hide the X version of the Asp.Net MVC we use the below change in the Application_Start method of the Global.asax. The snippet would go like below:-
      protected void Application_Start()
              {
                  MvcHandler.DisableMvcResponseHeader = true;

      This hides the Asp.Net MVC version from the headers in the Network tab.
    • Lastly, there are chances of exposing the Users to the Yellow screen of death, when an exception occurs in the application and is unhandled. Thus, it is advisable to have a custom error page, where users will be landing when exception occur. Lets see how:
      Custom errors in the Web config needs to be on. There are three modes of the Custom errors. They are:

      1. On:-
        –Prevents the stack trace that is shown when exceptions arise
        –Also allows to display custom error pages to the end user
        –Custom error pages shown to both Remote Clients as well as Local
      2. Off:-
        –Makes the end user view the description of the exception along with the entire stack trace.
        –ASP.NET error/exception and stack trace shown to both Remote clients and Local as well.
      3. Remote only:-
        –This is the best among all for the developers’ perspective, as this allows the Remote clients to view thecustom error messages/pages.
        –Allows the Local users/especially developers to view the ASP.NET errors.
        –This is the default value.

      The other attribute which is used to the custom error element is defaultredirect. This is used to redirect the users to a default page when exceptions occur.

      The exceptions can also be handled globally , application level by using the below snippet:

      protected void Application_Error(Object sender, EventArgs e)
      {
          Exception ex = Server.GetLastError();  //self explanatory gets the most recent error
          Server.ClearError();  //self explanatory clears the error 
              //(Required to clear as otherwise user gets to see the default ASP.NET error handlers)
          Response.Redirect(""); //default redirect. 
      }

      For details you can follow: Custom Errors

      Conclusion

      Thus, security and validations are very important features to be implemented in any application now a days. According to forbes in a day 30,000 sites were hacked. This is truly an astonishing numbers. And in today’s world most of the sensitive information are being stored on cloud. Thus, in any application the data have a great chance of being exposed and hacked. So security is a major concern and needs to be handled very carefully.
      Hopefully, Some of the major points are discussed above and can be implemented in any application to avoid any sort of breaching.

      References

      How can I miss the references from which I learnt and got this opportunity to share with the world.
      OWASP Cheat Sheet
      Security testing
      Sql Injection and Entity Framework

]]>
/validation-security-in-mvc-application/feed/ 0
Using Font Awesome from Nuget /using-font-awesome-from-nuget/ /using-font-awesome-from-nuget/#respond Thu, 19 Feb 2015 19:29:02 +0000 /?p=264 Introduction

Still using images for icons!! Now in every other web site/web pages, we find intensive use of icons to help user navigate and understand easily the whole purpose. Making the icons simple and understandable from user point of view is what the motive stands here. But using images for icons!! would that be fine!!Would not that affect the page performance as the image has some size right readers!!Let me introduce here to you a small package upgraded and light-weight and easy to use which makes the GUI so simple to implement. Lets get started..

Getting Started With Font-awesome

As the name itself suggests, this package is awesome. From a github post,

Font Awesome is a full suite of 519 pictographic icons for easy scalable vector graphics on websites, created and maintained by Dave Gandy.

These are simple text, which can easily be manipulated like normal texts using the fonts. You stretch or enlarge an image(.png) icon it gets blurred, it looks bad in simple language. You enlarge any font from the package of fontawesome it would never get blurred or pixalated. Moreover no width no height is required as used in image as attributes, just increase the font-size, it manipulates the icon.
The best thing is this package can be downloaded from the Nuget Package or the Package manager console too. The below image will show how to install the package from the PM Console.
Capture1
As you can see in the above Image, you need to get to the PM Console window and hit the yellowed Install command.
Install-Package font-awesome -Version 4.1.0
After Installing you may face some error for the assembly package. That is the dependencies on this library and their version may cause some issue here. As for example which I have encountered while adding in my project was the assembly Web.Optimization as this version of this library require varsion 1.1.3. . If any package upgradation/update is required as its dependencies then without any hesitation just update the packages. Infact, the updates for the packages should be checked and updated regularly. After adding the following files/folders get added to the web project.Capture2
When added/installed two css files are added for the font-awesome. To a shock,both the files are same, now wonder why then both??Because a small difference between both matters a lot: .min.css is the minified version of the css file that is small light and good for performance. So, while adding the reference in the layout, minified version is preferred/made mandate actually.
Capture3
The other thing that gets added is shown in the above image.
Lets get some information about the extensions of the files inside the folder. Information are from WIKI:

.eot :- Embedded Open Type fonts are a compact form of OpenType fonts designed by Microsoft for use as embedded fonts on web pages.

.svg :- This is common and known, but still, Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation.

.ttf :- This is developed by Apple, stands for True Type font. This means the font can be scaled to any font size even without tampering the quality.

.woff :- Stands for Web Open Font Format. This is a font format to be used in the pages rendered on web, that is Webpage.

.otf :- Stands for Open Type Font

This was all about the extensions of the files in the folder.

Usage

To use this as I have already mentioned, we need to have the minified version of the .css file in the layout itself, as the icons would be used intensively. The reference goes as below:

<link href="~/Content/font-awesome.min.css" rel="stylesheet" />

Now to use the class out of the .css defined classes, the use is as below:-

<i class="fa fa-2x fa-fw "></i>

As you can see in the above snippet, this is the way fontawesome classes defined in the <em>.css</em> file.

Class fa is defined as below:-

.fa {
  display: inline-block;
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

fa-fw is defined as below:

.fa-fw {
  width: 1.28571429em;
  text-align: center;
}

These are the definition of the classes defined in the css. You think I have missed fa-2x, ok Guys there are fa-1x, fa-3x and more as they represent the font-size simplified as <em>1em, 2em, 3em & similarly..</em>

Then the actual class for the icon is to be used along with these which define its characteristics. The class name is prefixed with “fa-“. The many icons along with the classes that can be used are given in the link/cheatsheet:-Font Awesome Cheatsheet
You find a lots of icons with their class name to be used. Just specify the name as below and see the icon onscreen. Even another fact is we can even change the color of the icon as we want, using the similar color css property.

<i class="fa fa-2x fa-fw fa-adjust"></i>

Conclusion

This is how this awesome Font Awesome can be used so simply in our projects. Thus reducing the time & size for the page being loaded. So start using this beautiful, light-weight and authentic library for the icons to be used.

References

Font Awesome Examples
Wiki
CP

]]>
/using-font-awesome-from-nuget/feed/ 0
Render Sections Magic using Razor View Engine /rendersection-razor/ /rendersection-razor/#respond Wed, 04 Feb 2015 18:02:30 +0000 /?p=223
A small, simple and a handy one..
Recently, I came across the use of RenderSection method & got to learn about this due to a Web.Exception (mentioned below) that was thrown and had blown off my mind.
Render Section!! Lets first know about this gem…
RenderSection() is a method from System.Web.WebPages namespace & the WebPageBaseclass. To be exact RenderSection() method is of two types i.e. same method but with different parameters. They are:-
  1. RenderSection(string):- This method just renders the contents of a named section in the layout Pages, as simple as this could be(the definition 🙂 ).
  2. RenderSection(string, Boolean):- This renders the named section similar to the previous method, but also specifies whether the section is required. This method with an extra parameter does a great bit of work, which we will discuss below.

 

Why is this required by the way!!
As we know something to explain has a better way of understanding if explained through an example. So, lets take one.
  • Suppose we are designing an application that has three pages. The “Home”, “About”, “Topics” pages and oviously all the pages have different content.
  • Now, we have a small sidebar on all the three pages and the content for Home and About pages are same that is the contacts of the Admin, & the Topics page has the contact replaced by a cloud structure displaying all the Tags for the articles/topics.
  • As we would know by now that these three pages will use the same layout and the sidebar would be displayed at the same place for the pages. Here is where the Render Section method comes into play.
  • In the layout.cshtml(C# Razor), wherever we need the sidebar section to be rendered, we write as @RenderSection(“Section Name”).
  • And in the individual pages those use the Layout, we define the section there as , @section “Section Name(remove the quotes)”{…..}. Wherever and whatever the contents might be just define it and render once in the Layout. This simplifies the work of writing the HTML codes and the css also..
This sounds so simple, until you have only three pages. Give a thought, is this possible always!! No. In a web application there might be many pages using The layout. Here is what an important point about Render Section comes, which we should keep in mind before using.
“Every Page that uses the Layout, and the layout.cshtml has a RenderSection(), that page needs to have the section with that name defined”. Else this also throws the user to the yellow screen of death(depending on the Custom Errors mode) or nothing a blank pageas whole parts of a page are not yet rendered. The exact exception is:-
“System.Web.Exception: Section not defined:”SECTION NAME”.”
Just give a thought if there are many pages, where would you search for, where you have missed to define the section. This is not a feasible solution right?
So, it is better to use the second method, i.e. RenderSection(string, Boolean).
If we use the RenderSection(“SECTION NAME”, required:false), what this means is, if a section is required and is not defined in the page and the section is optional in some page, then by the use of this method the RenderSection() method will render nothing and no runtime error would occur.
If we use the RenderSection(“SECTION NAME”, required:true), then we need to define the section in each page as we are prescribing here that section needs to be rendered on each page using the layout. We can also define a blank section to avoid the runtime error.
Using Conditional Detection for presence of a section:-
We can also use another small piece of code to avoid the runtime error and detect that the section is defined or not. Here goes the code:-
@if(IsSectionDefined("SECTION NAME")) {  
@RenderSection("SECTION NAME")  
}  
else {  
.....//Goes on  
}

People rightly say, “Man learns from Mistakes” & as a developer, we should be proud of these mistakes as this helps us learn more & more. 🙂

 Hope this helps some way..
]]>
/rendersection-razor/feed/ 0