Web Application Security Requirements

Web Application Security Requirements ICS Security & Compliance Division This document introduces guidelines for secure programming techniques that wi...
Author: Belinda Bryant
1 downloads 3 Views 603KB Size
Web Application Security Requirements ICS Security & Compliance Division This document introduces guidelines for secure programming techniques that will help developers build an appropriate level of protection into Church applications.

LDS Church 3/22/2010 Version 0.4

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Contents Executive Summary....................................................................................................................................... 4 Introduction .................................................................................................................................................. 4 Data Validation ............................................................................................................................................. 5 Input Validation ........................................................................................................................................ 5 White List Regex Examples: .................................................................................................................. 5 Java Regex Usage Example: .................................................................................................................. 6 Output Encoding ....................................................................................................................................... 6 Use ESAPI Encoding............................................................................................................................... 6 Java: Use Struts output mechanisms. ................................................................................................... 7 .NET: Use the Microsoft Anti-XSS Library ............................................................................................. 7 PHP: Ensure output is passed through htmlentities() or htmlspecialchars()........................................ 7 Parameterized Queries ............................................................................................................................. 7 Java “Vulnerable” Example ................................................................................................................... 7 Java “Safe” Example .............................................................................................................................. 7 C# .NET “Safe” Example ........................................................................................................................ 8 Authentication .............................................................................................................................................. 9 Usernames & Passwords........................................................................................................................... 9 Administrative Interfaces:......................................................................................................................... 9 Transport Encryption ................................................................................................................................ 9 Session Invalidation .................................................................................................................................. 9 Session Timeout ........................................................................................................................................ 9 User Enumeration ................................................................................................................................... 10 Sensitive URL Portions ............................................................................................................................ 10 Password Autocomplete ......................................................................................................................... 10 Authorization .............................................................................................................................................. 11 Role Based Access Control ...................................................................................................................... 11 Least Privilege ......................................................................................................................................... 11 Audit Logging .......................................................................................................................................... 11 2

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE Restrict URL Access ................................................................................................................................. 11 Parameter Tampering: ............................................................................................................................ 11 Configuration Management........................................................................................................................ 12 Path Traversal on Object References ...................................................................................................... 12 Vulnerable Example ............................................................................................................................ 12 Directory Browsing.................................................................................................................................. 12 Code Comments...................................................................................................................................... 12 HTTP Methods......................................................................................................................................... 12 Secure Server Configuration: .................................................................................................................. 12 Secure Database Configuration: ............................................................................................................. 12 Patch Management ................................................................................................................................. 12 Data Protection ........................................................................................................................................... 13 Secure Disposal ....................................................................................................................................... 13 Cached Data ............................................................................................................................................ 13 Cryptographic Algorithms ....................................................................................................................... 13 Key Management .................................................................................................................................... 13 Error Reporting ....................................................................................................................................... 13 Session Management .................................................................................................................................. 14 Session IDs: ............................................................................................................................................. 14 Session Management:............................................................................................................................. 14 Good Example: .................................................................................................................................... 14 Secure Cookies ........................................................................................................................................ 14 Authorization/Role Data ......................................................................................................................... 14 Conclusion ................................................................................................................................................... 15 Appendix A: Terms and Definitions ............................................................................................................ 16 Appendix B: Additional Resources .............................................................................................................. 17 Works Cited ................................................................................................................................................. 18

3

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Executive Summary This document contains specific guidance for securely coding Church applications. Adhering to the guidance will protect Church and customer data and facilitate alignment with Church information security policies. Threats to applications are real and exploited vulnerabilities have been observed. Successful defenses require adopting the principles that follow.

Introduction Secure programming practices are essential to protecting an organization against current and future threats. It is here that security can have the most significant impact, by employing principles that reduce the number and severity of possible attacks against an application. By identifying coding practices with known exploits and following recommended guidelines, development teams can substantially reduce the number of security vulnerabilities in production applications. (CERT) This document provides a list of fundamental secure coding practices in the form of security requirements. These requirements are based on Church IT policies, industry best practices and recommendations from the Open Web Application Security Project (OWASP). Those responsible for designing and maintaining Church-owned web applications should become familiar with and apply the recommendations outlined in this document. One of the key principles of successful application defense is that the application must regard the client as a potentially hostile entity. Request tampering, social engineering, hijacked computers, and reflected attacks change the way that applications should treat input. Developers should plan accordingly to address these issues. Please see the Additional Resources section for additional secure coding information.

4

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Data Validation Data Validation techniques counter identity spoofing, tampering, repudiation, information disclosure, and elevation of privilege attacks. Validating input and output information is one of the most effective means of protecting a website as it directly affects communications between the client and the web application.

Input Validation Input validation techniques ensure that data entered by the client fall within accepted parameters. The following are methods used to implement input validation: Use strong input validation mechanism to check and validate all input data for length, type, syntax and business rules before input data is processed Ensure that final validation of input is performed server-side. Do not rely strictly on client-side validation If possible, adopt an “accept known good” or ‘white list’ approach At a minimum, ensure that dangerous characters are URL encoded or blocked (e.g. &, , “, ‘, and /) Ensure that canonicalization occurs before validation. Canonicalization refers to the process of standardizing or normalizing communications.

The following OWASP examples provide commonly used cases of ‘white list’ regular expressions (OWASP): White List Regex Examples: Validating Data from Free Form Text Field for Zip Code (5 digits and optional plus 4) ^\d{5}(\d{4})?$ Validating Data from Fixed List Drop-Down Box For U.S. State Selection ^(AA|AE|AP|AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|M E|MH|MD|MA|MI|MN|MS| MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT |VI|VA|WA|WV|WI|WY)$ Validating a Free Form Text Field for allowed chars (numbers, letters, whitespace, .-_) ^[a-zA-Z0-9\s\.\-_]+$ (Any number of characters) ^[a-zA-Z0-9\s\.\-_]{1-100}$ (This is better, since it limits this field to 1 to 100 characters) 5

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE Note: \s matches any whitespace character (i.e., space, tab, carriage return, or linefeed, [ \t\r\n]) Additional Examples are available at the OWASP Validation Regex Repository (http://www.owasp.org/index.php/OWASP_Validation_Regex_Repository) Java Regex Usage Example: Example validating the parameter “zip” using a regular expression. private static final Pattern zipPattern = Pattern.compile("^\d{5}(-\d{4})?$"); public void doPost( HttpServletRequest request, HttpServletResponse response) { try { String zipCode = request.getParameter( "zip" ); if ( !zipPattern.matcher( zipCode ).matches() { throw new YourValidationException( "Improper zipcode format." ); } .. do what you want here, after its been validated .. } catch(YourValidationException e ) { response.sendError( response.SC_BAD_REQUEST, e.getMessage() ); } }

Output Encoding Output encoding is primarily used to defend against Cross-Site Scripting (XSS) attacks. It involves a standardized way of escaping output to prevent user supplied code from executing improperly. Use strong output encoding to ensure that all user input is entity encoded before rendering for display Ensure that characters that could be used in a scripting attack (e.g. &, , “, ‘, and /) are removed or encoded

The following are language-specific recommendations to apply output encoding from OWASP: Use ESAPI Encoding ESAPI (The OWASP Enterprise Security API) greatly simplifies output encoding tasks through best practice libraries. Example Usage: Writer.println(“
Last Name: ”); 6

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE Java: Use Struts output mechanisms. Use or the default JSTL escapeXML="true" attribute in . Do NOT use unnested (that is, outside of a properly encoded output mechanism) .NET: Use the Microsoft Anti-XSS Library Version 1.5 is freely available from MSDN. Do not assign form fields data directly from the Request ( object: username.Text = Request.QueryString("username"); ) without using this library. Understand which .NET controls automatically encode output data PHP: Ensure output is passed through htmlentities() or htmlspecialchars() Evaluate the soon to be released OWASP PHP Anti-XSS library. Disable register_globals if it is not already disabled (OWASP)

Parameterized Queries Parameterized queries protect against SQL injection attacks by creating structured queries that limit the scope of the command and create boundaries around escape sequences. Use parameterized queries or parameterized stored procedures to prevent user-supplied input from being directly executed in queries. Here are some examples from the OWASP SQL Injection Prevention Cheat Sheet:

Java “Vulnerable” Example The following code is vulnerable to SQL injection because it accepts a non-validated string from the user and passes it into the query. string query = "SELECT account_balance FROM user_data WHERE user_name = " + request.getParameter("customerName"); try { Statement statement = connection.createStatement( … ); ResultSet results = statement.executeQuery( query ); } To correct, follow one of the following examples: Java “Safe” Example String selectStatement = "SELECT * FROM User WHERE userId = ?”; PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, userID); ResultSet rs = prepStmt.executeQuery();

7

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE C# .NET “Safe” Example string query = "SELECT account_balance FROM user_data WHERE user_name = ?"; try { OleDbCommand command = new OleDbCommand(query, connection); command.Parameters.Add(new OleDbParameter("customerName", CustomerName Name.Text)); OleDbDataReader reader = command.ExecuteReader(); // … } catch (OleDbException se) { // error handling } (OWASP)

8

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Authentication Good authentication techniques counter identity spoofing, tampering, repudiation, information disclosure, and elevation of privilege attacks. It is one of the most visible and targeted aspects of web application security.

Usernames & Passwords Use LDSAccount for authentication wherever possible Ensure that passwords meet Church policy requirements Ensure the system does not have shared accounts (administrative or otherwise) Ensure that accounts are locked after no more than 6 incorrect attempts Publically accessible applications should require new passwords on a periodic basis Ensure that usernames do not default to known values (i.e. partial or full email addresses, first initial+last name) Allow the user to specify a username and validate that it does not match the email address on record for the account New accounts should default to no-privilege or low-privilege

Administrative Interfaces: Ensure the system does not have publicly accessible administrative interfaces (i.e. Apache Tomcat’s Manager, custom developed administrative interfaces, etc.).

Transport Encryption: Ensure that all authenticated portions of the application use TLS v1.2 or SSL v3. Ensure that the application infrastructure will not accept connections using older SSL or TLS versions with known security vulnerabilities. Do not pass usernames and passwords unencrypted.

Session Invalidation: Ensure that every authenticated page has a logout link which destroys all server side session state and client side cookies. Logout functionality should not require additional human intervention (e.g. closing browser window or clicking ok/cancel).

Session Timeout: Use a session timeout period to automatically log out an inactive session. The inactivity threshold should be consistent with the value of the data or application it protects (shorter timeout periods are more secure). Session timeouts in excess of 60 minutes should not be used. 9

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

User Enumeration: Ensure that feedback from the authentication mechanism does not reveal whether or not a username is valid. This feedback may manifest itself in many forms including the following: Error messages (e.g. instead of “Invalid username” use “Invalid username or password”) Processing time (e.g. invalid user accounts receive error messages immediately but valid user accounts take longer for the error message to display.) Information rich URLs or URL redirections http://site.com/err.jsp?User=baduser&error=0 http://site.com/err.jsp?User=gooduser&error=2)

Sensitive URL Portions: Do not expose session identifiers, username, or password in the URL or logs. Use POST requests for sensitive data or to perform sensitive value transactions. Example: http://site.com/query?ssn=111-22-3333

Password Autocomplete: Do not implement “remember my password” mechanisms. Set the autocomplete property for all password fields to off. Example:

10

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Authorization Appropriate authorization architectures will counter identity spoofing, tampering, repudiation, information disclosure, and elevation of privilege attacks. Proper authorization techniques require that users access only the information that is appropriate for their role.

Role Based Access Control: Implement strong, server-side Role Based Access Control (RBAC) mechanisms to prevent unauthorized access to sensitive data. After authentication, do not place user credentials (or similar) in the URL, in POST parameters, or in cookie parameters even if they have been encrypted. Ensure that users having privileged access are audited from time to time.

Least Privilege: Ensure that database connection accounts are granted the least amount of privileges necessary to the fewest number of resources (e.g. tables/columns) required for the task.

Audit Logging: Implement sufficient logging to detect abuse and misuse of data and privileges. Restrict URL Access: Ensure that administrative or high privilege actions are protected using strong access control mechanisms. Do not rely strictly on hidden URLs or form fields. Authorization checks should occur for each protected page.

Parameter Tampering: Ensure that persons cannot gain access to restricted data by manipulating parameters in the URL, post parameters, or cookies. Bad Example: http://site.com/access.php?user=normal

11

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Configuration Management Proper patching and resource configuration is critical to the security of the entire application and affects all threat vectors.

Path Traversal on Object References: To protect against path traversal vulnerabilities, avoid exposing private object references (e.g. primary keys or filenames) to users whenever possible. When this is not possible, ensure that private object references are validated extensively with an “accept known good” approach. For example, the following code could be attacked using a string such as “../../../../etc/passwd%00” to gain unauthorized access to the /etc/passwd file: Vulnerable Example: Français … require_once ($_REQUEST['language’]."lang.php"); (OWASP)

Directory Browsing: Ensure that web server directory browsing and relative paths (../) are not allowed.

Code Comments: Ensure that comments which reveal information about the application or infrastructure are removed from client-side, production code.

HTTP Methods: Disable the TRACE, OPTIONS, CONNECT, PUT and DELETE, or other custom/developer defined HTTP methods on web servers.

Secure Server Configuration: Ensure the public facing web servers and application servers have been securely configured based on an industry recognized standard.

Secure Database Configuration: Ensure the database servers have been securely configured based on an industry recognized standard.

Patch Management: Ensure that application and database components are regularly evaluated for new security vulnerabilities. Appropriate patches must be applied at least quarterly.

12

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Data Protection Sensitive data is often the target of an attacker’s attention and should be properly safeguarded throughout its lifecycle. Developers and application designers should consider data protection techniques anywhere information is stored, processed, or transmitted.

Secure Disposal: Ensure that documents and storage media containing Social Security Numbers (SSN), Personally Identifiable Information (PII), Protected Health Information (PHI), or other restricted information are securely disposed of. Documents should be cross-cut shredded prior to disposal. Computers, storage components, and removable storage media that have ever contained sensitive information should be disposed of only after using a secure media sanitization technique which overwrites all addressable locations with random, non-sensitive data. (See NIST SP800-88 for further details)

Cached Data: Ensure that all pages that display sensitive information implement the ‘Cache-Control: no-cache’ and ‘Pragma: no-cache’ HTTP directives.

Cryptographic Algorithms: Use public algorithms which have been approved under FIPS 140-2 such as AES, RSA, and SHA-1 or better. (http://csrc.nist.gov/publications/fips/fips140-2/fips1402annexa.pdf)

Key Management: Ensure that private keys are encrypted and managed securely. Never transmit private keys over insecure channels. Email is not an acceptable method for private key exchange.

Error Reporting: Ensure that detailed error messages, debug information, stack traces, path information, and application vendors and versions are not displayed to the user. Replace default error pages with customized pages consistent with the application.

13

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Session Management Session attacks primarily involve value tampering to enable identity spoofing and escalation of privilege.

Session IDs: Session IDs should be large, random numbers generated by an acceptable source (ie. /dev/random or /dev/urandom on Linux systems), and have at least 50 random chars.

Session Management: New session IDs must be created and used after user authentication and destroyed on the server after session timeout or logout. User supplied session IDs must never be accepted. Sessions must never be transmitted in the URL. Good Example: // Invalidate session after successful login ((HttpServletRequest)request).getSession().invalidate(); // Create new session …

Secure Cookies: Implement the ‘domain’, ‘path’, ‘secure’ and ‘HttpOnly’ cookie attributes whenever sensitive information is passed in a cookie.

Authorization/Role Data: Ensure that authorization and role data is stored server-side.

14

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Conclusion These recommendations and examples represent proven practices for mitigating web application vulnerabilities and preventing attacks. Appropriate and consistent implementation will ensure that the Church adequately protects its resources and sensitive information. Building security into the application is the right way to do business and will enable technology to assist the Church as it spreads throughout the earth (Daniel 2: 44-45).

15

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Appendix A: Terms and Definitions Spoofing [identity]. A spoofing attack describes a situation in which a person or program masquerades as another by falsifying data and gaining access. Tampering with data. “Data tampering involves the malicious modification of data.”1 Repudiation. “Repudiation threats are associated with users who deny performing an action without other parties having any way to prove otherwise—for example, a user performs an illegal operation in a system that lacks the ability to trace the prohibited operations.”2 Information disclosure. “Information disclosure threats involve the exposure of information to individuals who are not supposed to have access to it.”3 Denial of service. “Denial of service (DoS) attacks deny service to valid users—for example, by making a Web server temporarily unavailable or unusable.“4 Elevation of privilege. “In this type of threat, an unprivileged user gains privileged access and thereby has sufficient access to compromise or destroy the entire system. Elevation of privilege threats include those situations in which an attacker has effectively penetrated all system defenses and become part of the trusted system itself….”5

1

Microsoft Developer Network. http://msdn.microsoft.com/en-us/library/ee823878(CS.20).aspx. March 2010.

2

Microsoft Developer Network. http://msdn.microsoft.com/en-us/library/ee823878(CS.20).aspx. March 2010.

3

Microsoft Developer Network. http://msdn.microsoft.com/en-us/library/ee823878(CS.20).aspx. March 2010.

4

Microsoft Developer Network. http://msdn.microsoft.com/en-us/library/ee823878(CS.20).aspx. March 2010.

5

Microsoft Developer Network. http://msdn.microsoft.com/en-us/library/ee823878(CS.20).aspx. March 2010.

16

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Appendix B: Additional Resources 1. Open Web Application Security Project (OWASP) (http://www.owasp.org) 2. Microsoft Security Developer Center (http://msdn.microsoft.com/en-us/security/default.aspx) 3. SANS (SysAdmin, Audit, Network, Security) Institute (http://www.sans.org/top25-programmingerrors/)

17

INFORMATION AND COMMUNICATION SYSTEMS

SECURITY & COMPLIANCE

Works Cited CERT. (n.d.). Secure Coding. Retrieved 06 1, 2009, from Cert Website: http://www.cert.org/securecoding/ OWASP. (n.d.). SQL Injection Prevention Cheat Sheet. Retrieved May 29, 2009, from OWASP: http://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet OWASP. (n.d.). Top 10 2007-Cross Site Scripting. Retrieved June 1, 2009, from http://www.owasp.org/index.php/Top_10_2007-A1 OWASP. (n.d.). Top 10 2007-Insecure Direct Object Reference. Retrieved May 29, 2009, from http://www.owasp.org/index.php/Top_10_2007-A4 The STRIDE Threat Model. (2010). Retrieved March 2010, from Microsoft Developer Network: http://msdn.microsoft.com/en-us/library/ee823878(CS.20).aspx

18