Secure Coding Cheat Sheet
- 1 DRAFT CHEAT SHEET - WORK IN PROGRESS
- 2 Introduction
- 3 How To Use This Document
- 4 Secure Coding Policy
- 5 Authentication
- 6 Session Management
- 7 Access Control
- 8 Input Data Validation
- 9 Output Encoding
- 10 Secure Transmission / Network Layer security
- 11 File Uploads
- 12 Error Handling
- 13 Logging and Auditing
- 14 Cryptography
- 15 Cookie Management
- 16 Secure Deployment
- 17 Unvalidated Redirects and Forwards Cheat Sheet
- 18 Common Vulnerabilities
DRAFT CHEAT SHEET - WORK IN PROGRESS
The goal of this document is to create high level guideline for secure coding practices. The goal is to keep the overall size of the document condensed and easy to digest. Individuals seeking addition information on the specific areas should refer to the included links to learn more.
How To Use This Document
The information listed below are generally acceptable secure coding practices; however, it is recommend that organizations consider this a base template and update individual sections with secure coding recommendations specific to the organization's policies and risk tolerance.
Secure Coding Policy
Always maintain a secure coding policy. List down the activities that are related to maintenance of secure coding standards (would these standards be technology specific or technology agnostic), feedback of code review output to training, input data validation, output data validation etc
Why should you be having a secure coding policy? It helps in maintaining consistency across organisation and helps in vertical and horizontal scaling of usage of standards for web development projects.
For more information on password complexity, please see https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Implement_Proper_Password_Strength_Controls.
Input Data Validation
Preventing XSS and Content Security Policy
- All user data controlled must be encoded when returned in the html page to prevent the execution of malicious data (e.g. XSS). For example <script> would be returned as <script>
Detailed information on XSS prevention here: OWASP XSS Prevention Cheat Sheet
Preventing SQL Injection
- It's not realistic to always know if a piece of data is user controlled, therefore parameterized queries should be used whenever a method/function accepts data and uses this data as part of the SQL statement.
- String concatenation to build any part of a SQL statement with user controlled data creates a SQL injection vulnerability.
- Parameterized queries are a guaranteed approach to prevent SQL injection.
Further Reading: SQL Injection Prevention Cheat Sheet
Preventing OS Injection
- Avoid sending user controlled data to the OS as much as possible
- Ensure that a robust escaping routine is in place to prevent the user from adding additional characters that can be executed by the OS ( e.g. user appends | to the malicious data and then executes another OS command). Remember to use a positive approach when constructing escaping routinges. Example
Further Reading: Reviewing Code for OS Injection
Preventing XML Injection
- In addition to the existing input validation, define a positive approach which escapes/encodes characters that can be interpreted as xml. At a minimum this includes the following: < > " ' &
- If accepting raw XML then more robust validation is necessary. This can be complex. Please contact the infrastructure security team for additional discussion
Secure Transmission / Network Layer security
- Use input validation to ensure the uploaded filename uses an expected extension type
- Ensure the uploaded file is not larger than a defined maximum file size
- Use a new filename to store the file on the OS. Do not use any user controlled text for this filename or for the temporary filename.
- Store all user uploaded files on a separate domain (e.g. mozillafiles.net vs mozilla.org). Archives should be analyzed for malicious content (anti-malware, static analysis, etc)
Public Serving of Uploaded Content
- Ensure the image is served with the correct content-type (e.g. image/jpeg, application/x-xpinstall)
Beware of "special" files
- The upload feature should be using a whitelist approach to only allow specific file types and extensions. However, it is important to be aware of the following file types that, if allowed, could result in security vulnerabilities.
- "crossdomain.xml" allows cross-domain data loading in Flash, Java and Silverlight. If permitted on sites with authentication this can permit cross-domain data theft and CSRF attacks. Note this can get pretty complicated depending on the specific plugin version in question, so its best to just prohibit files named "crossdomain.xml" or "clientaccesspolicy.xml".
- ".htaccess" and ".htpasswd" provides server configuration options on a per-directory basis, and should not be permitted. See http://en.wikipedia.org/wiki/Htaccess
- Use image rewriting libraries to verify the image is valid and to strip away extraneous content.
- Set the extension of the stored image to be a valid image extension based on the detected content type of the image from image processing (e.g. do not just trust the header from the upload).
- Ensure the detected content type of the image is within a list of defined image types (jpg, png, etc)
Typical types of errors: • The result of business logic conditions not being met. • The result of the environment wherein the business logic resides fails. • The result of upstream or downstream systems upon which the application depends fail. • Technical hardware / physical failure.
To address these errors:
- Ensure that all method/function calls that return a value have proper error handling and return value checking
- Ensure that exceptions and error conditions are properly handled
- Ensure that no system errors can be returned to the user
- Ensure that the application fails in a secure manner
- Ensure resources are released if an error occurs
- Ensure that stack trace is not thrown to the user
- If the language in question has a finally method, use it. The finally method is always called. The finally method can be used to release resources referenced by the method that threw the exception.
This is very important. An example would be if a method gained a database connection from a pool of connections, and an exception occurred without finally, the connection object shall not be returned to the pool for some time (until the timeout). This can lead to pool exhaustion. The method finally() is called even if no exception is thrown.
Logging and Auditing
- All protocols and algorithms for authentication and secure communication should be well vetted by the cryptographic community.
- Ensure certificates are properly validated against the hostnames/users ie whom they are meant for.
- Avoid using wildcard certificates unless there is a business need for it
- Maintain a cryptographic standard to ensure that the developer community knows about the approved ciphersuits for network security protocols, algorithms, permitted use, cryptoperiods and Key Management
- Secure access to with authentication and authorisation to configuration files, directories, and resources on the host so that direct access to such artifacts is disallowed
- Use a “deny all” rule to deny access to resources on the hosts and then grant access on need basis
- In Apache HTTP server, ensure directories like WEB-INF and META-INF are protected. If permissions for a directory and subdirectories are specified in .htaccess file, ensure that it is protected using the “deny all” rule
- While using Struts framework, ensure that JSP files are not accessible directly by denying access to *.jsp files in web.xml
- Maintain a clean environment. remove files that contain source code but are not used by the application.
- Ensure production environment does not contain any source code / development tools and that the production
- Ensure environment contains only compiled code / executables.
- Remove test code / debug code (that might contain backdoors).
- Remove commented code and meta tags as they might contain sensitive data.
- If applicable, obfuscate your code to ensure that reverse engineering is avoided
Unvalidated Redirects and Forwards Cheat Sheet
Cross Site Scripting
Cross Site Request Forgery
Preventing Malicious Site Framing (ClickJacking)
- Diable all the services, ports, protocols and daemons that are not required.
- Change all the default and vendor supplied passwords
- Protect servers by grouping all similar functions into a VLAN
- White wash error messages such that no internal workings are revealed
- Prevent stack traces from leaving the container.
- Authorising access to the least amount of data/ least number of pages that is possible
Insecure Direct Object references
- Do not enable Directory Listing on your server
Concurrancy and Race Conditions
- Use a locking mechanism to lock shared resources
- Obtain a lock on shared resources before it is read
OWASP Cheat Sheets Project Homepage