Lot of ASP.NET MVC developers are great in delivery , writing high performance code and so on. But when it comes to security there is no planning done. So in this article we will run through 10 points which will help us to make our MVC code secure.
·
Security Misconfiguration (Error Handling Must
Setup Custom Error Page)
- Security Misconfiguration (Error Handling Must Setup Custom Error Page)
- Cross-Site Request Forgery (CSRF)
- Cross-Site Scripting (XSS) attacks
- Malicious File Upload.
- Version Discloser
- SQL Injection Attack.
- Sensitive Data Exposure
- Audit trail
- Broken authentication and session management
- Unvalidated Redirects and Forwards
·
Security Misconfiguration (Error Handling Must
Setup Custom Error Page)
In this kind of attack the attacker intercepts form data which
is submitted by end User and changes values and sends the modified data to the
server.
So for such kind of scenarios developers do put proper
validations in place but when these validations display error lot of
information of the server is revealed.
Solution: -
So the solution here is we need to set some kind of error page which does not show the internal technical error but rather shows a custom error message.
We have two approaches for it :-
- Create a custom Error handling Attribute.
- Setting Custom Error page from Web.config file
Solution 1:-
Create a custom Error handling Attribute using HandleErrorAttribute or using IExceptionFilterFilter
Showing example using HandleErrorAttribute
Hide Copy Code
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Web.Mvc;
namespaceMvcSecurity.Filters
{
publicclassCustomErrorHandler : HandleErrorAttribute
{
publicoverridevoidOnException(ExceptionContextfilterContext)
{
Exception e = filterContext.Exception;
filterContext.ExceptionHandled = true;
var result = newViewResult()
{
ViewName = "Error"
}; ;
result.ViewBag.Error = "Error Occur While Processing Your Request Please Check After Some Time";
filterContext.Result = result;
}
}
After creating custom Error attribute we need to apply this globally for entire application. For doing this we need to call this attribute in FilterConfig class which is in App_Start Folder as show below.
Hide Copy Code
usingMvcSecurity.Filters;
usingSystem.Web;
usingSystem.Web.Mvc;
namespaceMvcSecurity
{
publicclassFilterConfig
{
publicstaticvoidRegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(newCustomErrorHandler());
}
}
}
Whenever error occurs the CustomErrorHandler attribute will get called and it will redirect toError.cshtml page. And any message you want to pass then you can pass through @ViewBag.Errorfrom CustomErrorHandler attribute.
Html Error Page code snippet
Hide Copy Code
@{
Layout = null;
}
<!DOCTYPEhtml>
<html>
<head>
<metaname="viewport"content="width=device-width"/>
<title>Error</title>
</head>
<body>
<hgroup>Error.
@ViewBag.Error
</body> </html>
Error Page View
2) Cross-Site Request Forgery (CSRF)
A CSRF vulnerability allows an attacker to force a validated and logged in user to perform actions without their consent or unknowingly.
Take this simple example.
- User logs in to the bank server.
- Bank authorizes and a secure session is established between user and the bank server.
- The attacker sends an email with a malicious link saying “Earn 100000$ now” to the user.
- User clicks on the malicious link and the site tries transfer money from your account to the attackers account. Because the secure session is established the malicious code can execute successfully.
Microsoft has recognized this threat and for preventing the same we have something called as AntiForgeryToken.
Solution:-
We need to add @Html.AntiForgeryToken()helper in your form inside form tag . And on the Action Method which handles your post ([HttpPost])Request we need to put[ValidateAntiForgeryToken] attribute which will check if the token is valid.
Adding [AntiForgeryToken] helper to View
Fig 13.Adding AntiForgeryToken on View.
Adding [ValidateAntiForgeryToken] Attribute to HttpPost[HttpPost] Method.
Fig 14.Adding ValidateAntiForgeryTokenon [HttpPost] Method (Index).
3) Cross-Site Scripting (XSS) attacks
Cross-site Scripting (XSS) is an attack in which malicious scripts is injected via input fields this attack is most common and allows an attacker to steal credentials and valuable data that can lead to a big security breach.
Fig 17. Cross Site Scripting (XSS).
In this attack attacker visits a website and tries to execute a malicious scripts in form comment box. Now if website has not checked for Malicious code then the code can get executed on the server causing damage.
Lets try to understand the same using a example.Below is simple Employee form which we are trying to save data. Now in the text box I am trying to execute some malicious code using javascript using the SCRIPT tag. But if we try to submit the same MVC throws an error that something bad is happening.
In short by default ASP.NET prevents Cross Site Script attack.
Understanding the Error Displayed
A potentially dangerous Request.Form value was detected from the client (worktype="<script>alert('hi');")
.
This error occurs because MVC is validating data which is entered by User and if User tried to execute such script it does not allow and that’s a good news.
Fig 18.SubmittingMaliciousscripts in Input fields which lead to Error.
But now what if we want to put SCRIPT tag. For example programming sites like codeproject has a genuine need that end user should submit code and script snippets. In those scenarios we would like the end user to post code through the UI.
So lets us understand how to do the same but at the same time not compromise on security.
So we have four things via which we can allow scripts to be posted.
Solution: -
- [ValidateInput(false)]
- [AllowHtml]
- [RegularExpressionAttribute]
- AntiXSS Library
-
Solution 1:-
ValidateInput
[ValidateInput] is an attribute which can be applied on Controller or Action Method on which we want the script to go through.
If we want Mark up to be allowed then we need to set enableValidation Properties to False([ValidateInput(false)]) which will not validate input if we set to true then[ValidateInput(true)]) It will validate input.In the same way, if you apply it on Controller then it appliesto entire action methods inside thecontroller and if you apply it on Action Method then it will only be specific to that action method.
But ValidateInputattributewill apply to all properties of Model (EmployeeDetails).
Snapshot of Applying ValidateInputAttributeon HttpPostMethod.
Fig 19.Applying ValidateInput Attribute on HttpPost Method.
Snapshot after Applying ValidateInputAttribute
Fig 20.After adding ValidateInput Attributeon HttpPost Method it allows submitting script.
"<script>alert('hi');")
.
Solution 1:-
ValidateInput
[ValidateInput] is an attribute which can be applied on Controller or Action Method on which we want the script to go through.
If we want Mark up to be allowed then we need to set enableValidation Properties to False([ValidateInput(false)]) which will not validate input if we set to true then[ValidateInput(true)]) It will validate input.In the same way, if you apply it on Controller then it appliesto entire action methods inside thecontroller and if you apply it on Action Method then it will only be specific to that action method.
But ValidateInputattributewill apply to all properties of Model (EmployeeDetails).
Snapshot of Applying ValidateInputAttributeon HttpPostMethod.
Fig 19.Applying ValidateInput Attribute on HttpPost Method.
Snapshot after Applying ValidateInputAttribute
Fig 20.After adding ValidateInput Attributeon HttpPost Method it allows submitting script.
Malicious File Upload.
Till now we have learned how to protect all your input fields from attack but still, we are missing one main field it is File upload control we need to protect from taking invalid input most attackers try to upload a malicious file which may cause a security issue. The attacker can change file extension [tuto.exe to tuto.jpeg] and the malicious script can be uploaded as an image file. The Most of the developer just look on the file extension of the file and save in folder or database but file extension is valid not file it may have a malicious script.
Fig 29.This image shows how people try to upload files some try valid files and some invalid files.
Solution:-
- First thing we need to do is validate file uploads
- Allow only access to files extension which are required
- Check the file header.
Till now we have learned how to protect all your input fields from attack but still, we are missing one main field it is File upload control we need to protect from taking invalid input most attackers try to upload a malicious file which may cause a security issue. The attacker can change file extension [tuto.exe to tuto.jpeg] and the malicious script can be uploaded as an image file. The Most of the developer just look on the file extension of the file and save in folder or database but file extension is valid not file it may have a malicious script.
Fig 29.This image shows how people try to upload files some try valid files and some invalid files.
Solution:-
- First thing we need to do is validate file uploads
- Allow only access to files extension which are required
- Check the file header.
SQL Injection Attack.
SQL Injection attack is one of the most dangerousattacks it is ranked 1 in top 10 Vulnerabilitiesby OWASP2013 [Open Web Application Security Project] . SQL injection attack can give valuable data to theattacker that can lead to abig security breach and can also take full access to thedatabase server.
In SQL Injection attacker always try to enter malicious SQL statement which will get executed in thedatabase and return unwanted data to the attacker.
Fig 46.Sql injection attack example which shows how attack mostly occurs if you are using inline queries.
Simple View which shows User data
View Shows Single Employee data based on EmployeeID as displayed in below Snapshot.
Fig 47.Employee View which displays user data.
Simple View which shows All User data after SQL Injectionattack
In this Browser View as attacker saw Application URL which contains some valuable data which is ID [http://localhost:3837/EmployeeList/index?Id=2] attacker triesSQL Injectionattack as shown below.
Fig 48.Employee View which displays all User data after SQL injection.
After trying permutation & combination of SQL injection attack , theattackergets access to all User data.
Displaying SQL injection in Debug Mode
Here we can see in details how attacker passed maliciousSQL statement which gets executed in thedatabase.
Fig 49.Debug mode View of index Action Method.
SQL Profiler View of SQL statement
Fig 50.SQL Profiler View.
Solution:-
- Validate inputs
- Use of low-privileged database logins
- Use Parameterized queries
- Use ORM (e.g. Dapper , Entity framework )
- 5) Use Stored Procedures
SQL Injection attack is one of the most dangerousattacks it is ranked 1 in top 10 Vulnerabilitiesby OWASP2013 [Open Web Application Security Project] . SQL injection attack can give valuable data to theattacker that can lead to abig security breach and can also take full access to thedatabase server.
In SQL Injection attacker always try to enter malicious SQL statement which will get executed in thedatabase and return unwanted data to the attacker.
Fig 46.Sql injection attack example which shows how attack mostly occurs if you are using inline queries.
Simple View which shows User data
View Shows Single Employee data based on EmployeeID as displayed in below Snapshot.
Fig 47.Employee View which displays user data.
Simple View which shows All User data after SQL Injectionattack
In this Browser View as attacker saw Application URL which contains some valuable data which is ID [http://localhost:3837/EmployeeList/index?Id=2] attacker triesSQL Injectionattack as shown below.
Fig 48.Employee View which displays all User data after SQL injection.
After trying permutation & combination of SQL injection attack , theattackergets access to all User data.
Displaying SQL injection in Debug Mode
Here we can see in details how attacker passed maliciousSQL statement which gets executed in thedatabase.
Fig 49.Debug mode View of index Action Method.
SQL Profiler View of SQL statement
Fig 50.SQL Profiler View.
Solution:-
- Validate inputs
- Use of low-privileged database logins
- Use Parameterized queries
- Use ORM (e.g. Dapper , Entity framework )
- 5) Use Stored Procedures
Sensitive Data Exposure
All Website and Application always have database in which entire data is been stored .mean while we store Users personal information (which may contains Password , PAN number , Passport details ,Credit Card Numbers) in this we mostly encryptonly password right other data are stored in clear text which can lead to Sensitive Data Exposurewhenever an attacker attack he gets access to database if he finds the table where all this personal and financial details stored steal that information .
Fig 77.Sensitive Data Exposure.
3) Do not store Sensitive data in Database in a clear form
Always Try not to store Credit Card, Debit Card and financial details and other Sensitive details in thedatabasein Clear form . Always Use Strong Hashing techniques to encrypted data and then store in thedatabase. if anattacker gets direct access to thedatabase then all data in clear form can be Breached.
Below is alist of Algorithm which can be Used according to need.
Hash Algorithm
if someonewantsjust Hash then they can use Hash Algorithmwe mostly use Hash function for Encrypting Password.
SymmetricAlgorithm
If someonewants just one key for encryption and decryption then they can useSymmetricAlgorithm.
AsymmetricAlgorithm
If someonewants just one key for encryption (Public key) and another keydecryption (Private key) then they can useAsymmetricAlgorithm. E.g we can usethis when we are sharing Web Services and WebAPI with clients when theuser.
HashAlgorithm
- MD5
- SHA256
- SHA384
- SHA512
All Website and Application always have database in which entire data is been stored .mean while we store Users personal information (which may contains Password , PAN number , Passport details ,Credit Card Numbers) in this we mostly encryptonly password right other data are stored in clear text which can lead to Sensitive Data Exposurewhenever an attacker attack he gets access to database if he finds the table where all this personal and financial details stored steal that information .
Fig 77.Sensitive Data Exposure.
3) Do not store Sensitive data in Database in a clear form
Always Try not to store Credit Card, Debit Card and financial details and other Sensitive details in thedatabasein Clear form . Always Use Strong Hashing techniques to encrypted data and then store in thedatabase. if anattacker gets direct access to thedatabase then all data in clear form can be Breached.
Below is alist of Algorithm which can be Used according to need.
Hash Algorithm
if someonewantsjust Hash then they can use Hash Algorithmwe mostly use Hash function for Encrypting Password.
SymmetricAlgorithm
If someonewants just one key for encryption and decryption then they can useSymmetricAlgorithm.
AsymmetricAlgorithm
If someonewants just one key for encryption (Public key) and another keydecryption (Private key) then they can useAsymmetricAlgorithm. E.g we can usethis when we are sharing Web Services and WebAPI with clients when theuser.
HashAlgorithm
- MD5
- SHA256
- SHA384
- SHA512
Audit trail
Audit Trail in IT World is used to keep track of User activity on aWebapplication which he using , it is where important in detecting security problems, performance problems, and ApplicationsLevel Error problems. It also helps us to easily track where theproblemactually is and resolve it.
Audit Trail in IT World is used to keep track of User activity on aWebapplication which he using , it is where important in detecting security problems, performance problems, and ApplicationsLevel Error problems. It also helps us to easily track where theproblemactually is and resolve it.
Unvalidated Redirects and Forwards
In all web application, we do redirect from one page to another page and sometimes we redirect to another application too but while redirect we won't validate URL which we are going redirect which causesUnvalidated Redirects and Forwards Attack.
This attack mostly uses to phish User to get Valuable details (User Credentials) or to install maliciousmalware to the User computer.
In all web application, we do redirect from one page to another page and sometimes we redirect to another application too but while redirect we won't validate URL which we are going redirect which causesUnvalidated Redirects and Forwards Attack.
This attack mostly uses to phish User to get Valuable details (User Credentials) or to install maliciousmalware to the User computer.
No comments:
Post a Comment