Security Best Practices to Adopt for ASP.NET Core MVC Web Applications
Table of Contents
ASP.NET MVC is a web application framework developed by Microsoft that works on the model–view–controller (MVC) pattern.
Web developers who create ASP.NET web apps form the largest group of developers in the world after the developers who build PHP-based applications. And when it comes to building high-traffic-based websites, ASP.NET wins the race. According to a survey report by W3Techs, ASP.NET is the second most popular programming language to be adopted after JAVA for web applications with higher traffic rates.
Having stated that, when a web application is prone to severe traffic, advanced security measures must be adopted to ensure its security. Let us look into the different types of security best practices that can be adopted to avoid vulnerabilities in a web application.
1. Cross-Site Scripting (XSS)
It is a type of web application security vulnerability that allows attackers to inject client-side scripts or malicious code into web pages that other users see. It differs from other web attacks, such as SQL injection, which do not directly target web applications. Script injection can be carried out through Form Inputs, URL Query Strings, and HTTP Headers.
Types of Cross-Site Scripting (XSS) attacks
Reflected XSS, DOM-based XSS, and Stored XSS are the three main types of XSS vulnerabilities. The most common sort of XSS vulnerability is reflected XSS. An attacker can inject payloads (also known as metadata) into the victim’s request so that the payload script is included in the request and reflected in the HTTP response.
Document Object Model (DOM) Based XSS is a more advanced sort of XSS attack that occurs when a client script builds DOM using data supplied by the user. In stored XSS, the attacker injects a script that is persistently kept in the victim application. For example, a malicious script can be injected into any input form on a website, such as a comment area, and the victim will see this page differently.
Prevention of Cross-Site Scripting (XSS) attacks
Regular Expression
Regular expressions can be used to validate the user’s form inputs. So, before allowing the user to move further, one can block the harmful letters and symbols and allow only the required characters in the input area. So, such validation (client and server-side both) can prevent the malicious data from harming the website.
Encoding the HTML
HTML encoding can help avoid XSS attacks on websites that accept HTML markup as input. It entails encoding the HTML that is saved. The Razor engine automatically encodes all inputs. Therefore the script component that gets inserted as any field is never run. Furthermore, you can also apply an encoding rule to the variable by using the @ directive.
URL Encoding
In most cases, plain text is used in URL query strings, which can be used to conduct cross-site scripting (XSS) attacks. As a result, the query parameter input in the URL should be encoded. With ASP.net core 2.0 and higher versions, the UrlEncode and UrlDecode methods of Microsoft.AspNetCore. WebUtilities class can be used to encode and decode URLs.
2. SQL Injection
It is the most prevalent attack, in which malicious SQL code is injected into the database and information is obtained by an unauthorized user. For example, through SQL injection, the user receives the information that they do not have the authority to see. In this attack, a hacker constantly attempts to insert SQL statements into the database, causing it to run and retrieve untested data.
Prevention of SQL Injection
Parameterized Query
Instead of using an inline query, one should use a stored procedure. To protect the application from SQL Injection, one must use a parameterized query when using an inline query. The following is an example of a parameterized query.
ORM such as Entity Framework
Usage of ORM or Object-relational mapping maps SQL objects like table view to the domain objects like class. The ORM generates a parameterized query internally to get a record from the database.
Limited Permissions for DB Access
For tables with confidential data, one should limit the DB user permissions. Tables connected to payments and transactions, for example, should have their insert, update, and delete rights restricted, as should tables that store a user’s personal information. If a user exclusively works with select queries, then he should only give permission for the Select statement and not the Insert, Update, or Delete statements.
Data Encryption
It is advisable not to store confidential information such as email addresses and passwords in a database in plain text. It should be kept encrypted at all times.
3. Cross-Site Request Forgery (CSRF)
Another name for it is session riding. Using this method of attack, the attacker copies forging as a reliable source and delivers the data to the website. The website processes this data, assuming it originated from a trustworthy source. This form of attack can destroy client relationships as well as your business. Unauthorized financial transfers, data theft, and other forms of CSRF are instances.
Typically, this is performed by creating a forged website that communicates with the legitimate website internally and then does malicious activities while the user session is still active. For example, a user transfers funds from one account to another, and the user and the bank site have established a secure connection. At the same time, the user clicks on potentially harmful links in junk email (that sent by the attacker). The attacker takes advantage of the secure session between the user and the bank site and executes malicious operations such as financial transfers. However, this is a server (web application) vulnerability rather than an end-user issue.
Prevention of Cross-Site Request Forgery (CSRF)
You can avoid this type of attack by using AntiForgeryToken.
The HTML tag helper asp anti-forgery can be set to true in an HTML attribute. By default, this value is false. An anti-forgery token will be generated if this value is set to true. The [ValidateAntiForgeryToken] element must be added to the form post action method to verify that a legitimate token is generated.
4. Proper Error Handling
It could be a possibility that a web application’s error-handling code is miswritten.
As a result, users may be exposed to sensitive information such as database setup information, table names, stored procedures, data structures, and programming coding structures. An attacker/hacker could use this information to plan an attack on the website.
Prevention
You can avoid such a situation by establishing a custom error page that appears when an error occurs or by writing the code to handle custom errors. In the first solution, one must develop a page with a generic message that must be configured using the startup class’s Configure method.
One can also use custom code to handle exceptions, such as a try-catch block, an exception handler, or an exception filter.
5. Enforcing SSL (Secure Sockets Layer) and using HSTS
SSL establishes a secure connection between a web server and a browser. It guarantees that all data sent between the web server (application) and the browser is encrypted and does not alter during the transfer. One can utilize HTTPS (HyperText Transfer Protocol Secure) to secure the web application. Adopting HTTPS has numerous advantages, including confidence, validated data, data integrity, etc.
One can construct a web application configured over HTTPS using ASP.net Core 2.1 and subsequent versions. Before the.NET core framework 1.1, one could configure HTTPS with ASP.net Core, but it was a bit more complex. When one creates a web application with Visual Studio, he has the option of configuring the web application over HTTPS. HTTPS is enabled for the application in the template of a web application.
HSTS (HTTP Strict Transport Security Protocol) is a web application security strategy that guards against downgrade protocol assaults and cookie hijacking. It makes the web server use an HTTPS connection to communicate. Insecure connections are always rejected. The HSTS middleware is included by default in the Asp.net core template. It is not advisable to use in a development environment because the browser caches the HSTS header.
One can override the following options when configuring HSTS
MaxAge: A period that defines the Strict-Transport-maximum Security’s age. 30 days is the default value.
IncludeSubDomains: The Strict-Transport-Security header will be available for subdomains if this value is set to true.
Preload: The Strict-Transport-Security module now supports preload.
Excluded Hosts: A list of host names for which the HSTS header will not be added.
Another middleware is included in the default template, redirecting requests from non-secure HTTP to secure HTTP. The request is redirected using the default redirect status code (307). You may customize this middleware to meet your needs. You can override the default setting by adding the AddHttpsRedirection method to the starter class’s ConfigureService method. Also, you can set the default redirect status code and the HTTPS port here.
6. XXE (XML External Entities) attack
An XXE (XML External Entity) attack is conceivable on the program that parses XML input. This attack could be because the XML input contains a reference to an external entity that was misconfigured in the XML parser. It could happen as a result of the hacker scanning the port where the application (XML parser) is hosted, the leak of confidential data, SSRF (server-side request forgery), denial of service (Dos), and so on. By injecting entities into entities, a hacker or attacker can use XML to cause a Denial of Service attack. The “Billion Laughs Attack” is this type of attack. As a result, the system required additional resources to accomplish the task, and the server may have crashed owing to excessive utilization.
Prevention of the Attack
To parse XML files with XmlTextReader, one must set the DtdProcessing attribute to Prohibit or Ignore.
If it is set to Prohibit, an exception will be thrown if a DTD (Document Type Definition) is found.
If it’s set to Ignore, all DTD specifications in the document will be disregarded, and the document will continue to be processed.
It will parse any DTD requirements in the document if one sets it to Parse. By default, DtdProcessing is set to Parse. It has the potential to be susceptible.
7. Improper Authentication and Session Management
The authentication module is present in most web applications, and we should be cautious when building code. One may make errors such as failing to remove authentication cookies after successful logout. As a result of this error, attackers may be able to steal user credentials such as cookies and session settings, allowing them to access the entire program and cause significant harm.
The following errors can aid data theft by attackers:
The connection is not secure (without SSL).
Predictable login credentials.
Keeping raw (non-encrypted) credentials on the server.
Logging out of applications incorrectly.
Prevention
- After you’ve successfully logged out, delete your cookies.
- SSL is used to protect cookies and sessions.
- Set HTTP only to secure cookies.
8. Version Disclosure
The request and response objects contain various data, including the request method, remote address, and server X-Powered-By, among other things. Some of them, such as X-Powered-By and Server, are extremely sensitive. They must not reveal this information to the end-user since the attacker may use it to launch an attack. It’s probable that some framework versions will include security flaws and that an attacker will use them to break the system.
One can get information such as a server, X-Powered-By, and X-source files from the Header. The Server property indicates which server is used to host the application, the X-Powered-By indicates the information about the framework, and X-Source Files is only available in debugging modules in IIS / IIS express.
Solution
The solution is to remove headers that contain sensitive information. One can remove the server header by setting up AddServerHeader to false where we configure the server. We can remove the X-Powered-By header either by using web.config or from the IIS setting.
Conclusion
The above article has been put together to highlight the best practices for securing ASP.NET Core MVC web applications.
Stay updated on the latest innovation and everything tech- from emerging technologies to old transformations with Capital Numbers. We are a full-service Software Solutions Company in India offering dedicated resources across the globe