White Paper [Type here] Application Security Development Guidelines Reducing the Top-Ten most critical web application security flaws Image source: Manoranjan Paul Document Revision Version 1.0 Doc Revision Date: February 26, 2014 Application Security Development Guidelines Table of contents Purpose of this document ....................................................................................................... 4 Introduction ........................................................................................................................... 4 What is Application Security Development? ........................................................................... 4 Security Architecture ..................................................................................................................................... 4 Security Principles ......................................................................................................................................... 4 1. Guidelines for Preventing Injection................................................................................... 6 1.1. 1.2. 1.3. 1.4. 1.5. What is Injection? ................................................................................................................................. 6 Defence Option 1: Prepared Statements (Parameterized Queries) ..................................................... 7 Defence Option 2: Stored Procedures .................................................................................................. 8 Defence Option 3: Escaping All User Supplied Input ............................................................................ 9 Additional Defences: .......................................................................................................................... 10 2. Guidelines for Preventing Broken Authentication and Session Management ................... 11 2.1. What is Broken Authentication and Session Management................................................................ 11 2.2. Defences ............................................................................................................................................. 11 3. Guidelines for Preventing Cross Site Scripting (XSS) ........................................................ 12 3.1. What is XSS? ....................................................................................................................................... 12 3.2. Three known types of XSS flaws: ........................................................................................................ 13 3.3. Defences ............................................................................................................................................. 16 4. Guidelines for Preventing Insecure Direct Object References .......................................... 21 4.1. What are Insecure Direct Object References? ................................................................................... 21 4.2. Insecure Direct Object References Examples: .................................................................................... 22 4.3. Defences for Insecure Direct Object References................................................................................ 22 5. Guidelines for Preventing Application Security Misconfiguration .................................... 22 5.1. 5.2. 5.3. 5.4. What is Application Security Misconfiguration? ................................................................................ 22 Is My Organisation Vulnerable to Application Security Misconfiguration? ....................................... 23 Application Security Misconfiguration Examples: .............................................................................. 23 Defences for Application Security Misconfiguration .......................................................................... 23 6. Guidelines for Preventing Sensitive Data Exposure ......................................................... 24 6.1. 6.2. 6.3. 6.4. What is Sensitive Data Exposure? ...................................................................................................... 24 Is My Organisation vulnerable to Sensitive Data Exposure? .............................................................. 25 Examples of Sensitive Data Exposure ................................................................................................. 25 Defences for Preventing Sensitive Data Exposure ............................................................................. 25 7. Guidelines for Missing Function Level Access Control...................................................... 26 7.1. 7.2. 7.3. 7.4. What is Missing Function Level Access Control? ................................................................................ 26 Is My Organisation Vulnerable to Missing Function Level Access Control? ....................................... 26 Examples of Missing Function Level Access Control .......................................................................... 27 Defences for Missing Function Level Access Control ......................................................................... 27 8. Guidelines for Preventing Cross-Site Request Forgery (CSRF) .......................................... 28 8.1. What is Cross-Site Request Forgery?.................................................................................................. 28 Page 2 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines 8.2. Cross-Site Request Forgery Example: ................................................................................................. 29 8.3. Defences for Cross-Site Request Forgery ........................................................................................... 29 9. Guidelines for Components with Known Vulnerabilities ................................................. 32 9.1. 9.2. 9.3. 9.4. What are Known Vulnerable Components? ....................................................................................... 32 Is My Organisation vulnerable to Using Components with Known Vulnerabilities?.......................... 32 Examples of Using Components with Known Vulnerabilities:............................................................ 32 Defences for Using Components with Known Vulnerabilities:........................................................... 33 10. Guidelines for Preventing Un-validated Redirects and Forwards ................................... 33 10.1. What are Un-validated Redirects and Forwards? .............................................................................. 33 10.2. Is My Organisation vulnerable to Un-validated Redirects and Forwards?......................................... 33 10.3. Examples of Un-validated Redirects and Forwards ............................................................................ 34 10.4. Defences for Un-validated Redirects and Forwards ........................................................................... 34 11. About This Document ................................................................................................... 35 11.1. Referenced documents ...................................................................................................................... 35 © Copyright Test and Verification Solutions Ltd. 2014 Page 3 Application Security Development Guidelines Purpose of this document The purpose of this document is to set out the guidelines for application development to include good practice for avoiding security vulnerabilities on any project. This document outlines the following: An explanation of Application Security Development. Guidelines for developers to prevent the top ten application security risks. Introduction The aim of this Development Guide is to allow developers, designers and solution architects to produce secure web applications. If done from the earliest stages, secure applications cost about the same to develop as insecure applications, but are far more cost effective in the long run. To protect an organisation, web applications must be self-defending. What is Application Security Development? Security Architecture The best system architecture designs and detailed design documents contain security discussion in each and every feature, how the risks are going to be mitigated, and what was actually done during coding. Security architecture starts on the day the business requirements are modeled, and never finishes until the last copy of your application is decommissioned. Security is a life-long process, not a one shot accident. When starting a new application or re-factoring an existing application, you should consider each functional feature: Is the process surrounding this feature as safe as possible? In other words, is this a flawed process? If I were evil, how would I abuse this feature? Is the feature required to be on by default? If so, are there limits or options that could help reduce the risk from this feature? Security Principles Minimize Attack Surface Area Every feature that is added to an application adds a certain amount of risk to the overall application. The aim for secure development is to reduce the overall risk by reducing the attack surface area. For example, a web application implements online help with a search function. The search function may be vulnerable to SQL injection attacks. If the help feature was limited to authorized users, the attack likelihood is reduced. If the help feature’s search function was gated through centralized data validation routines, the ability to perform SQL injection is dramatically reduced. However, if the help feature was re-written to eliminate the search function (through better user interface, for example), this almost eliminates the attack surface area, even if the help feature was available to the Internet at large. Principle of Least Privilege The principle of least privilege recommends that accounts have the least amount of privilege required to perform their business processes. This encompasses user rights, resource permissions such as CPU limits, Page 4 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines memory, network, and file system permissions. For example, if a middleware server only requires access to the network, read access to a database table, and the ability to write to a log, this describes all the permissions that should be granted. Under no circumstances should the middleware be granted administrative privileges. Principle of Defence in Depth The principle of defense in depth suggests that where one control would be reasonable, more controls that approach risks in different fashions are better. Controls, when used in depth, can make severe vulnerabilities extraordinarily difficult to exploit and thus unlikely to occur. With secure coding, this may take the form of tier-based validation, centralized auditing controls, and requiring users to be logged on all pages. For example, a flawed administrative interface is unlikely to be vulnerable to anonymous attack if it correctly gates access to production management networks, checks for administrative user authorization, and logs all access. Fail Securely Applications regularly fail to process transactions for many reasons. How they fail can determine if an application is secure or not. For example: isAdmin = true; try { codeWhichMayFail(); isAdmin = isUserInRole( “Administrator” ); } catch (Exception ex) { log.write(ex.toString()); } If either codeWhichMayFail() or isUserInRole fails or throws an exception, the user is an admin by default. This is obviously a security risk. Avoid security by obscurity Security through obscurity is a weak security control, and nearly always fails when it is the only control. This is not to say that keeping secrets is a bad idea, it simply means that the security of key systems should not be reliant upon keeping details hidden. For example, the security of an application should not rely upon knowledge of the source code being kept secret. The security should rely upon many other factors, including reasonable password policies, defense in depth, business transaction limits, solid network architecture, and fraud and audit controls. Fix security issues correctly Once a security issue has been identified, it is important to develop a test for it, and to understand the root cause of the issue. When design patterns are used, it is likely that the security issue is widespread amongst all code bases, so developing the right fix without introducing regressions is essential. For example, a user has found that they can see another user’s data by adjusting their cookie. The fix seems to be relatively straightforward, but as the cookie handling code is shared among all applications, a change to just one application will trickle through to all other applications. The fix must therefore be tested on all affected applications. © Copyright Test and Verification Solutions Ltd. 2014 Page 5 Application Security Development Guidelines 1. Guidelines for Preventing Injection 1.1. What is Injection? Source: OWASP An SQL injection is often used to attack the security of a website by inputting SQL statements in a web form to get a poorly designed website to perform operations on the database (often to dump the database content to the attacker) other than the usual operations as intended by the designer. SQL injection is a code injection technique that exploits security vulnerability in a website's software. The vulnerability happens when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not ‘strongly typed’ and unexpectedly executed. SQL commands are thus injected from the web form into the database of an application (like queries) to change the database content or dump the database information to the attacker. SQL injection is mostly known as an attack vector for websites but can be used to attack any type of SQL (including Oracle) database. An example: The application uses untrusted data in the construction of the following vulnerable SQL call: String query = "SELECT * request.getParameter("id") +"'"; FROM accounts WHERE custID='" + 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 customer's. 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, allowing a complete takeover of the database host. To avoid SQL injection flaws is simple. Developers need to either: a) stop writing dynamic queries; and/or b) prevent user supplied input which contains malicious SQL from affecting the logic of the executed query. These Development Guidelines provides a set of simple techniques for preventing SQL Injection vulnerabilities by avoiding these two problems. These techniques can be used with practically any kind of programming language with any type of database. There are other types of databases, like XML databases, which can have similar problems (e.g., XPath and XQuery injection) and these techniques can be used to protect them as well. Primary Defenses: Option #1: Use of Prepared Statements (Parameterized Queries) Option #2: Use of Stored Procedures Option #3: Escaping all User Supplied Input Additional Defenses: Also Enforce: Least Privilege Also Perform: White List Input Validation Page 6 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines 1.2. Defence Option 1: Prepared Statements (Parameterized Queries) The use of prepared statements (aka parameterized queries) is how all developers should first be taught how to write database queries. They are simple to write, and easier to understand than dynamic queries. Parameterized queries force the developer to first define all the SQL code, and then pass in each parameter to the query later. This coding style allows the database to distinguish between code and data, regardless of what user input is supplied. Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker. In the safe example below, if an attacker were to enter the userID of tom' or '1'='1, the parameterized query would not be vulnerable and would instead look for a username which literally matched the entire string tom' or '1'='1. Language specific recommendations: Java EE – use PreparedStatement() with bind variables .NET – use parameterized queries like SqlCommand() or OleDbCommand() with bind variables PHP – use PDO with strongly typed parameterized queries (using bindParam()) Hibernate - use createQuery() with bind variables (called named parameters in Hibernate) SQLite - use sqlite3_prepare() to create a statement object In rare circumstances, prepared statements can harm performance. When confronted with this situation, it is best to escape all user supplied input using an escaping routine specific to your database vendor as is described below, rather than using a prepared statement. Another option which might solve your performance issue is to use a stored procedure instead. Safe Java Prepared Statement Example: The following code example uses a PreparedStatement, Java's implementation of a parameterized query, to execute the same database query. String custname = request.getParameter("customerName"); // This should REALLY be validated too // perform input validation to detect attacks String query = "SELECT account_balance FROM user_data WHERE user_name = ? "; PreparedStatement pstmt = connection.prepareStatement( query ); pstmt.setString( 1, custname); ResultSet results = pstmt.executeQuery( ); Hibernate Query Language (HQL) Prepared Statement (Named Parameters) Examples: First is an unsafe HQL Statement:- Query unsafeHQLQuery = session.createQuery("from Inventory where productID='"+userSuppliedParameter+"'"); Here is a safe version of the same query using named parameters:Query safeHQLQuery = session.createQuery("from Inventory where productID=:productid"); safeHQLQuery.setParameter("productid", userSuppliedParameter); Developers tend to like the Prepared Statement approach because all the SQL code stays within the application. This makes your application relatively database independent. However, other options allow you to store all the SQL code in the database itself, which has both security and non-security advantages. That approach, called Stored Procedures, is described next. © Copyright Test and Verification Solutions Ltd. 2014 Page 7 Application Security Development Guidelines 1.3. Defence Option 2: Stored Procedures Stored procedures have the same effect as the use of prepared statements when implemented safely*. They require the developer to define the SQL code first, and then pass in the parameters after. The difference between prepared statements and stored procedures is that the SQL code for a stored procedure is defined and stored in the database itself, and then called from the application. Both of these techniques have the same effectiveness in preventing SQL injection so developers should choose which approach makes the most sense. *Note: 'Implemented safely' means the stored procedure does not include any unsafe dynamic SQL generation. Developers do not usually generate dynamic SQL inside stored procedures. However, it can be done, but should be avoided. If it can't be avoided, the stored procedure must use input validation or proper escaping as described in this document to make sure that all user supplied input to the stored procedure can't be used to inject SQL code into the dynamically generated query. Auditors should always look for uses of sp_execute, execute or exec within SQL Server stored procedures. Similar audit guidelines are necessary for similar functions for other vendors. There are also several cases where stored procedures can increase risk. For example, on MS SQL server, you have 3 main default roles: db_datareader, db_datawriter and db_owner. Before stored procedures came into use, DBA's would give db_datareader or db_datawriter rights to the webservice's user, depending on the requirements. However, stored procedures require execute rights, a role that is not available by default. Some setups where the user management has been centralized, but is limited to those 3 roles, cause all web apps to run under db_owner rights so stored procedures can work. Naturally, that means that if a server is breached the attacker has full rights to the database, where previously they might only have had read-access. Unsafe Java Query Example SQL injection flaws typically look like this: The following (Java) example is UNSAFE, and would allow an attacker to inject code into the query that would be executed by the database. The unvalidated “customerName” parameter that is simply appended to the query allows an attacker to inject any SQL code they want. Unfortunately, this method for accessing databases is all too common. String query = "SELECT account_balance FROM user_data WHERE user_name = " + request.getParameter("customerName"); try { Statement statement = connection.createStatement( … ); ResultSet results = statement.executeQuery( query ); } Safe Java Stored Procedure Example The following code example uses a CallableStatement, Java's implementation of the stored procedure interface, to execute the same database query. The "sp_getAccountBalance" stored procedure would have to be predefined in the database and implement the same functionality as the query defined above. String custname = request.getParameter("customerName"); // This should REALLY be validated try { CallableStatement cs = connection.prepareCall("{call sp_getAccountBalance(?)}"); cs.setString(1, custname); ResultSet results = cs.executeQuery(); // … result set handling } catch (SQLException se) { // … logging and error handling } Page 8 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines 1.4. Defence Option 3: Escaping All User Supplied Input This third technique is to escape user input before putting it in a query. If you are concerned that rewriting your dynamic queries as prepared statements or stored procedures might break your application or adversely affect performance, then this might be the best approach for you. However, this methodology is frail compared to using parameterized queries. This technique should only be used, with caution, to retrofit legacy code in a cost effective way. Applications built from scratch, or applications requiring low risk tolerance should be built or re-written using parameterized queries. This technique works like this. Each DBMS supports one or more character escaping schemes specific to certain kinds of queries. If you then escape all user supplied input using the proper escaping scheme for the database you are using, the DBMS will not confuse that input with SQL code written by the developer, thus avoiding any possible SQL injection vulnerabilities. Database Specific Escaping Details If you want to build your own escaping routines, here are the escaping details for each of the databases that OWASP have developed ESAPI Encoders for: Oracle Escaping This information is based on the Oracle Escape character information found here: http://www.orafaq.com/wiki/SQL_FAQ#How_does_one_escape_special_characters_when_writing_SQL _queries.3F Escaping Dynamic Queries To use an ESAPI database codec is pretty simple. An Oracle example looks something like: ESAPI.encoder().encodeForSQL( new OracleCodec(), queryparam ); So, if you had an existing Dynamic query being generated in your code that was going to Oracle that looked like this: String query = "SELECT user_id req.getParameter("userID") FROM user_data WHERE user_name = '" + + "' and user_password = '" + req.getParameter("pwd") +"'"; try { Statement statement = connection.createStatement( … ); ResultSet results = statement.executeQuery( query ); } You would rewrite the first line to look like this: Codec ORACLE_CODEC = new OracleCodec(); String query = "SELECT user_id FROM user_data WHERE user_name = '" + ESAPI.encoder().encodeForSQL( ORACLE_CODEC, req.getParameter("userID")) + "' and user_password = '" + ESAPI.encoder().encodeForSQL( ORACLE_CODEC, req.getParameter("pwd")) +"'"; And it would now be safe from SQL injection, regardless of the input supplied. For maximum code readability, you could also construct your own OracleEncoder. Encoder oe = new OracleEncoder(); String query = "SELECT user_id FROM user_data WHERE user_name = '" + oe.encode( req.getParameter("userID")) + "' and user_password = '" + oe.encode( req.getParameter("pwd")) +"'"; © Copyright Test and Verification Solutions Ltd. 2014 Page 9 Application Security Development Guidelines With this type of solution, all developers would have to do is wrap each user supplied parameter being passed in into an ESAPI.encoder().encodeForOracle( ) call or whatever it is called at your organisation . Turn off character replacement Use SET DEFINE OFF or SET SCAN OFF to ensure that automatic character replacement is turned off. If this character replacement is turned on, the & character will be treated like a SQLPlus variable prefix that could allow an attacker to retrieve private data. See http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch12040.htm#i2698854 and http://stackoverflow.com/questions/152837/how-to-insert-a-string-which-contains-an for more information. Escaping Wildcard characters in Like Clauses The LIKE keyword allows for text scanning searches. In Oracle, the underscore '_' character matches only one character, while the ampersand '%' is used to match zero or more occurrences of any characters. These characters must be escaped in LIKE clause criteria. For example: SELECT name FROM emp WHERE id LIKE '%/_%' ESCAPE '/'; SELECT name FROM emp WHERE id LIKE '%\%%' ESCAPE '\'; Oracle 10g escaping An alternative for Oracle 10g and later is to place { and } around the string to escape the entire string. However, you have to be careful that there isn't a } character already in the string. You must search for these and if there is one, then you must replace it with }} otherwise that character will end the escaping early, and may introduce a vulnerability. 1.5. Additional Defences: Least Privilege To minimize the potential damage of a successful SQL injection attack, you should minimize the privileges assigned to every database account in your environment. Do not assign DBA or admin type access rights to your application accounts. We understand that this is easy, and everything just ‘works’ when you do it this way, but it is very dangerous. Start from the ground up to determine what access rights your application accounts require, rather than trying to figure out what access rights you need to take away. Make sure that accounts that only need read access are only granted read access to the tables they need access to. If an account only needs access to portions of a table, consider creating a view that limits access to that portion of the data and assigning the account access to the view instead, rather than the underlying table. Rarely, if ever, grant create or delete access to database accounts. If you adopt a policy where you use stored procedures everywhere, and don’t allow application accounts to directly execute their own queries, then restrict those accounts to only be able to execute the stored procedures they need. Don’t grant them any rights directly to the tables in the database. SQL injection is not the only threat to your database data. Attackers can simply change the parameter values from one of the legal values they are presented with, to a value that is unauthorized for them, but the application itself might be authorized to access. As such, minimizing the privileges granted to your application will reduce the likelihood of such unauthorized access attempts, even when an attacker is not trying to use SQL injection as part of their exploit. Page 10 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines While you are at it, you should minimize the privileges of the operating system account that the DBMS runs under. Don't run your DBMS as root or system! Most DBMSs run out of the box with a very powerful system account. For example, MySQL runs as system on Windows by default! Change the DBMS's OS account to something more appropriate, with restricted privileges. White List Input Validation can be used to detect unauthorized input before it is passed to the SQL query. Positive or "whitelist" input validation with appropriate canonicalization also helps protect against injection, but is not a complete defence as many applications require special characters in their input. 2. Guidelines for Preventing Broken Authentication and Session Management 2.1. What is Broken Authentication and Session Management Source: OWASP Anonymous external attackers, as well as users with their own accounts, may attempt to steal accounts from others or to disguise their actions. The attacker uses leaks or flaws in the authentication or session management functions (e.g., exposed accounts, passwords, session IDs) to impersonate users. Developers frequently build custom authentication and session management schemes, but building these correctly is hard. As a result, these custom schemes frequently have flaws in areas such as logout, password management, time-outs, remember me, secret question, account update, etc. 2.2. Defences Authentication is the act of establishing or confirming something (or someone) as authentic, and that claims made by or about the thing are true. Authenticating an object may mean confirming its provenance, whereas authenticating a person often consists of verifying his or her identity. Authentication depends upon one or more authentication factors. In computer security, authentication is the process of attempting to verify the digital identity of the sender of a communication. A common example of such a process is the logon process. Password Storage - All passwords must be stored in either hashed or encrypted form to protect them from exposure, regardless of where they are stored. Hashed form is preferred since it is not reversible. Encryption should be used when the plaintext password is needed, such as when using the password to login to another system. Passwords should never be hardcoded in any source code. Decryption keys must be strongly protected to ensure that they cannot be grabbed and used to decrypt the password file. Protecting Credentials in Transit - The only effective technique is to encrypt the entire login transaction using something like SSL. Simple transformations of the password such as hashing it on the client prior to transmission provide little protection as the hashed version can simply be intercepted and retransmitted even though the actual plaintext password might not be known. Session ID Protection – Ideally, a user’s entire session should be protected via SSL. If this is done, then the session ID (e.g., session cookie) cannot be grabbed off the network, which is the biggest risk of exposure for a session ID. If SSL is not viable for performance or other reasons then session IDs themselves must be protected in other ways. First, they should never be included in the URL as they can be cached by the © Copyright Test and Verification Solutions Ltd. 2014 Page 11 Application Security Development Guidelines browser, sent in the referrer header, or accidentally forwarded to a ‘friend’. Session IDs should be long, complicated, random numbers that cannot be easily guessed. Session IDs can also be changed frequently during a session to reduce how long a session ID is valid. Session IDs must be changed when switching to SSL, authenticating, or other major transitions. Session IDs chosen by a user should never be accepted. Account Lists - Systems should be designed to avoid allowing users to gain access to a list of the account names on the site. If lists of users must be presented, it is recommended that some form of pseudonym (screen name) that maps to the actual account be listed instead. That way, the pseudonym can’t be used during a login attempt or some other hack that goes after a user’s account. Browser Caching – Authentication and session data should never be submitted as part of a GET, POST should always be used instead. Authentication pages should be marked with all varieties of the no cache tag to prevent someone from using the back button in a user’s browser to backup to the login page and resubmit the previously typed in credentials. Many browsers now support the AUTOCOMPLETE=OFF flag to prevent storing of credentials in autocomplete caches. Trust Relationships – Your site architecture should avoid implicit trust between components whenever possible. Each component should authenticate itself to any other component it is interacting with unless there is a strong reason not to (such as performance or lack of a usable mechanism). If trust relationships are required, strong procedural and architecture mechanisms should be in place to ensure that such trust cannot be abused as the site architecture evolves over time. 3. Guidelines for Preventing Cross Site Scripting (XSS) 3.1. What is XSS? Source: OWASP Cross-Site Scripting (XSS) attacks are a type of injection problem, in which malicious scripts are injected into the otherwise benign and trusted web sites. Cross-site scripting attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user in the output it generates without validating or encoding it. An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the user’s browser and associated with that site. These scripts can even rewrite the content of the HTML page. Cross-Site Scripting (XSS) attacks occur when: 1. Data enters a Web application through an untrusted source, most frequently a web request. 2. The data is included in dynamic content that is sent to a web user without being validated for malicious code. The malicious content sent to the web browser often takes the form of a segment of JavaScript, but may also include HTML, Flash or any other type of code that the browser may execute. The variety of attacks based on XSS is almost limitless, but they commonly include transmitting private data like cookies or other session information to the attacker, redirecting the victim to web content controlled by the Page 12 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines attacker, or performing other malicious operations on the user's machine under the guise of the vulnerable site. Anyone who can send untrusted data to an organisation systems, including external users, internal users, and administrators is a threat agent. Almost any source of data can be an attack vector, including internal sources such as data from the database. XSS is the most prevalent web application security flaw. XSS flaws occur when an application includes user supplied data in a page sent to the browser without properly validating or escaping that content. 3.2. Three known types of XSS flaws: 1) Stored - Stored attacks are those where the injected code is permanently stored on the target servers, such as in a database, in a message forum, visitor log, comment field, etc. The victim then retrieves the malicious script from the server when it requests the stored information. 1. The attacker uses one of the website's forms to insert a malicious string into the website's database. 2. The victim requests a page from the website. 3. The website includes the malicious string from the database in the response and sends it to the victim. 4. The victim's browser executes the malicious script inside the response, sending the victim's cookies to the attacker's server. Source: Excess XSS by Jakob Kallin and Irene Lobo Valbuena 2) Reflected - Reflected attacks are those where the injected code is reflected off the web server, such as in an error message, search result, or any response that includes some or all of the input sent to the server as part of the request. © Copyright Test and Verification Solutions Ltd. 2014 Page 13 Application Security Development Guidelines Reflected attacks are delivered to victims via another route, such as in an e-mail message, or on some other web server. When a user is tricked into clicking on a malicious link or submitting a specially crafted form, the injected code travels to the vulnerable web server, which reflects the attack back to the user’s browser. The browser then executes the code because it came from a "trusted" server. 1. The attacker crafts a URL containing a malicious string and sends it to the victim. 2. The victim is tricked by the attacker into requesting the URL from the website. 3. The website includes the malicious string from the URL in the response. 4. The victim's browser executes the malicious script inside the response, sending the victim's cookies to the attacker's server. Source: Excess XSS by Jakob Kallin and Irene Lobo Valbuena 3) DOM (Document Object Model) based XSS - DOM Based XSS (or as it is called in some texts, “type-0 XSS”) is an XSS attack wherein the attack payload is executed as a result of modifying the DOM “environment” in the victim’s browser used by the original client side script, so that the client side code runs in an “unexpected” manner. That is, the page itself (the HTTP response that is) does not change, but the client side code contained in the page executes differently due to the malicious modifications that have occurred in the DOM environment. This is in contrast to other XSS attacks (stored or reflected), wherein the attack payload is placed in the response page (due to a server side flaw). Page 14 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines Source: Excess XSS by Jakob Kallin and Irene Lobo Valbuena 1. The attacker crafts a URL containing a malicious string and sends it to the victim. 2. The victim is tricked by the attacker into requesting the URL from the website. 3. The website receives the request, but does not include the malicious string in the response. 4. The victim's browser executes the legitimate script inside the response, causing the malicious script to be inserted into the page. 5. The victim's browser executes the malicious script inserted into the page, sending the victim's cookies to the attacker's server. In traditional XSS, the malicious JavaScript is executed when the page is loaded, as part of the HTML sent by the server. In DOM-based XSS, the malicious JavaScript is executed at some point after the page has loaded, as a result of the page's legitimate JavaScript treating user input in an unsafe way. Injection is an attack that involves breaking out of a data context and switching into a code context through the use of special characters that are significant in the interpreter being used. A data context is like <div>data context</div>. If the attacker's data gets placed into the data context, they might break out like this <div>data < script>alert("attack")</script> context</div>. XSS is a form of injection where the interpreter is the browser and attacks are buried in an HTML document. HTML is particularly difficult because it is not only hierarchical, but also contains many different parsers (XML, HTML, JavaScript, VBScript, CSS, URL, etc...). © Copyright Test and Verification Solutions Ltd. 2014 Page 15 Application Security Development Guidelines There are two ways to inject code: Injecting UP The most common way is to close the current context and start a new code context. For example, this is what you do when you close an HTML attribute with a "> and start a new <script> tag. This attack closes the original context (going up in the hierarchy) and then starts a new tag that will allow script code to execute. Remember that you may be able to skip many layers up in the hierarchy when trying to break out of your current context. For example, a </script> tag may be able to terminate a script block even if it is injected inside a quoted string inside a method call inside the script. This happens because the HTML parser runs before the JavaScript parser. Injecting DOWN The less common way to perform XSS injection is to introduce a code subcontext without closing the current context. For example, if the attacker is able to change <img src="...UNTRUSTED DATA HERE..." /> into < img src="javascript:alert(document.cookie)" /> they do not have to break out of the HTML attribute context. Instead, they introduce a subcontext that allows scripting within the src attribute (in this case a javascript url). Another example is the expression() functionality in CSS properties. Even though you may not be able to escape a quoted CSS property to inject up, you may be able to introduce something like xss:expression(document.write(document.cookie)) without ever leaving the current context. General Notes There's also the possibility of injecting directly in the current context. For example, if you take untrusted input and put it directly into a JavaScript context. Generally it is impossible to secure untrusted code with escaping (or anything else). If you do this, your application is just a conduit for attacker code to get running in your users' browsers. The rules in this document have been designed to prevent both UP and DOWN varieties of XSS injection. To prevent injecting up, you must escape the characters that would allow you to close the current context and start a new one. To prevent attacks that jump up several levels in the DOM hierarchy, you must also escape all the characters that are significant in all enclosing contexts. To prevent injecting down, you must escape any characters that can be used to introduce a new sub-context within the current context. 3.3. Defences To defend against XSS, ensure that all user supplied input sent back to the browser is verified to be safe (via input validation), and that user input is properly escaped before it is included in the output page. Proper output encoding ensures that such input is always treated as text in the browser, rather than active content that might get executed. Rule 0 – Never Insert Untrusted Data Except in Allowed Locations Preventing XSS requires keeping untrusted data separate from active browser content. <script>...NEVER PUT UNTRUSTED DATA HERE...</script> directly in a script <!--...NEVER PUT UNTRUSTED DATA HERE...--> inside an HTML comment <div ...NEVER PUT UNTRUSTED DATA HERE...=test /> in an attribute name <NEVER PUT UNTRUSTED DATA HERE... href="/test" /> in a tag name <style>...NEVER PUT UNTRUSTED DATA HERE...</style> directly in CSS Page 16 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines Rule 1 – HTML Escape Before Inserting Untrusted Data into HTML Element Content Rule 1 is for when you want to put untrusted data directly into the HTML body somewhere. This includes inside normal tags like div, p, b, td, etc. Most web frameworks have a method for HTML escaping for the characters detailed below. However, this is absolutely not sufficient for other HTML contexts. You need to implement the other rules detailed here as well. <body>...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...</body> <div>...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...</div> any other normal HTML elements Escape the following characters with HTML entity encoding to prevent switching into any execution context, such as script, style, or event handlers. Using hex entities is recommended in the spec. In addition to the 5 characters significant in XML (&, <, >, ", '), the forward slash is included as it helps to end an HTML entity. & --> &amp; < --> &lt; > --> &gt; " --> &quot; ' --> &#x27; &apos; is not recommended / --> &#x2F; forward slash is included as it helps end an HTML entity Rule 2 – Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes Rule 2 is for putting untrusted data into typical attribute values like width, name, value, etc. This should not be used for complex attributes like href, src, style, or any of the event handlers like onmouseover. It is extremely important that event handler attributes should follow Rule #3 for HTML JavaScript Data Values. <div attr=...ESCAPE UNTRUSTED inside UNquoted attribute DATA BEFORE PUTTING HERE...>content</div> <div attr='...ESCAPE UNTRUSTED inside single quoted attribute DATA BEFORE PUTTING HERE...'>content</div> <div attr="...ESCAPE UNTRUSTED inside double quoted attribute DATA BEFORE PUTTING HERE...">content</div> Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the &#xHH; format (or a named entity if available) to prevent switching out of the attribute. The reason this rule is so broad is that developers frequently leave attributes unquoted. Properly quoted attributes can only be escaped with the corresponding quote. Unquoted attributes can be broken out of with many characters, including [space] % * + , - / ; < = > ^ and |. Rule 3 – JavaScript Escape Before Inserting Untrusted Data into JavaScript Data Values Rule 3 concerns dynamically generated JavaScript code - both script blocks and event-handler attributes. The only safe place to put untrusted data into this code is inside a quoted "data value." Including untrusted data inside any other JavaScript context is quite dangerous, as it is extremely easy to switch into an © Copyright Test and Verification Solutions Ltd. 2014 Page 17 Application Security Development Guidelines execution context with characters including (but not limited to) semi-colon, equals, space, plus, and many more, so use with caution. <script>alert('...ESCAPE inside a quoted string UNTRUSTED DATA BEFORE PUTTING HERE...')</script> <script>x='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'</script> side of a quoted expression one <div onmouseover="x='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'"</div> inside quoted event handler Please note there are some JavaScript functions that can never safely use untrusted data as input - EVEN IF JAVASCRIPT ESCAPED! For example: <script> window.setInterval('...EVEN HERE...'); IF YOU ESCAPE UNTRUSTED DATA YOU ARE XSSED </script> Except for alphanumeric characters, escape all characters less than 256 with the \xHH format to prevent switching out of the data value into the script context or into another attribute. DO NOT use any escaping shortcuts like \" because the quote character may be matched by the HTML attribute parser which runs first. These escaping shortcuts are also susceptible to "escape-the-escape" attacks where the attacker sends \" and the vulnerable code turns that into \\" which enables the quote. If an event handler is properly quoted, breaking out requires the corresponding quote. Unquoted attributes can be broken out of with many characters including [space] % * + , - / ; < = > ^ and |. Also, a </script> closing tag will close a script block even though it is inside a quoted string because the HTML parser runs before the JavaScript parser. Rule 3.1 – HTML escape JSON values in an HTML context and read the data with JSON.parse The need for having data dynamically generated by an application in a javascript context is common. One strategy is to make an AJAX call to get the values, but this isn't always performant. Often, an initial block of JSON is loaded into the page to act as a single place to store multiple values. This data is tricky, though not impossible, to escape correctly without breaking the format and content of the values. Ensure returned Content-Type header is application/json and not text/html. This shall instruct the browser not misunderstand the context and execute injected script. JSON entity encoding The rules for JSON encoding can be found in the Output Encoding Rules Summary. Note, this will not allow you to use XSS protection provided by CSP 1.0. HTML entity encoding This technique has the advantage that html entity escaping is widely supported and helps separate data from server side code without crossing any context boundaries. Consider placing the JSON block on the page as a normal element and then parsing the innerHTML to get the contents. The javascript that reads the span can live in an external file, thus making the implementation of CSP enforcement easier. Page 18 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines Rule 4 – CSS Escape And Strictly Validate Before Inserting Untrusted Data into HTML Style Property Values Rule 4 is for when you want to put untrusted data into a stylesheet or a style tag. CSS is surprisingly powerful, and can be used for numerous attacks. Therefore, it's important that you only use untrusted data in a property value and not into other places in style data. You should stay away from putting untrusted data into complex properties like url, behavior, and custom (-moz-binding). You should also not put untrusted data into IE’s expression property value which allows JavaScript. <style>selector { property : ...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...; } </style> property value <style>selector { property : "...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE..."; } </style> property value <span style="property HERE...">text</style> : ...ESCAPE UNTRUSTED property value DATA BEFORE PUTTING Please note there are some CSS contexts that can never safely use untrusted data as input - EVEN IF PROPERLY CSS ESCAPED! You will have to ensure that URLs only start with "http" not "javascript" and that properties never start with "expression". For example: { background-url : "javascript:alert(1)"; } // and all other URLs { text-size: "expression(alert('XSS'))"; } // only in IE Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the \HH escaping format. DO NOT use any escaping shortcuts like \" because the quote character may be matched by the HTML attribute parser which runs first. These escaping shortcuts are also susceptible to "escapethe-escape" attacks where the attacker sends \" and the vulnerable code turns that into \\" which enables the quote. If attribute is quoted, breaking out requires the corresponding quote. All attributes should be quoted but your encoding should be strong enough to prevent XSS when untrusted data is placed in unquoted contexts. Unquoted attributes can be broken out of with many characters including [space] % * + , - / ; < = > ^ and |. Also, the </style> tag will close the style block even though it is inside a quoted string because the HTML parser runs before the JavaScript parser. Rule 5 – URL Escape Before Inserting Untrusted Data into HTML URL Parameter Values Rule 5 is for when you want to put untrusted data into HTTP GET parameter value. <a href="http://www.somesite.com?test=...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...">link</a > Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the %HH escaping format. Including untrusted data in data: URLs should not be allowed as there is no good way to disable attacks with escaping to prevent switching out of the URL. All attributes should be quoted. Unquoted attributes can be broken out of with many characters including [space] % * + , - / ; < = > ^ and |. Note that entity encoding is useless in this context. WARNING: Do not encode complete or relative URL's with URL encoding! If untrusted input is meant to be placed into href, src or other URL-based attributes, it should be validated to make sure it does not point to an unexpected protocol, especially Javascript links. URL's should then be encoded based on the context © Copyright Test and Verification Solutions Ltd. 2014 Page 19 Application Security Development Guidelines of display like any other piece of data. For example, user driven URL's in HREF links should be attribute encoded. For example: String userURL = request.getParameter( "userURL" ) boolean isValidURL "URL", 255, false); = ESAPI.validator().isValidInput("URLContext", userURL, if (isValidURL) { <a href="<%=encoder.encodeForHTMLAttribute(userURL)%>">link</a> } Rule 6 – Sanitize HTML Markup with a Library Designed for the Job If your application handles markup (untrusted input that is supposed to contain HTML) it can be very difficult to validate. Encoding is also difficult, since it would break all the tags that are supposed to be in the input. Therefore, you need a library that can parse and clean HTML formatted text. There are several available at OWASP that are simple to use: OWASP AntiSamy: https://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project import org.owasp.validator.html.*; Policy policy = Policy.getInstance(POLICY_FILE_LOCATION); AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(dirtyInput, policy); MyUserDAO.storeUserProfile(cr.getCleanHTML()); // some custom function OWASP Java HTML Sanitizer: https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project import org.owasp.html.Sanitizers; import org.owasp.html.PolicyFactory; PolicyFactory sanitizer = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS); String cleanResults = sanitizer.sanitize("<p>Hello, <b>World!</b>"); Rule 7 – Prevent DOM-based XSS Reflected and Stored XSS are server side execution issues while DOM based XSS is a client (browser) side execution issue. All of this code originates on the server, which means it is the application owner's responsibility to make it safe from XSS, regardless of the type of XSS flaw it is. This is a large topic best tackled by following the links below for combating DOM-based XSS. 1. The Open Web Application Security Project – XSS Prevention https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet Cheat Sheet: 1.1 RULE #1 - HTML Escape then JavaScript Escape Before Inserting Untrusted Data into HTML Subcontext within the Execution Context 1.1.1 Example Dangerous HTML Methods 1.1.1.1 Attributes 1.1.1.2 Methods 1.1.2 Guideline Page 20 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines 1.2 RULE #2 - JavaScript Escape Before Inserting Untrusted Data into HTML Attribute Subcontext within the Execution Context 1.2.1 SAFE but BROKEN example 1.2.2 SAFE and FUNCTIONALLY CORRECT example 1.3 RULE #3 - Be Careful when Inserting Untrusted Data into the Event Handler and JavaScript code Subcontexts within an Execution Context 1.3.1 HTML Encoding’s Disarming Nature 1.4 RULE #4 - JavaScript Escape Before Inserting Untrusted Data into the CSS Attribute Subcontext within the Execution Context 1.5 RULE #5 - URL Escape then JavaScript Escape Before Inserting Untrusted Data into URL Attribute Subcontext within the Execution Context 2. The DOMinator Tool - A FireFox based plugin that helps testers identify and verify DOM based XSS flaws. See: http://code.google.com/p/dominator/ 3. The DOM XSS Wiki - The start of a Knowledgebase for defining sources of attacker controlled inputs and sinks which could potentially introduce DOM Based XSS issues. See: http://code.google.com/p/domxsswiki/ Bonus Rule 1: Use HTTPOnly cookie flag Preventing all XSS flaws in an application is hard. To help mitigate the impact of an XSS flaw on your site, set the HTTPOnly flag on your session cookie and any custom cookies you have that are not accessed by any Javascript you wrote. This cookie flag is typically on by default in .NET apps, but in other languages you have to set it manually. For more details on the HTTPOnly cookie flag, including what it does, and how to use it, see the OWASP article on HTTPOnly. Bonus Rule 2: Implement Content Security Policy There is another good complex solution to mitigate the impact of an XSS flaw called Content Security Policy. It's a browser side mechanism which allows you to create source whitelists for client side resources of your web application, e.g. JavaScript, CSS, images, etc. CSP via special HTTP header instructs the browser to only execute or render resources from those sources. For more details on Content Security Policy, including what it does, and how to use it, see the OWASP article on Content_Security_Policy 4. Guidelines for Preventing Insecure Direct Object References 4.1. What are Insecure Direct Object References? Source: OWASP Applications frequently use the actual name or key of an object when generating web pages. Applications don’t always verify the user is authorized for the target object. This results in an insecure direct object reference flaw. An attacker, who is an authorized system user, simply changes a parameter value that © Copyright Test and Verification Solutions Ltd. 2014 Page 21 Application Security Development Guidelines directly refers to a system object to another object the user isn’t authorized for. If access is granted, such flaws can compromise all the data that can be referenced by the parameter. The best way to find out if an application is vulnerable to insecure direct object references is to verify that all object references have appropriate defences. To achieve this, consider: 4.2. For direct references to restricted resources, the application needs to verify the user is authorized to access the exact resource they have requested. If the reference is an indirect reference, the mapping to the direct reference must be limited to values authorized for the current user. Insecure Direct Object References Examples: The application uses unverified data in a SQL call that is accessing account information: String query = "SELECT * FROM accts WHERE account = ?"; PreparedStatement pstmt = connection.prepareStatement(query , ... ); pstmt.setString( 1, request.getParameter("acct")); ResultSet results = 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 user’s account, instead of only the intended customer’s account. http://example.com/app/accountInfo?acct=notmyacct 4.3. Defences for Insecure Direct Object References Preventing insecure direct object references requires selecting an approach for protecting each user accessible object (e.g., object number, filename): Use per user or session indirect object references. This prevents attackers from directly targeting unauthorized resources. For example, instead of using the resource’s database key, a drop down list of six resources authorized for the current user could use the numbers 1 to 6 to indicate which value the user selected. The application has to map the per-user indirect reference back to the actual database key on the server. Check access. Each use of a direct object reference from an untrusted source must include an access control check to ensure the user is authorized for the requested object. 5. Guidelines for Preventing Application Security Misconfiguration 5.1. What is Application Security Misconfiguration? Source: OWASP Page 22 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines Security misconfiguration can happen at any level of an application stack, including the platform, web server, application server, framework, and custom code. Such flaws frequently give attackers unauthorized access to some system data or functionality. Occasionally, such flaws result in a complete system compromise. The attacker accesses default accounts, unused pages, unpatched flaws, unprotected files and directories, etc. to gain unauthorized access to or knowledge of the system. The system could be completely compromised without the owner knowing it. All data could be stolen or modified slowly over time. Perpetrators could be anonymous external attackers, users with their own accounts that may attempt to compromise the system, or insiders wanting to disguise their actions. 5.2. Is My Organisation Vulnerable to Application Security Misconfiguration? We should check that the organisation has performed the proper security hardening across the entire application stack. Does my organisation have a process for keeping all software up to date? This includes the OS, Web/App Server, DBMS, applications, and all code libraries. Is everything unnecessary disabled, removed, or not installed (e.g. ports, services, pages, accounts, privileges)? Are default account passwords changed or disabled? Is my organisation system error handling set up to prevent stack traces and other overly informative error messages from leaking? Are the security settings in the my organisation development frameworks and libraries understood and configured properly? A concerted, repeatable process is required to develop and maintain a proper application security configuration. 5.3. Application Security Misconfiguration Examples: Scenario #1: The application relies on a powerful framework like Struts or Spring. XSS flaws are found in these framework components. An update is released to fix these flaws but the libraries are not updated. Until the libraries are updated, attackers can easily find and exploit these flaws in the application. Scenario #2: The application server admin console is automatically installed and not removed. Default accounts aren’t 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 a server. Attackers discover they can simply list directories to find any file. The attackers find and download all the compiled Java classes, which they reverse engineer to get all the custom code. The attackers then find a serious access control flaw in an 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. 5.4. Defences for Application Security Misconfiguration Developers and network administrators need to work together to ensure that the entire stack is configured properly. Automated scanners are useful for detecting missing patches, misconfigurations, use of default accounts, unnecessary services, etc. The primary recommendations are to establish all of the following: © Copyright Test and Verification Solutions Ltd. 2014 Page 23 Application Security Development Guidelines 1. A repeatable hardening process that makes it fast and easy to deploy another environment that is properly locked down. Development, QA, and production environments should all be configured identically. This process should be automated to minimize the effort required to setup a new secure environment. 2. A process for keeping abreast of and deploying all new software updates and patches in a timely manner to each deployed environment. This needs to include all code libraries. 3. A strong application architecture that provides good separation and security between components. 4. Consider running scans and doing audits periodically to help detect future misconfigurations or missing patches. Often analysis of the infrastructure and topology architecture can reveal a great deal about a web application. Information such as source code, HTTP methods permitted, administrative functionality, authentication methods, and infrastructural configurations can be obtained. Minimize this exposure! The file extensions present in a web server or a web application make it possible to identify the technologies which compose the target application, e.g. jsp and asp extensions. File extensions can also expose additional systems connected to the application. Avoid this! Redundant, readable and downloadable files on a web server, such as old, backup and renamed files, are a big source of information leakage. It is necessary to verify the presence of these files because they may contain parts of source code, installation paths as well as passwords for applications and/or databases. Minimize this! Many applications use a common path for administrative interfaces which can be used to guess or brute force administrative passwords. Avoid this! 6. Guidelines for Preventing Sensitive Data Exposure 6.1. What is Sensitive Data Exposure? Source: OWASP Protecting sensitive data with cryptography has become a key part of most web applications. Simply failing to encrypt sensitive data is very widespread. Applications that do encrypt frequently contain poorly designed cryptography, either using inappropriate ciphers or making serious mistakes using strong ciphers. These flaws can lead to disclosure of sensitive data and compliance violations. The most common flaw is simply not encrypting data that deserves encryption. When encryption is employed, unsafe key generation and storage, not rotating keys and weak algorithm usage is common. Use of weak or unsalted hashes to protect passwords is also common. External attackers have difficulty detecting such flaws due to limited access. They usually must exploit something else first to gain the needed access. Applications frequently do not protect network traffic. They may use SSL/TLS during authentication, but not elsewhere, exposing data and session IDs to interception. Expired or improperly configured certificates may also be used. Page 24 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines 6.2. Is My Organisation vulnerable to Sensitive Data Exposure? All web application frameworks are vulnerable to insecure cryptographic storage. Would anyone (including internal administrators) like to gain access to protected data they aren’t authorized for? Preventing cryptographic flaws takes careful planning. The most common problems are: 6.3. Not encrypting sensitive data everywhere it is stored, including backups; Using home grown algorithms; Insecure use of strong algorithms; Continued use of proven weak algorithms; Hard coding keys, and storing keys in unprotected stores. Not using SSL to protect all authentication related traffic. Not ensuring SSL is used for all resources on all private pages and services. This would protect all data and session tokens that are exchanged. Mixed SSL on a page should be avoided since it causes user warnings in the browser, and may expose the user’s session ID. Not ensuring all session cookies have their ‘secure’ flag set so the browser never transmits them in the clear. Not verifying the server certificate is legitimate and properly configured for that server. This includes being issued by an authorized issuer, not expired, has not been revoked, and it matches all domains the site uses. Examples of Sensitive Data Exposure Example scenario #1: A site simply doesn’t use SSL for all pages that require authentication. Attacker simply monitors network traffic (like an open wireless or their neighbourhood cable modem network), and observes an authenticated victim’s session cookie. Attacker then replays this cookie and takes over the user’s session. Example 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 site’s customers lures them to a lookalike site which doesn’t 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. Example scenario #3: A site simply uses standard ODBC/JDBC for the database connection, not realizing all traffic is in the clear. 6.4. Defences for Preventing Sensitive Data Exposure The most important aspect is to ensure that everything that should be encrypted is actually encrypted. Then you must ensure that the cryptography is implemented properly. Do not create cryptographic algorithms. Only use approved public algorithms such as AES, RSA public key cryptography, and SHA-256 or better for hashing. Do not use weak algorithms, such as MD5 / SHA1. Favor safer alternatives, such as SHA-256 or better. Generate keys offline and store private keys with extreme care. Never transmit private keys over insecure channels © Copyright Test and Verification Solutions Ltd. 2014 Page 25 Application Security Development Guidelines Ensure that infrastructure credentials such as database credentials or MQ queue access details are properly secured (via tight file system permissions and controls), or securely encrypted and not easily decrypted by local or remote users Ensure that encrypted data stored on disk is not easy to decrypt. For example, database encryption is worthless if the database connection pool provides unencrypted access. Providing proper transport layer protection can affect the site design. It’s easiest to require SSL for the entire site. For performance reasons, some sites use SSL only on private pages. Others use SSL only on ‘critical’ pages, but this can expose session IDs and other sensitive data. At a minimum, do all of the following: Require SSL for all sensitive pages. Non-SSL requests to these pages should be redirected to the SSL page. Set the ‘secure’ flag on all sensitive cookies. Configure your SSL provider to only support strong (e.g., FIPS 140-2 compliant) algorithms. Ensure your certificate is valid, not expired, not revoked, and matches all domains used by the site. Backend and other connections should also use SSL or other encryption technologies. Further protection may be provided by applying the following defences: https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet https://www.owasp.org/index.php/Cryptographic_Storage_Cheat_Sheet 7. Guidelines for Missing Function Level Access Control 7.1. What is Missing Function Level Access Control? Source: OWASP Frequently, the only protection for a URL is that links to that page are not presented to unauthorized users. However, a motivated, skilled, or just plain lucky attacker may be able to find and access these pages, invoke functions, and view data. Security by obscurity is not sufficient to protect sensitive functions and data in an application. Access control checks must be performed before a request to a sensitive function is granted, to ensure the user is authorized to access that function. The primary attack method for this vulnerability is called "forced browsing", which encompasses guessing links and brute force techniques to find unprotected pages. Applications frequently allow access control code to evolve and spread throughout a code-base, resulting in a complex model that is difficult to understand for developers and security specialists alike. This complexity makes it likely that errors will occur and pages will be missed, leaving them exposed. 7.2. Is My Organisation Vulnerable to Missing Function Level Access Control? The best way to find out if an application has failed to properly restrict function level access is to verify every application function: 1. Does the UI show navigation to unauthorized functions? Page 26 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines 2. Are server side authentication or authorization checks missing? 3. Are server side checks done that solely rely on information provided by the attacker? Using a proxy, browse your application with a privileged role. Then revisit restricted pages using a less privileged role. If the server responses are alike, the application is probably vulnerable. Some testing proxies directly support this type of analysis. You can also check the access control implementation in the code. Try following a single privileged request through the code and verifying the authorization pattern. Then search the codebase to find where that pattern is not being followed. Automated tools are unlikely to find these problems. 7.3. Examples of Missing Function Level Access Control Scenario 1: The attacker simply force-browses to target URLs. The following URLs 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 an unauthenticated user can access either page, that’s a flaw. If an authenticated, non-admin, user is allowed to access the admin_getappInfo page, this is also a flaw, and may lead the attacker to more improperly protected admin pages. Scenario 2: A page provides an 'action' parameter to specify the function being invoked, and different actions require different roles. If these roles aren’t enforced, that’s a flaw. 7.4. Defences for Missing Function Level Access Control The goal is to verify that access control is enforced consistently in the presentation layer and the business logic for all URLs in the application. Taking the time to plan authorization by creating a matrix to map the roles and functions of the application is a key step in achieving protection against unrestricted URL access. Web applications must enforce access control on every URL and business function. It is not sufficient to put access control into the presentation layer and leave the business logic unprotected. It is also not sufficient to check once during the process to ensure the user is authorized, and then not check again on subsequent steps. Otherwise, an attacker can simply skip the step where authorization is checked, and forge the parameter values necessary to continue on at the next step. Enabling URL access control takes some careful planning. Among the most important considerations: Ensure the access control matrix is part of the business, architecture, and design of the application Ensure that all URLs and business functions are protected by an effective access control mechanism that verifies the user’s role and entitlements prior to any processing taking place. Make sure this is done during every step of the way, not just once towards the beginning of any multi-step process Pay close attention to include/library files, especially if they have an executable extension such as .php. Where feasible, they should be kept outside of the web root. They should verify that they are not being directly accessed, e.g. by checking for a constant that can only be created by the library’s caller Do not assume that users will be unaware of special or hidden URLs or APIs. Always ensure that administrative and high privilege actions are protected Block access to all file types that your application should never serve. Ideally, this filter would follow the "accept known good" approach and only allow file types that you intend to serve, e.g., .html, .pdf, © Copyright Test and Verification Solutions Ltd. 2014 Page 27 Application Security Development Guidelines .php. This would then block any attempts to access log files, xml files, etc. that you never intend to serve directly. Keep up to date with virus protection and patches to components such as XML processors, word processors, image processors, etc., which handle user supplied data. 8. Guidelines for Preventing Cross-Site Request Forgery (CSRF) 8.1. What is Cross-Site Request Forgery? Source: OWASP Cross-Site Request Forgery (CSRF) is an attack that tricks the victim into loading a page that contains a malicious request. It is malicious in the sense that it inherits the identity and privileges of the victim to perform an undesired function on the victim's behalf, like change the victim's e-mail address, home address, or password, or purchase something. CSRF attacks generally target functions that cause a state change on the server but can also be used to access sensitive data. For most sites, browsers will automatically include with such requests any credentials associated with the site, such as the user's session cookie, basic authentication credentials, IP address, Windows domain credentials, etc. Therefore, if the user is currently authenticated to the site, the site will have no way to distinguish this from a legitimate user request. In this way, the attacker can make the victim perform actions that they didn't intend to, such as logout, purchase item, change account information, retrieve account information, or any other function provided by the vulnerable website. Sometimes, it is possible to store the CSRF attack on the vulnerable site itself. Such vulnerabilities are called Stored CSRF flaws. This can be accomplished by simply storing an IMG or IFRAME tag in a field that accepts HTML, or by a more complex cross-site scripting attack. If the attack can store a CSRF attack in the site, the severity of the attack is amplified. In particular, the likelihood is increased because the victim is more likely to view the page containing the attack than some random page on the Internet. The likelihood is also increased because the victim is sure to be authenticated to the site already. Synonyms: CSRF attacks are also known by a number of other names, including XSRF, "Sea Surf", Session Riding, Cross-Site Reference Forgery, and Hostile Linking. Microsoft refers to this type of attack as a OneClick attack in their threat modeling process and many places in their online documentation. Since browsers send credentials like session cookies automatically, attackers can create malicious web pages which generate forged requests that are indistinguishable from legitimate ones. Attackers can cause victims to change any data the victim is allowed to change or perform any function the victim is authorized to use. The easiest way to check whether an application is vulnerable is to see if each link and form contains an unpredictable token for each user. Without such an unpredictable token, attackers can forge malicious requests. Investigation should focus on the links and forms that invoke state-changing functions, since those are the most important CSRF targets. Check multi-step transactions as they are not inherently immune. Attackers can easily forge a series of requests by using multiple tags or possibly JavaScript. Note that session cookies, source IP addresses, and other information that is automatically sent by the browser are also included in forged requests. Page 28 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines 8.2. Cross-Site Request Forgery Example: 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 victim’s account to their account, and then embeds this attack in an image request or iframe stored on various sites under the attacker’s 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 user’s session info, inadvertently authorizing the request. In this example the browser will try to display the specified zero-width (i.e., invisible) image as well. This action results in a request being automatically sent to the web application hosted on the site. It is not important that the image URL does not refer to a proper image, its presence will trigger the request specified in the imgsrc field anyway; this happens provided that image download is not disabled in the browsers, which is a typical configuration. 8.3. Defences for Cross-Site Request Forgery Checking the referrer in the client's HTTP request will prevent CSRF attacks. By ensuring the HTTP requests have come from the original site means that the attacks from other sites will not function. Audit the application to ascertain if its session management is vulnerable. If session management relies only on client side values (information available to the browser); then the application is vulnerable. “Client side values” are cookies and HTTP authentication credentials (Basic Authentication and other forms of HTTP authentication; NOT form-based authentication, which is an application-level authentication). For an application to not be vulnerable, it must include session-related information in the URL, in a form of unidentifiable or unpredictable by the user. Resources accessible via HTTP GET requests are easily vulnerable, though POST requests can be automated via Javascript and are vulnerable as well; therefore, the use of POST alone is not enough to correct the occurrence of CSRF vulnerabilities. Synchronizer Token Pattern In order to facilitate a "transparent but visible" CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern http://www.corej2eepatterns.com/Design/PresoDesign.htm. The synchronizer token pattern requires the generating of random "challenge" tokens that are associated with the user's current session. These challenge tokens are then inserted within the HTML forms and links associated with sensitive server-side operations. When the user wishes to invoke these sensitive operations, the HTTP request should include this challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. Inclusion of a required security token in HTTP requests associated with sensitive business functions helps mitigate CSRF attacks as successful exploitation assumes the attacker knows the randomly generated token for the target victim's session. This is analogous to the attacker being able to guess the target victim's session identifier. The following synopsis describes a general approach to incorporate challenge tokens within the request. When a Web application formulates a request (by generating a link or form that causes a request when submitted or clicked by the user), the application should include a hidden input parameter with a common name such as "CSRFToken". The value of this token must be randomly generated such that it cannot be © Copyright Test and Verification Solutions Ltd. 2014 Page 29 Application Security Development Guidelines guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token. <form action="/transfer.do" method="post"> <input type="hidden" name="CSRFToken" value="OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZ jMTViMGYwMGEwOA=="> … </form> In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session and is utilized for each subsequent request until the session expires. When a request is issued by the end-user, the server-side component must verify the existence and validity of the token in the request as compared to the token found in the session. If the token was not found within the request or the value provided does not match the value within the session, then the request should be aborted, token should be reset and the event logged as a potential CSRF attack in progress. To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the "Back" button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS. Disclosure of Token in URL Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This may be implemented as a result of sensitive server-side operations being invoked because of embedded links in the page or other general design patterns. These patterns could be implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In JavaEE web applications, however, HTTP method scoping is seldom utilized when retrieving HTTP parameters from a request. Calls to "HttpServletRequest.getParameter" will return a parameter value regardless if it was a GET or POST. This is not to concede that HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class, or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost. In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required: 1. The victim must be interacting with the application such that a valid CSRF token is generated. Page 30 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines 2. The CSRF token must be transmitted in a GET request by interacting with the web page 3. A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server 4. This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.) 5. The attacker must parse this repository and retrieve the token. 6. The attacker needs to somehow know what user owns this exposed CSRF token 7. The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document. 8. The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.). While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business. Double Submit Cookies Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. The first is sent as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An attacker cannot read any data sent from the server or modify cookie values, per the same-origin policy. This means that while an attacker can send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value. While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article: Direct Web Remoting (DWR) © Copyright Test and Verification Solutions Ltd. 2014 Page 31 Application Security Development Guidelines Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently. 9. Guidelines for Components with Known Vulnerabilities 9.1. What are Known Vulnerable Components? Source: OWASP Some vulnerable components (e.g., framework libraries) can be identified and exploited with automated tools, expanding the threat agent pool beyond targeted attackers to include chaotic actors. The attacker identifies a weak component through scanning or manual analysis. He/she customizes the exploit as needed and executes the attack. It gets more difficult if the used component is deep in the application. The full range of weaknesses is possible, including injection, broken access control, XSS, etc. The impact could range from minimal to complete host takeover and data compromise. 9.2. Is My Organisation vulnerable to Using Components with Known Vulnerabilities? According to OWASP, virtually every application has these issues because most development teams don’t focus on ensuring their components/libraries are up to date. In many cases, the developers don’t even know all the components they are using, never mind their versions. Component dependencies make things even worse. In theory, it ought to be easy to discover if an organisation is currently using any vulnerable components or libraries. Unfortunately, vulnerability reports do not always specify exactly which versions of a component are vulnerable in a standard, searchable way. Further, not all libraries use an understandable version numbering system. Finally, not all vulnerabilities are reported to a central clearinghouse that is easy to search, although sites like CVE and NVD are becoming easier to search. Determining if an organisation is vulnerable requires searching these databases, as well as keeping abreast of project mailing lists and announcements for anything that might be a vulnerability. If one of the components does contain a vulnerability, you should carefully evaluate whether your implementation is actually vulnerable by checking to see if your code uses the part of the component with the vulnerability, and whether the flaw could result in an impact an organisation would care about. 9.3. Examples of Using Components with Known Vulnerabilities: Component vulnerabilities can cause almost any type of risk imaginable, ranging from the trivial to sophisticated malware designed to target a specific organization. Components almost always run with the full privilege of the application, so flaws in any component can be serious, The following two vulnerable components were downloaded 22m times in 2011. Apache CXF Authentication Bypass – By failing to provide an identity token, attackers could invoke any web service with full permission. (Apache CXF is a services framework, not to be confused with the Apache Application Server.) Page 32 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines Spring Remote Code Execution – Abuse of the Expression Language implementation in Spring allowed attackers to execute arbitrary code, effectively taking over the server. Every application using either of these vulnerable libraries is vulnerable to attack as both of these components are directly accessible by application users. Other vulnerable libraries, used deeper in an application, may be harder to exploit. 9.4. Defences for Using Components with Known Vulnerabilities: Upgrading to new component versions that fix known vulnerabilities is critical. Software projects should have a process in place to: 1. Identify all components and the versions being used, including all dependencies. (e.g., the versions plugin). 2. Monitor the security of these components in public databases, project mailing lists, and security mailing lists, and keep them up to date. 3. Establish security policies governing component use, such as requiring certain software development practices, passing security tests, and acceptable licenses. 4. Where appropriate, consider adding security wrappers around components to disable unused functionality and/ or secure weak or vulnerable aspects of the component. Verifying the processes described above are in place is a recommended Quality Control activity. More information is available here: https://docs.eudra.org/webtop/drl/objectId/090142b28240b262 10. Guidelines for Preventing Un-validated Redirects and Forwards 10.1. What are Un-validated Redirects and Forwards? Source: OWASP Applications frequently redirect users to other pages, or use internal forwards in a similar manner. Sometimes the target page is specified in an un-validated parameter, allowing attackers to choose the destination page. An attacker links to an un-validated redirect and tricks victims into clicking it. Victims are more likely to click on it, since the link is to a valid site. The attacker targets unsafe forward to bypass security checks. Such redirects may attempt to install malware or trick victims into disclosing passwords or other sensitive information. Unsafe forwards may allow access control bypass. 10.2. Is My Organisation vulnerable to Un-validated Redirects and Forwards? The best way to find out if an application has any un-validated redirects or forwards is to: 1. Review the code for all uses of redirect or forward (called a transfer in .NET). For each use, identify if the target URL is included in any parameter values. If so, verify the parameter(s) are validated to contain only an allowed destination, or element of a destination. © Copyright Test and Verification Solutions Ltd. 2014 Page 33 Application Security Development Guidelines 2. Also, spider the site to see if it generates any redirects (HTTP response codes 300-307, typically 302). Look at the parameters supplied prior to the redirect to see if they appear to be a target URL or a piece of such a URL. If so, change the URL target and observe whether the site redirects to the new target. 3. If code is unavailable, check all parameters to see if they look like part of a redirect or forward URL destination and test those that do. 10.3. Examples of Un-validated Redirects and Forwards Scenario 1: An application has a page called “redirect.jsp” which takes a single parameter named “url”. The attacker crafts a malicious URL redirecting users to a malicious site that performs phishing and installs malware. http://www.example.com/redirect.jsp?url=evil.com Scenario 2: An application uses forward to route requests between different parts of a site. To facilitate this action, 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 application’s access control check and forward the attacker to an administrative function that they would not normally be able to access. http://www.example.com/boring.jsp?fwd=admin.jsp 10.4. Defences for Un-validated Redirects and Forwards Safe use of redirects and forwards can be done in a number of ways: 1. Simply avoid using redirects and forwards. 2. If used, don’t involve user parameters in calculating the destination. This can usually be done. 3. If destination parameters can’t be avoided, ensure that the supplied value is valid, and authorized for the user. It is recommended that any such destination parameters be a mapping value, rather than the actual URL or portion of the URL, and that server side code translate this mapping to the target URL. Applications can use ESAPI to override the sendRedirect() method to make sure all redirect destinations are safe. Avoiding such flaws is extremely important as they are a favourite target of phishers trying to gain the user’s trust. Page 34 © Copyright Test and Verification Solutions Ltd. 2014 Application Security Development Guidelines 11. About This Document 11.1. Referenced documents Title Locator Open Web Application Security Project https://www.owasp.org/index.php/Main_Page Oracle Frequently Asked Questions http://www.orafaq.com/wiki/SQL_FAQ#How_does_one_e scape_special_characters_when_writing_SQL_queries.3F Writing Secure Code by Howard & LeBlanc Information security management http://www3.open.ac.uk/study/postgraduate/course/m88 6.htm Black Box Penetration Test http://www.comsecglobal.com/Services.aspx Broken Authentication and Session Management https://www.owasp.org/index.php/Broken_Authentication _and_Session_Management Data validation http://en.wikipedia.org/wiki/Data_validation Watch for Authentication Bypass Vulnerabilities http://www.enterprisenetworkingplanet.com/netsecur/arti cle.php/3916331/Watch-for-Authentication-BypassVulnerabilities.htm Strong typing http://en.wikipedia.org/wiki/Stronglytyped_programming_language Black Box Security Testing Tools https://buildsecurityin.uscert.gov/bsi/articles/tools/black-box/261-BSI.html What is iRisk? http://community.securestate.com/index.php?title=What _is_iRisk%3F&goback=%2Egde_36874_member_179490 322 Stopping SQL Injection and Crossing Over Cross-site Scripting by Manoranjan Paul http://securitymasala.files.wordpress.com/2007/11/mano _paul_sqlinjandxss_catalyst_eu.pdf Excess XSS by Jakob Kallin and Irene Lobo Valbuena http://excess-xss.com/ Document history Version Who Date What 1.0 Declan O’Riordan 26/02/2014 Initial version for distribution to anyone. © Copyright Test and Verification Solutions Ltd. 2014 Page 35