Difference between revisions of "Secure Coding Cheat Sheet"

From OWASP
Jump to: navigation, search
(Access Control)
m (Add Other Cheatsheets marker for the book)
(24 intermediate revisions by 2 users not shown)
Line 1: Line 1:
= DRAFT CHEAT SHEET - WORK IN PROGRESS =
 
 
= Introduction =
 
= Introduction =
 
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.
 
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.
Line 11: Line 10:
 
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.  
 
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.  
  
= Authentication=
+
= User Authentication =
  
== User Authentication ==
+
Please see https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Utilize_Multi-Factor_Authentication
  
Authentication mechanisms
+
= Password Complexity =
 
 
Authentication can be performed by using single factor or using multifactor. Typically, single factor authentication involves one of the following:
 
 
 
1. What you know
 
 
 
2. What you have
 
 
 
3. Who you are
 
 
 
4. Where you are
 
 
 
Whereas multifactor authentication uses more than one of the above mentioned factors
 
 
 
When a user is authentication with a password and a PIN, it is still a single factor authentication, as both password and PIN are what a user has. However, if a PIN is generated off a device / soft token, then it becomes a multifactor authentication, as the PIN is generated off a device / token that you have.
 
 
 
For transactions that process "high risk" data (like credit cards, health information, personally identifiable data) use multifactor authentication
 
 
 
If you are using only client-side authentication, ensure it can not be bypassed, manipulated or misused.
 
 
 
=== User names ===
 
 
 
For authentication purposes, user names should be unique. Scenarios that process high risk / critical data choose a unique user name for the user. Eg in case of banking applications, shopping applications, applications that process personally identifiable data etc.
 
 
 
=== Password Complexity ===
 
 
 
For more information on password complexity, please see [https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Implement_Proper_Password_Strength_Controls https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Implement_Proper_Password_Strength_Controls].
 
 
 
=== Password Rotation ===
 
Password rotation should be required for privileged accounts within applications at a frequency of every 90 days
 
== Online Password Guessing and Password Attacks ==
 
Applications must defend against online password guessing attempts by one of the following methods:
 
* Account Lockout - Lock account after 5 failed password attempts
 
* Temporary Account Lockout- Temporarily lock account after 5 failed password attempts
 
* Anti-automation Captcha - Require a captcha to be successfully completed after 5 failed password attempts
 
[https://www.owasp.org/index.php/Blocking_Brute_Force_Attacks Additional Reading]
 
 
 
 
 
=== Password Reset Functions ===
 
 
 
* Where applicable use out of band verification while resetting passwords. For Example, use One Time Passwords (OTPs) sent on a registered mobile or email ids. In this process do not ask the user to enter email id / phone number as the malicious user can use it to his/her advanatage.
 
* Where possible verify the user's identity by asking security questions
 
 
 
=== Email Verification Functions ===
 
If the application requires verification of ownership of an email address then observe the following
 
* Email verification links should only satisfy the requirement of verify email address ownership and should not provide the user with an authenticated session (e.g. the user must still authenticate as normal to access the application).
 
* Email verification codes must expire after the first use or expire after 8 hours if not used.
 
=== Password Storage ===
 
* Passwords should be stored in a format, such as Bcrypt, that is resistant to high speed offline brute force attacks
 
* Password storage using hashing algorithms plus a per user salt are good, but not sufficient.
 
* Do not store passwords in code or in configuration files.
 
 
 
== Server Authentication ==
 
When using SSL / TLS, ensure that the server identity is established by following a trust chain to a known root certificate
 
 
 
Do not rely upon IP numbers or DNS names in establishing identity.
 
 
 
Ensure all internal and external connections (user and entity) go through an appropriate and adequate form of authentication.
 
 
 
Ensure that this control cannot be bypassed.
 
 
 
== Logging and Monitoring ==
 
*Ensure that all failures are logged and reviewed
 
*Ensure that all password failures are logged and reviewed
 
*Ensure that all account lockouts are logged and reviewed
 
  
 +
Please see [https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Implement_Proper_Password_Strength_Controls https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Implement_Proper_Password_Strength_Controls].
  
 
= Session Management =
 
= Session Management =
  
https://www.owasp.org/index.php/Session_Management_Cheat_Sheet
+
Please see https://www.owasp.org/index.php/Session_Management_Cheat_Sheet
 
 
== Session ID Length ==
 
* Session tokens should be 128-bit or greater
 
 
 
== Session ID Creation ==
 
* The session tokens should be handled by the web server if possible or generated via a cryptographically secure random number generator.
 
 
 
== Inactivity Time Out ==
 
* Authenticated sessions should timeout after determined period of inactivity - 15 minutes is recommended.
 
 
 
== Secure Flag ==
 
* The "Secure" flag should be set during every set-cookie. This will instruct the browser to never send the cookie over HTTP. The purpose of this flag is to prevent the accidental exposure of a cookie value if a user follows an HTTP link.
 
 
 
== HTTP-Only Flag ==
 
* The "HTTP-Only" flag should be set to disable malicious script access to the cookie values, such as the session ID
 
 
 
== Logout ==
 
* Upon logout the session ID should be invalidated on the server side and deleted on the client via expiring and overwriting the value.
 
 
 
== Logging and Monitoring ==
 
* Log all the sessions, without logging any cardholder data or personally identifiable information
 
* Monitor all logs for suspicious activities
 
 
 
  
 
= Access Control =
 
= Access Control =
  
https://www.owasp.org/index.php/Access_Control_Cheat_Sheet
+
Please see https://www.owasp.org/index.php/Access_Control_Cheat_Sheet
 
 
== Presentation Layer ==
 
* It is recommended to not display links or functionality that is not accessible to a user. The purpose is to minimize unnecessary access controls messages and minimize privileged information from being unnecessarily provided to users.
 
 
 
== Business Layer ==
 
* Ensure that an access control verification is performed before an action is executed within the system. A user could craft a custom GET or POST message to attempt to execute unauthorized functionality.
 
 
 
== Data Layer ==
 
* Ensure that an access control verification is performed to check that the user is authorized to act upon the target data. Do not assume that a user authorized to perform action X is able to necessarily perform this action on all data sets.
 
 
 
== Logging and Monitoring ==
 
* Log all access related activities
 
* Monitor and review all logs
 
  
 
= Input Data Validation =
 
= Input Data Validation =
  
https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet
+
Please see https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet
  
 
= Output Encoding =
 
= Output Encoding =
  
== Preventing XSS and Content Security Policy ==
+
Please see https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#Output_Encoding
* 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>
 
* The type of encoding is specific to the context of the page where the user controlled data is inserted. For example, HTML entity encoding is appropriate for data placed into the HTML body. However, user data placed into a script would need JavaScript specific output encoding
 
 
 
Detailed information on XSS prevention here: [http://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet 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: [http://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet 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: [http://www.owasp.org/index.php/Reviewing_Code_for_OS_Injection 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 =
 
= Secure Transmission / Network Layer security =
  
== When To Use SSL/TLS ==
+
Please see https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet#Benefits
* All points from the login page to the logout page must be served over HTTPS.
 
* Ensure that the page where a user completes the login form is accessed over HTTPS. This is in addition to POST'ing the form over HTTPS.
 
* All authenticated pages must be served over HTTPS. This includes css, scripts, images. Failure to do so creates a vector for man in the middle attack and also causes the browser to display a mixed SSL warning message.
 
 
 
== Implement HTTP Strict Transport Security (HSTS)==
 
* Applications that are served exclusively over HTTPS should utilize HSTS to instruct compatible browsers to not allow HTTP connections to the domain
 
 
 
  
 
= File Uploads =  
 
= File Uploads =  
  
==Upload Verification==
+
Please see https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#File_Uploads
*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
 
 
 
==Upload Storage==
 
*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
 
 
 
==Upload Verification==
 
*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)
 
 
 
  
 
= Error Handling =
 
= Error Handling =
  
Typical types of errors:
+
Please see https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#Error_Handling
• 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 =
 
= Logging and Auditing =
  
https://www.owasp.org/index.php/Logging_Cheat_Sheet
+
Please see https://www.owasp.org/index.php/Logging_Cheat_Sheet
 
 
  
 
= Cryptography =
 
= Cryptography =
  
* All protocols and algorithms for authentication and secure communication should be well vetted by the cryptographic community.
+
Please see https://www.owasp.org/index.php/Cryptographic_Storage_Cheat_Sheet
* 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
 
 
 
  
 
= Cookie Management =
 
= Cookie Management =
  
* Ensure that sensitive information is not comprised, by ensuring that sensitive information is not persistent / encrypting / stored on a need basis for the duration of the need
+
Please see https://www.owasp.org/index.php/Session_Management_Cheat_Sheet#Cookies
* Ensure that unauthorized activities cannot take place via cookie manipulation
 
* Ensure secure flag is set to prevent accidental transmission over “the wire” in a non-secure manner
 
* Determine if all state transitions in the application code properly check for the cookies and enforce their use
 
* Ensure entire cookie should be encrypted if sensitive data is persisted in the cookie
 
* Define all cookies being used by the application, their name and why they are needed
 
 
 
 
 
= Secure Deployment =
 
 
 
* 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 =
 
= Unvalidated Redirects and Forwards Cheat Sheet =
  
https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet
+
Please see https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet
 
 
= Common Vulnerabilities =
 
 
 
 
 
 
 
== SQL Injection ==
 
 
 
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
 
 
 
== Cross Site Scripting ==
 
 
 
https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet
 
 
 
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
 
 
 
https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
 
 
 
== Cross Site Request Forgery ==
 
 
 
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
 
 
 
* Any state changing operation requires a secure random token (e.g CSRF token) to prevent against CSRF attacks
 
* Characteristics of a CSRF Token
 
** Unique per user & per user session
 
** Tied to a single user session
 
** Large random value
 
** Generated by a cryptographically secure random number generator
 
* The CSRF token is added as a hidden field for forms or within the URL if the state changing operation occurs via a GET
 
* The server rejects the requested action if the CSRF token fails validation
 
 
 
== Preventing Malicious Site Framing (ClickJacking) ==
 
  
Set the x-frame-options header for all responses containing HTML content. The possible values are "DENY" or "SAMEORIGIN".
+
= SQL Injection =
  
    DENY will block any site (regardless of domain) from framing the content.
+
Please see https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
    SAMEORIGIN will block all sites from framing the content, except sites within the same domain.
 
  
The "DENY" setting is recommended unless a specific need has been identified for framing.
+
= Cross Site Scripting =
  
== Security Misconfigurations ==
+
Please see https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet
  
* Diable all the services, ports, protocols and daemons that are not required.
+
Please see https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
* 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 ==
+
Please see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
  
https://www.owasp.org/index.php/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet
+
= Cross Site Request Forgery =
  
== Directory Listing ==
+
Please see https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
  
* Do not enable Directory Listing on your server
+
= Preventing Malicious Site Framing (ClickJacking) =
  
== Concurrancy and Race Conditions ==
+
Please see https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Defending_with_X-Frame-Options_Response_Headers
  
* Use a locking mechanism to lock shared resources
+
= Insecure Direct Object references =
* Obtain a lock on shared resources before it is read
 
  
== References ==
+
Please see https://www.owasp.org/index.php/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet
  
 +
= Other Cheatsheets =
  
 
{{Cheatsheet_Navigation}}
 
{{Cheatsheet_Navigation}}
  
 
[[Category:Cheatsheets]]
 
[[Category:Cheatsheets]]

Revision as of 02:03, 26 May 2018

Introduction

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.

User Authentication

Please see https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Utilize_Multi-Factor_Authentication

Password Complexity

Please see https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Implement_Proper_Password_Strength_Controls.

Session Management

Please see https://www.owasp.org/index.php/Session_Management_Cheat_Sheet

Access Control

Please see https://www.owasp.org/index.php/Access_Control_Cheat_Sheet

Input Data Validation

Please see https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet

Output Encoding

Please see https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#Output_Encoding

Secure Transmission / Network Layer security

Please see https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet#Benefits

File Uploads

Please see https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#File_Uploads

Error Handling

Please see https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#Error_Handling

Logging and Auditing

Please see https://www.owasp.org/index.php/Logging_Cheat_Sheet

Cryptography

Please see https://www.owasp.org/index.php/Cryptographic_Storage_Cheat_Sheet

Cookie Management

Please see https://www.owasp.org/index.php/Session_Management_Cheat_Sheet#Cookies

Unvalidated Redirects and Forwards Cheat Sheet

Please see https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet

SQL Injection

Please see https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

Cross Site Scripting

Please see https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet

Please see https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

Please see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet

Cross Site Request Forgery

Please see https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet

Preventing Malicious Site Framing (ClickJacking)

Please see https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Defending_with_X-Frame-Options_Response_Headers

Insecure Direct Object references

Please see https://www.owasp.org/index.php/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet

Other Cheatsheets

OWASP Cheat Sheets Project Homepage