Securing Your ASP.NET Web Applications

Introduction

Web application security is not just about attackers hacking websites, stealing sensitive information from websites, sending high traffic to websites with denial of service attacks, viruses, worms and Trojan horses. Are these are the only problems that we have? The answer is no. There are other problems that are frequently overlooked.

The objective of this article is to give you an insight on various areas that a design architect should focus on while designing a web application to make more secured. This article discusses almost all types of vulnerability that can be exploited by the hacker and the counter measure to avoid the same.

Effective way of analyzing the various security issues on a web application by decomposing the problem domain into various areas of focus. I have discussed the same in detail below. If you follow this approach, you get your focus on the key design and implementation choices that affect your application's security.

Input validation

Identifying the validation needs for type, length, format or range of input data avoids hacker discovering the vulnerability in your application. An attacker can compromise your application if any such vulnerability is identified. It is a must to validate the input before processing it by your application. So, how do you know that your application is safe enough? You just need to answer whether your application trusts the input blindly. If the answer is yes, may be your application is susceptible for following threats.

  • Buffer Overflow
  • Cross-site scripting
  • SQL injection
  • Canonicalization

Buffer Overflow

This vulnerability leads to denial of service attacks and it eventually leads to process crash. Another vulnerability of buffer overflow is code injection which eventually alters the program execution address to run an attacker's injected code. The following piece of code demonstrates the example for occurrence of buffer overflow.

// Vulnerable function
void vulnerable(char *str)
{
char buffer[10];
strcpy(buffer, str);
// overrun buffer !!!
}
int main()
{
// declare buffer that is bigger than expected
char large_buffer[] = "This string is longer than 10 characters!!!";
vulnerable(large_buffer);

Managed .NET code is not susceptible to this problem because array bounds are automatically checked whenever an array is accessed. It is still a concern, however, especially where managed code calls unmanaged APIs or COM objects.

Countermeasures to prevent buffer overflows

  • Perform thorough input validation
  • Wherever possible, limit application's use of unmanaged code
  • If unmanaged API is called in your application, check the values passed for the parameters of unmanaged API to avoid this attack
  • Compile your code with /GS flag if it is developed in Microsoft Visual C++ system. The /GS option detects some buffer overruns, which overwrite the return address - a common technique for exploiting code that does not enforce buffer size restrictions. This is achieved by injecting security checks into the compiled code.

Cross-site scripting

It is commonly referred as XSS occurs when a web application gathers malicious data from a user. Often attackers will inject JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable application to fool a user in order to gather data from them.

Because the script code is downloaded by the browser from a trusted site, the browser has no way of knowing that the code is not legitimate. Internet Explorer security zones provide no defense. Since the attacker's code has access to the cookies associated with the trusted site and are stored on the user's local computer, a user's authentication cookies are typically the target of attack.

Attacker normally exploits this by identifying the vulnerable page that outputs the unvalidated input back to the browser. The following snippet of code shows the input that is accepted a vulnerable page that exploits this vulnerability

http://www.yourapplicationname.com/home.aspx?name=<script>alert('Your page is hacked')</script>

When this link is clicked, it will show an alert message because of the script tag embedded in the url. The legitimate url is suppose to carry the original user name which can be exploited as above

Counter measure to prevent XSS

  • Perform thorough input validation on form fields, query strings, cookies. Always check for scripting tags and filter the same. Regular expression is the best way of validating input
  • User inputs should be encoded using HTMLEncode and URLEncode functions

SQL Injection

Using this attack, the attacker can run the code of his choice in the database. The same will be achieved by exploiting the unvalidated input. Typical scenarios where this could be exploited are application that constructs dynamic SQL statements based on the user input and application that executes stored procedure with arguments based on the user input. The attacker can go to a maximum extent of running operating system commands if the account under which the SQL statements executed were over privileged. The extent to which the data being destroyed, manipulated and retrieved is based on the privilege of the account under which the SQL command is being executed.

Following snippet of code shows how this vulnerability can be exploited.
SqlDataAdapter myCommand = new SqlDataAdapter("select * from tablename where fieldname = '" + userinput + "'", myConnection);
The above code gets executed based on the user input. This code can be exploited if the input is entered/passed as value'; Any valid SQL command

Counter measures to prevent SQL Injection

  • Validate the input received by the application using regular expression
  • Set appropriate privileges to execute the SQL commands
  • Stored procedures executed using arguments should be parameterized stored procedures

Canonicalization

When the different forms of input accepted resolves a standard name otherwise called canonical name, it is referred to as canonicalization. The application code is susceptible to canonicalization related issues when it makes a security decision based on the name of a resource that has been received as input. Files, paths and URLs are susceptible for this vulnerability.

A single file can be represented in many different ways as shown below
C:\myfolder\filename.zip
Filename.zip
..\filename.zip

Countermeasures to prevent this vulnerability

  • Avoid accepting file name as input. When there is a need for accepting input to grant access, convert the name to canonical form prior providing security decisions
  • Assure well formed filenames are received and check whether they are within your application's directory hierarchy
  • Ensure that the character encoding is set correctly to limit how input can be represented. Check that your application's Web.config has set the requestEncoding and responseEncoding attributes on the <globalization> element.

Authentication

Authentication is the act of validating the user to whom s/he claims to be. .NET framework has provided several authentication mechanisms that user can choose upon and implement in the application. An attacker can find a vulnerability if they are not properly implemented. Following are the possible vulenerabilities that an attacker can find in improper implementation

  • Network eavesdropping
  • Brute force attacks
  • Dictionary attacks
  • Cookie replay attacks
  • Credential theft

Network eavesdropping

This can be exploited only when passwords are passed in plain text format from client to server. This is accomplished by using network monitoring software that can capture traffic leading to host which is on the same network.

Countermeasure to prevent eavesdropping

  • Use Kerberos authentication or Windows authentication which doesn't transmit the password over the network
  • When there is a necessity for transmitting password through network, use an encryption communication channel like SSL which will encrypt the contents passed through network channel

Brute force attacks

Hacking the sensitive data like password or other such secrets by relying upon the computational power to identify the hash string and encryption technique used for securing the sensitive information.

Countermeasure to prevent Brute force attacks

  • The only way is by using a very strong hash key strings

Dictionary attacks

Typically, sensitive information like password will not be stored in plain text format or encrypted form in the application. Rather the application normally uses a hashing technique and stores the hashed strings. If an attacker gains the access to hash strings stored in the application, a dictionary attack can be performed. That is, iterate through all the words in a dictionary of all possible languages to arrive to the hashed string retrieved by the attacker.

Countermeasure to prevent dictionary attacks

  • Use strong passwords with that are complex. Use mixture of uppercase, lowercase, numerals, special characters in the password that makes difficult to crack.
  • Store non-reversible password hashes in the user store. Also combine a salt value (a cryptographically strong random number) with the password hash.

Cookie replay attacks

The attacker can read authentication information that is submitted for the application to gain access. The attacker can then replay the same information to the application causing cookie replay attacks

Countermeasure to prevent cookie replay attacks

  • Use SSL that encrypts al the information including cookie information passed through the channel
  • Always use timeout property for the cookie information. This will reduce the probability of attack.

Credentials theft

If your application implements its own user store containing user account names and passwords, compare its security to the credential stores provided by the platform, for example, a Microsoft Active Directory directory service or Security Accounts Manager (SAM) user store. Browser history and cache also store user login information for future use. If the terminal is accessed by someone other than the user who logged on, and the same page is hit, the saved login will be available

Countermeasures to prevent credential theft

  • Use and enforce strong passwords
  • Store password verifiers with one way hash with added salt
  • Enforce account lockout for end-users after a set number of retry attempts
  • Set the expiry property for the content rendered in the browser or force the browser not to cache the information

Authorization

Authorization is all about granting or denying access to the resource for which access is requested by the user. It will be accomplished based on user identity and role membership. Top threats that exploit authorization are

  • Elevation of privilege
  • Disclosure of confidential data
  • Data tampering
  • Luring attacks

Elevation of privilege

An attacker trying to elevate privileges to become a member of the local administrator group or local system account by calling the RevertToSelf API referred as Elevation of privilege. This will enable the attacker to take complete control over application and local machine.

Counter measure to prevent elevation of privilege

  • While designing the system, ensure that application gains access only to least privileged process, services and user accounts.

Disclosure of confidential data

Unauthorized users gaining access to sensitive data is referred as disclosure of confidential data. Confidential information should be secured in persistent store like databases, xml files and other configuration files. Care should be taken while transmitting the information through the network. Access to system level configuration data should be restricted to administrators

Counter measure to prevent disclosure of confidential data

  • Before providing access to sensitive data perform a role check
  • Always secure windows resources using strong Access Control Lists (ACL)
  • Persistent stores like database and configuration files should store the sensitive information in the encrypted form

Data tampering

Data tampering refers to unauthorized modification of data. An attacker, who gains access to the information transmitted through the network, can modify the information and the application while receiving will get the tampered data.

Countermeasures to prevent data tampering

  • Always secure windows resources using strong Access Control Lists (ACL)
  • Use role-based security to differentiate between users who can view data and users who can modify data.

Luring Attacks

A luring attack occurs when an entity with few privileges is able to have an entity with more privileges perform an action on its behalf.

Countermeasures to prevent luring attacks

  • Restrict access to trusted code with appropriate authorization. Code access security (CAS) of .NET framework can be used whenever a request is made to secure resources

Configuration management

Many applications provide configuration management interfaces and functionality to allow operators and administrators to change configuration parameters, update web site content, and to perform routine maintenance. If these interfaces were carefully not designed, it could lead following threats

  • Unauthorized access to administration interfaces
  • Unauthorized access to configuration stores
  • Retrieval of plain text configuration secrets
  • Lack of individual accountability
  • Over-privileged process and service accounts

Unauthorized access to administration interfaces

Most of the web applications provide interfaces to administrators, operators and content developers to manage site content and configuration. It should be available only to the restricted users. An attacker who gains access to the configuration management data can bring down the system by altering the configuration data.

Countermeasures to prevent unauthorized access to administrative interfaces

  • Minimize the number of administration interfaces
  • Use strong authentication like using digital certificates or multiple gatekeepers
  • Avoid remote administration interfaces. If it is a must, provide access through VPN or through SSL.

Unauthorized access to configuration stores

Because of the sensitive nature of the data maintained in configuration stores, you should ensure that the stores are adequately secured.

Countermeasures to prevent unauthorized access to configuration stores

  • Configure restricted ACLs on text based configuration files. For e.g. Machine.config and web.config should be configured for restricted access
  • Keep custom configuration files outside the directory that doesn't have web access

Retrieval of plain text configuration secrets

Configuration files such as web.config that stores password or connection string should not store the details in plain text format. External attackers who gains access can then see the sensitive information as it is stored in plain text format. Similarly, disgusted employees and administrators can misuse this sensitive information.

Countermeasure to prevent retrieval of plain text configuration secrets

  • Rather than storing the data in plain text format, store the sensitive information n encrypted formats.

Lack of individual Accountability

It is important to log when the changes were made and who made those changes. If not, it could lead us to a threat of not being able to track the changes made by whom and when. If a malicious change is encountered or any other breaking change is made in the application, corrective action can be taken immediately provided we could identify it from the log.

Countermeasures to prevent Lack of Individual Accountability

  • Administrative accounts must not be shared
  • While using user/application/service accounts, ensure that any damage to the privileges using this account can be identified
  • Apply preventive measures for all the possible violation that you foresee

Over-privileged process and service accounts

There might be a need for an application or service account to change the configuration information on the system. An attacker can take advantage of the same to modify configuration information.

Countermeasures to prevent over-privileged process and service accounts

  • Avoid providing rights to change the configuration information unless it is mandatory. In that case, enable auditing and logging to track each and every change made by the account.

Sensitive Data

Sensitive data is always at great risk as attackers try to view or modify sensitive information from the persistent data storage and networks. It is subjected to variety of threats by the attackers. Often, they are

  • Access to sensitive data in storage
  • Network eavesdropping
  • Data tampering

Access to sensitive data in storage

When the data is stored in a persistent data stores, action should be taken to prevent the attacker from gaining access to the data store. That is the attacker should not be able to either view or modify the information.

Countermeasures to protect access to sensitive data in storage

  • Use Access Control Lists to ensure that required users alone are provided with rights to view or modify the information stored in data storage
  • Always store the sensitive data in encrypted format. Never store it in a plain text format
  • Differentiate view and modify operations separately and provide access accordingly. Use identity and role based authorization to achieve the same.

Network Eavesdropping

In a web application, an http requests and responses travel through the network is sent in a plain text format. An attacker can use network monitoring tool to capture the information sent in the network and can even modify the information sent in the network

Countermeasures to prevent network eavesdropping

  • Use encryption for sensitive data so that it will not be sent in a plain text format when it is transmitted through the network
  • If required, consider encrypting the communication channel by implementing SSL

Data tampering

Data tampering refers to unauthorized modification of data. When sensitive data is passed in plain text format through the network, information can be modified resulting in tampered information reaching the destination.

Countermeasure to prevent Data tampering

  • Use tamper resistant protocols such as hashed message authentication codes.

Session Management

Sometimes application stores sensitive information in the session objects. Session objects should be managed by application layer. However, storing sensitive information in the session objects leads to potential threats. They include

  • Session Hijacking
  • Session Replay
  • Man in the middle

Session Hijacking

In most of the applications, the authentication is stored in a cookie for a particular user's session. An attacker can use a network monitoring tool to capture this information. Having captured the authentication token, an attacker can spoof the user's session and gain access to the system. An attacker can perform all the operations as that of legitimate user.

Countermeasures to prevent session hijacking

  • Avoid storing anything in the session objects. However, if the application demands that then use the following prevention technique
  • Implement SSL as it will encrypt all the information that is transmitted via the network. In that case, the authentication token stored in the cookie too will be encrypted and sent via the communication channel.
  • Allow only one session per user at a time. If a new session is started for the same user, implement logout functionality.
  • Incase if SSL is not implemented and still there is a need to store information in the session object, ensure you set a time period for expiry. Though it doesn't prevent the user from session hijacking, it reduces the risk of attack when the user is attempting for stealing cookie information.

Session Replay

If an attacker gains access to the authentication token stored in a cookie, then the attacker can then frame a requests with the authentication cookie received from another user to the application from which the authentication cookie is sent. An attacker gets access to the system as that of legitimate user.

Countermeasures to prevent session replay

  • Do not store authentication information on the client
  • Whenever a critical function is being called or an operation is performed, re-authenticate the user
  • Set expiry date for all cookies

Man in the middle attacks

When communication happens between sender and receiver, an attacker can come in the middle and intercept all the messages transmitted between the sender and receiver. An attacker can then change the information and send it to receiver. Both sender and receiver will be communicating with each other without the knowledge of a man in the middle who intercepts and modifies the information.

Countermeasures to prevent man in the middle attacks

  • Use strong encryption. When the data is sent in a encrypted format, even though the man in the middle gains access to the information, s/he will not be able to intercept the original message as it is encrypted
  • Use Hashing. When attacker tries to modify the hashed information, recalculation of hash will not be successful and hence it can be discovered that the information is modified in the middle.

Cryptography

Applications use cryptography to store sensitive information and transmit sensitive information across the network. However, if an attacker gains access to encrypted information, attacker should not be able to decrypt to the original information. When encryption information, common threats that it can lead to are

  • Poor key generation or key management
  • Weak or custom encryption

Poor key generation or key management

An attacker can decrypt to original information, if they get access to either encryption key or they can intercept or arrive to encryption key from the encrypted information. Attacker can identify this key only if they are poorly managed or they were not generated in a random fashion.

Countermeasures

  • Use built-in encryption routines that include secure key management. Data Protection application programming interface (DPAPI) is an example of an encryption service provided on Windows 2000 and later operating systems where the operating system manages the key.
  • Use strong random key generation functions and store the key in a restricted location - for example, in a registry key secured with a restricted ACL - if you use an encryption mechanism that requires you to generate or manage the key.
  • Encrypt the encryption key using DPAPI for added security.
  • Expire keys regularly

Weak or Custom encryption

When users define their own encryption algorithm, it has to be properly tested. Weak encryption algorithms are easy to break. Users should go for well known encryption algorithms that are been used for long time. If there is a need for using custom encryption algorithm, it has to be properly tested.

Countermeasures to address weak or custom encryption

  • Avoid using custom encryption algorithms
  • Use the well known encryption algorithm that are been in use for longtime that withstood against all attacks
  • Be aware of algorithms that are cracked and techniques used to crack them

Parameter Manipulation

In web application, communication that happens through http protocol between client and server is transmitted as a plain text over the network. Information captured from the user is either sent in the form of query string, form fields, cookies and HTTP headers in the communication channel. These parameter data are sent as a plain text through the channel and attackers can manipulate these data before it reaches the server. This leads to following major threats that needs to be taken care

  • Query String manipulation
  • Form field manipulation
  • Cookie manipulation
  • HTTP header manipulation

Query String manipulation

When user information is sent through query string, it would be clearly visible to the user as the query string information is appended with the URL address and sent to the server. If the security mechanism of your application relies on the query string values to check the user credentials or any other security decisions are taken based on that, the application is vulnerable to security attack.

Countermeasures to address query string manipulation

  • Do not pass security related information through query string
  • Use encryption to send the information passed via query string
  • Use HTTP POST rather than using HTTP GET.

Form field manipulation

As the HTTP Protocol transmits the information in plain text, it is still possible for the attackers to modify any form fields and their values that are sent to the server. So, do not rely on the hidden fields for passing security credentials as it can be modified bypassing the client script validations.

Countermeasures to address form field manipulation

  • Use session identifiers to reference state maintained in the state store on the server.

Cookie manipulation

Cookie manipulation does refer to modification of cookie values that are of both persistent cookies and memory resident cookies. If cookie value stores information used for security mechanism of the application, the application is vulnerable to attack.

Countermeasures to address cookie manipulation

  • Use SSL which encrypts the information that are transmitted via the communication channel
  • Incase of persistent cookies stored in the client computer, use encryption or hashing to protect the information

HTTP Header manipulation

In web application, the client always makes request through HTTP protocol and the server responses through HTTP Protocol. During submitting the requests, client prepares the request HTTP headers and during response, server prepares the response HTTP headers. Application should not make any security decisions based on request and response headers. If so, the application is vulnerable to attack.

Countermeasures to HTTP Header manipulation

  • Do not use HTTP Headers to make security decisions

Exception Management

When exceptions are thrown from the application, sometimes the information shown in the exception might not be making sense for the end user but might be a very interesting message for an attacker. Especially, when it reveals the internals of the underlying system. While handling all types of exception is very important, the message that is shown to the user is also equally important. If not it leads to threats that includes

  • Attacker reveals implementation details
  • Denial of service

Attacker reveals implementation details

When the exceptions are thrown from the application, it might reveal the SQL information like tables, connection strings, column names, etc… that will become a open door for an attacker to take the entry into the application.

Countermeasures to prevent important information being shown in exception to users

  • Handle all types of exception in your application through out the code base.
  • Log all the exceptions that rose in the application for internal use. However, show appropriate information in the front end to the user who received this exception

Denial of Service

The objective of the attacker is to make application to behave abnormally such that either it reveals internals of the underlying system or crashes the application process such that no other user can use the application. Application crash can occur if the exceptions are not properly caught and handled.

Countermeasures to prevent denial of service

  • Each individual input received from the user should be thoroughly validated
  • Handle all types of exception in your application through out the code base.

Auditing & Logging

Auditing and logging enables to identify whether any one is trying to exploit the application. Any attempt to exploit the application, if logged can help to identify which user is trying to exploit and necessary actions can be taken to prevent the system from such attacks. If not enabled, it is harder to find out whether any one is actually exploiting the system without the system administrator being aware. This could lead to following threats

  • User denies performing an operation
  • Attackers exploit an application without leaving a trace
  • Attackers cover their tracks

User denies performing an operation

To address the issue of repudiation that concerned with user denying that he/she performed an action or initiated a transaction, a defense mechanism should be in place to ensure that all the user activity can be tracked and recorded

Countermeasures to prevent

  • Enable auditing and logging in web server, database server and application server.
  • Identify the key events and log them. For eg. Login, logout events
  • Avoid shared accounts. It will lead to difficulty as we cannot trace out the original source

Attackers exploit an application without leaving a trace

Detection mechanism should be there to identify the suspicious activity that occurs in the system. It should be logged to identify the occurrence of exploit or whether someone is trying to exploit.

Countermeasure to detect such suspicious activities

  • All critical application level operations should be logged
  • Read the log files every day to detect suspicious activity. Always maintain the back up of log files
  • If the platform provides any support to log important transactions, make use of that

Attackers cover their tracks

What if your log file can be tampered? Situation should never be worse like this. So, it should be well protected to ensure that an attacker does the exploit and clean the audit file too.

Countermeasures to prevent

  • Do not keep the log files in the default location folder. Move it to a different location.
  • Secure log files using Access Control Lists

Summary

This article explained you the doorsteps that attacker takes to exploit your application. Now that you will be aware of the techniques used by attackers. The next step should be protecting your application against all the techniques described above. For more information on security, follow this url
http://msdn.microsoft.com/security.


Similar Articles