Secure Coding Practices Checklist:
- Input Validation
- Output Encoding
- Authentication and Password Management
- Session Management
- Access Control
- Cryptographic Practices
- Error Handling and Logging
- Data Protection
- Communication Security
- System Configuration
- Database Security
- File Management
- Memory Management
- General Coding Practices
Explanation:
Input Validation:
1) Identify trusted and non-trusted systems and conduct all data validation for them.
2) Maintain a centralized input validation routine for the application
3) Specify proper character sets
4) Encode something to a common set before validating
5) Validate all client provided data as in parameters, URLs and HTTP header content (cookie names and values)
6) Verify that header values in request and response contains ASCII values only
7) Validate redirects,expected data types, data range, data length, black list, white list
8) Hazardious characters must be properly verified using various APIs
Output Encoding:
1) Conduct all encoding on a trusted system and sent to the client.
2) encode all characters unless its safe for the other application.
Authentication and Password Management:
1) Require authentication for all pages and resources
2) authentication controls must be enforced on a trusted system
3) use standard, tested authentication services
4) use a centralized authentication control mechanism
5) credential store must store passwords in a encrypted way with proper salting.
6) validate the authentication data only on completion of all data input.
7) authentication failure must use generic message rather than "invalid username" or "invalid password"
8) authentication credentials for accessing outside service must be stored securely in a secure credential store. Source code is not a proper location.
9) Use only HTTP Post to transmit authentication
10) Temporary passwords is an exception to send unencrypted over a network.
11) Enforce password complexity
12) Enforce password length
13) Password must be obscured on the user's screen
14) Enable account disabling
15) Proper password reset and changing scheme must be enabled.
16) Password reset questions must be framed such that it can't be recovered easily using social engineering.
17) Temporary passwords must be send to registered email address only and it should have definite attempts and should have definite expiration time.
18) Enforce the change of password on next use.
19) Notify users upon sign-in/attempted sign-in from other devices
20) Notify users about last login status.
21) Prevent password re-use.
22) Password must be atleast 24 hours old to make an change attempt.
23) Disable “remember me” for critical applications.
24) Implement UBA.
25) Implement User Account Status Monitoring.
26) Change all vendor supplied user accounts and passwords.
27) Re-authenticate users prior to performing critical operations.
28) Use Multi-Factor Authentication for sensitive applications.
29) Examine the third party code if used for authentication for probable tampering or injection.
Session Management:
1) Use the server or framework’s session management controls. The application should recognize these session ids only.
2) Session creation must be done by trusted sources only.
3) Session generation algorithms must generate random session ids to prevent session guessing.
4) Set the domain and path for cookies containing authentication identifiers to an appropriately restricted value for the site.
5) Logout should terminate session completely.
6) Logout functionality must be available at every pages.
7) Set a session timeout activity to prevent session hijacking. Enforce requirement to re authenticate after session expiration.
8) Generate a new session id on re-authentication.
9) Do not allow concurrent logins from different systems for the same user ID/session IDs.
10) Do not expose session identifiers in URLs, error messages or logs. It should be available only in HTTP cookie header.
11) Secure the Session IDs from unauthorized access.
12) Generate a new session id periodically and disable existing one to prevent session hijacking.
13) Generate a new session id when the application changes from HTTP to HTTPS. It is recommended to consistently utilize HTTPS.
14) Generate per-session strong random parameters or tokens to avoid CSRF for every session.
15) Set the “secure” attribute for cookies transmitted over a TLS connection.
16) Set cookies with HTTPOnly attribute unless we require client side script to read or set a cookie.
Access Control:
1) Use only server side session objects for making authorization decisions.
2) Use a centralized or single-site component or module to check for authorization.
3) Deny all access if the application fail to access its security configuration information.
4) Enforce authorization controls on every request including controls for server side scripts.
5) Segregate privilege logic from other application code.
6) Enforce authorization controls for access to files or resources, protected URLs, functions, direct object reference, services, application data, user and data attributes, policy information, security related configuration information.
7) Server side implementation and presentation layer representation of access control should match.
8) If state data must be stored on the client to identify the state of the user, use encryption and integrity check to detect and avoid state data tampering
9) Limit the no. of transactions a user can perform in a given time.
10) Re-validate long sessions.
11) Implement UBA, account auditing and unused account protection.
12) Application must terminate the session immediately upon any authorization violation.
13) Service accounts or accounts used to communicate with external systems must have least privileges.
Cryptographic Practices:
1) Cryptographic functions used to secure the data must be implemented on a trusted system.
2) Protect master secrets from unauthorized access.
3) Use tested and certified, well known random generator module for generating random numbers.
4) Change the encryption key after a definite time.
Error Handling and Logging:
1) Sensitive information shouldn’t be disclosed in error responses, system details, session identifiers or account information.
2) Use error handlers that doesn’t display debugging or stack trace information.
3) Implement generic error messages and use custom error pages.
4) Properly allocate memory when error condition occurs.
5) Error handling logic must prevent access by default.
6) All logging and error controls must be implemented in server (trusted source).
7) Ensure proper log management.
8) Enable Log security e.g. audit log tempering, clearing etc.
9) Do not store sensitive information in logs.
10) Log everything as per the standards like application logs, events logs, system logs etc.
Data Protection:
1) Implement least privilege.
2) Protect cashed/RAM or temporary stored data from getting grabbed by other processes or applications.
3) Encrypt highly sensitive data with secure cryptographic programs.
4) Do not store passwords or sensitive information in clear text
5) Remove comments from the code.
6) Remove unnecessary application and documentation.
7) Do not include sensitive information in HTTP Get.
8) Disable autocomplete features for sensitive information.
9) Disable client side caching for sensitive information. Use Cache-control: no-store along with HTTP header control: Pragma: no-cache.
10) Remove sensitive data when no longer required.
11) Implement appropriate access control on the sensitive data.
Communication Security:
1) Send data through secure protocols: like IPSec, TLS, SSL, SSH etc.
2) TLS certificate should be valid with correct domain name, not expired and be installed with intermediate certificates when required.
3) Failed TLS should not be backward compatible.
4) Utilize a single standard TLS implementation.
5) Specify appropriate encoding for all connections.
6) Filter parameters containing sensitive information from the HTTP referer, when linking to external sites.
System Configuration:
1) Ensure system components are running the latest versions.
2) Turn off directory listing
3) Restrict the web server, processes and user accounts to least privilege policy.
4) Fail securely upon exceptions.
5) Remove all unnecessary files and functionalities.
6) Remove test code or any functionality not intended for production.
7) Prevent disclosure of directory not intended for public in “robots.txt” file. Rather than blocking individual directory, put all such files in a separate parent directory and disable that.
8) Define which HTTP methods the application will support and disallow others.
9) If the web server handles both HTTP 1.0 and 1.1 then ensure both are implemented in similar manner and we understand any possible difference (E.g. handling of extensive HTTP methods)
10) Remove unnecessary information from HTTP response headers related to the OS, web-server version and application frameworks
11) The security configuration store for the application should be able to be output in human readable form to support auditing
12) Implement an asset management system and register system components and software in it
13) Isolate development environments from the production network and provide access only to authorized development and test groups. Development environments are often configured less securely than production environments and attackers may use this difference to discover shared weaknesses or as an avenue for exploitation
14) Implement a software change control system to manage and record changes to the code both in development and production
Database Security:
1) Use parameterized queries only
2) Utilize input validation and output encoding and be sure to address meta characters. If these fail, do not run the database command
3) The application should use the lowest possible level of privilege when accessing the database
4) Use secure credentials for database access.
5) Connection strings must not be hardcoded in the code. Connection string must be stored in a separate configuration file on trusted system and it should be encrypted.
6) Close the connection as soon as possible.
7) Remove or change all default database administrative passwords. Utilize strong passwords/phrases or
8) Implement multi-factor authentication.
9) Turn off all unnecessary database functionality (e.g., unnecessary stored procedures or services, utility packages, install only the minimum set of features and options required.
10) Remove unnecessary default vendor content (e.g., sample schemas).
11) Disable any default accounts that are not required to support business requirements.
12) The application should connect to the database with different credentials for every trust distinction (e.g., user, read-only user, guest, administrators)
File Management:
1) Do not pass user supplied data directly to any dynamic include function.
2) Require authentication before file upload.
3) Limit the types of files as required.
4) Validate uploaded file types by checking the headers.
5) Do not save files in the same web context as the application. Files should either go to the content server or in the database.
6) Prevent or restrict the uploading of any file that may be interpreted by the web server.
7) Turn off execution privileges on file upload directories
8) When referencing existing files, use a white list of allowed file names and types. Validate the value of the parameter being passed and if it does not match one of the expected values, either reject it or use a hard coded default file value for the content instead.
9) Do not pass user supplied data into a dynamic redirect. If this must be allowed, then the redirect should accept only validated, relative path URLs
10) Do not pass directory or file paths, use index values mapped to pre-defined list of paths
11) Never send the absolute file path to the client
12) Ensure application files and resources are read-only
13) Scan user uploaded files for viruses and malware
Memory Management:
1) Utilize input and output control for un-trusted data.
2) Double check that buffer is as large as specified.
3) When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string
4) Check buffer boundaries if calling the function in a loop and make sure there is no danger of writing past the allocated space
5) Truncate all input strings to a reasonable length before passing them to the copy and concatenation functions
6) Specifically close resources, don’t rely on garbage collection
7) Use non-executable stacks when available
8) Avoid the use of known vulnerable functions (e.g., printf, strcat, strcpy etc.)
9) Properly free allocated memory upon the completion of functions and at all exit points
Generalized Coding Practice:
1) Use tested and approved managed code rather than creating new unmanaged code for common tasks
2) Utilize task specific built-in APIs to conduct operating system tasks. Do not allow the application to issue commands directly to the Operating System, especially through the use of application initiated command shells
3) Use checksums or hashes to verify the integrity of interpreted code, libraries, executables, and configuration files
4) Utilize locking to prevent multiple simultaneous requests or use a synchronization mechanism to prevent race conditions
5) Protect shared variables and resources from inappropriate concurrent access
6) Explicitly initialize all your variables and other data stores, either during declaration or just before the first usage
7) In cases where the application must run with elevated privileges, raise privileges as late as possible, and drop them as soon as possible
8) Avoid calculation errors by understanding your programming language's underlying representation and how it interacts with numeric calculation. Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how your language handles numbers that are too large or too small for its underlying representation
9) Do not pass user supplied data to any dynamic execution function
10) Restrict users from generating new code or altering existing code
11) Review all secondary applications, third party code and libraries to determine business necessity and validate safe functionality, as these can introduce new vulnerabilities
12) Implement safe updating. If the application will utilize automatic updates, then use cryptographic signatures for your code and ensure your download clients verify those signatures. Use encrypted channels to transfer the code from the host server
nice collection , thanks;
ReplyDelete