Top 10 secure coding practices

DevOps involves integrating development, testing, deployment, and release cycles into a collaborative process. Security is often considered an afterthought, to be inserted just before release. Having the forethought to integrate security throughout the DevOps cycles is known as DevSecOps; and it involves intelligence, situational awareness, and collaboration; secure coding, deployment and management.

Always follow to security SHIFT-LEFT approach, start thinking about security from very beginning. This is why secure coding practice is crucial in SecSDLC. According to OWASP I would focus on 10 most important steps to implement security while coding.

Input Validation

The “Input validation” section in your Secure Coding Practices checklist involves measures to ensure that data coming into your application is safe and free from potential security risks. It includes practices like conducting validation on trusted systems, distinguishing between trusted and untrusted data sources, specifying character sets, validating data types, lengths, and ranges, and being cautious about potentially hazardous characters. The goal is to prevent malicious data from entering your application and to handle it safely if it must be allowed. These practices help safeguard against common security vulnerabilities, such as injection attacks, by ensuring that only well-formed, expected, and safe data is processed.

Best practices:
  1. Ensure that all data validation is performed on the server, not on the client side. This prevents validation rules from being bypassed by manipulating client-side code.
  2. Classify data sources as trusted (e.g., internal databases) or untrusted (e.g., user input, external APIs). Validate all data from untrusted sources to prevent malicious input.
  3. Implement a centralized input validation routine to ensure consistent and thorough validation across the application.
  4. Validate all input from the client, including parameters, URLs, HTTP headers, and automated postbacks, to prevent malicious code injection.
  5. Validate data from redirects to prevent malicious content from being directly submitted to the redirect target, bypassing application logic.
  6. Limit the length of input to prevent buffer overflows and other length-based attacks.
  7. If potentially hazardous characters must be allowed as input, implement additional controls.

Output Encoding

The “output encoding” section in your Secure Coding Practices checklist focuses on ensuring that data leaving your application is secure and properly formatted. It involves practices such as conducting encoding on trusted systems, utilizing established encoding routines, and contextually encoding or sanitizing data before returning it to clients. This helps prevent security vulnerabilities by ensuring that all data is presented in a safe and well-structured manner, especially when it originated from untrusted sources. Proper output encoding safeguards against issues like cross-site scripting (XSS) and injection attacks by ensuring that data is correctly processed for the intended interpreter and presentation medium.

Best practices:
  1. Ensure that all encoding of output data is performed on the server, not on the client side, to prevent tampering and security vulnerabilities.
  2. Apply output encoding to all data that originates outside the application’s trust boundary and is returned to the client. Use appropriate encoding based on the context
  3. Sanitize all output of untrusted data to prevent injection attacks in queries for SQL, XML, and LDAP. Apply contextual sanitation based on the query type.

Authentication and Password Management

Authentication and Password Management focuses on ensuring secure access to your application. It includes practices like requiring authentication for most resources, using standard authentication services, securely storing and handling passwords, enforcing password complexity and reset policies, and monitoring for suspicious activities. The goal is to protect user accounts, data, and sensitive functions by implementing strong authentication and password management practices, ultimately safeguarding against unauthorized access and security breaches.

Best practices:
  1. Ensure that authentication is required for all pages and resources, except those specifically intended to be public.
  2. Implement all authentication controls on the server, not on the client side, to prevent tampering with authentication logic.
  3. Implement a centralized authentication mechanism for all authentication-related processes, providing a single point of control for managing user credentials and access permissions.
  4. Authentication controls should fail securely, with responses not revealing which part of the authentication data was incorrect.
  5. Apply the same level of security controls to administrative and account management functions as to the primary authentication mechanism to ensure consistent security.
  6. Perform password hashing on the server, not on the client side, to protect the hashing algorithm and salt values from exposure.
  7. Validate the authentication data only after all data input is complete, especially for sequential authentication implementations.
  8. Enforce password complexity requirements based on policy or regulations to enhance password security.
  9. Implement account disabling after a set number of invalid login attempts to deter brute force attacks.
  10. Use Multi-Factor Authentication (MFA) for highly sensitive or high-value transactional accounts to add an additional layer of security.

Session Management

Session Management is all about ensuring secure and well-controlled user sessions within your application. It involves practices like using trusted session management controls, setting appropriate timeout periods, disallowing concurrent logins, and protecting session data from unauthorized access. The primary goal is to safeguard user sessions from common threats like session hijacking or Cross-Site Request Forgery (CSRF) by implementing robust session management practices. These practices help maintain the integrity and security of user sessions while allowing for smooth and secure interactions with your application.

Best practices:
  1. Utilize the built-in session management provided by your web server or framework. This ensures that your application recognizes and uses valid session identifiers.
  2. Generate session identifiers (like cookies) on the server to prevent tampering.
  3. Ensure that the logout function fully terminates the user’s session or connection.
  4. Do not allow users to stay logged in indefinitely. Log them out periodically, even during an active session.
  5. Prevent multiple simultaneous logins with the same user ID.
  6. Implement access controls on the server to prevent unauthorized access to session data by other users or processes on the server.
  7. For highly sensitive or critical operations, use per-request, rather than per-session, strong random tokens or parameters.

Access Control

Access Control is about ensuring that only authorized users can access specific parts of your application. This section includes practices such as using trusted system objects for authorization decisions, enforcing access controls on every request, segregating privileged logic, and restricting access to files, resources, URLs, functions, and data. The primary goal is to prevent unauthorized access to sensitive areas of your application and data by implementing strong access control practices. These practices help protect your application from security threats, ensuring that users can only access what they are allowed to and that sensitive information remains secure.

Best practices:
  1. Use only trusted system objects, such as server-side session objects, for making access authorization decisions.
  2. Access controls should fail securely, ensuring that unauthorized users cannot gain access to restricted resources.
  3. Deny all access if the application cannot access its security configuration information, ensuring that security settings are enforced even when configuration data is inaccessible.
  4. Segregate privileged logic from other application code to prevent unauthorized access to sensitive operations.
  5. Restrict access to files and resources, including those outside the application’s control, to only authorized users.
  6. Ensure that server-side implementation and presentation layer representations of access control rules match.
  7. Implement account auditing and enforce the disabling of unused accounts, such as after 30 days from the expiration of an account’s password.
  8. Service accounts or accounts used for connections to external systems should have the least privilege necessary.

Error Handling and Logging

Error Handling and Logging is essential for maintaining the security and integrity of your application. This section includes practices like not revealing sensitive information in error responses, implementing custom error pages, and securely handling errors, as well as logging important security events and failures. The primary goal is to enhance application security by carefully managing how errors are handled and logged. Proper error handling helps prevent attackers from exploiting vulnerabilities and allows you to monitor and analyze security events effectively to detect and respond to potential threats.

Best practices:
  1. Error responses should not reveal sensitive information like system details, session identifiers, or account information.
  2. Use error handlers that do not display debugging or stack trace information
  3. Use custom error pages with generic error messages to prevent leaking sensitive information to users or attackers.
  4. Ensure that allocated memory is correctly freed when error conditions occur to prevent memory leaks.
  5. Implement logging controls on a trusted system
  6. Log entries should contain essential event data to help in diagnosing and understanding security incidents
  7. Avoid storing sensitive information like system details, session identifiers, or passwords in log entries.
  8. Employ cryptographic hash functions to verify the integrity of log entries and detect tampering.

Data Protection

Data Protection is crucial for securing sensitive information within your application. This section involves practices like implementing the principle of least privilege, encrypting sensitive data, protecting cached or temporary files, and safeguarding server-side source code. The primary goal is to ensure the confidentiality and integrity of data, preventing unauthorized access or data leaks. Effective data protection practices, like encryption and access controls, help keep sensitive information safe from threats and unauthorized disclosure, ultimately enhancing the security of your application.

Best practices:
  1. Implement least privilege, restrict users to only the required functionality, data, and system information.
  2. Protect cached or temporary copies of sensitive data on the server from unauthorized access and purge them when no longer needed.
  3. Encrypt highly sensitive stored information, like authentication verification data, even on the server side.
  4. Protect server-side source code from being downloaded by a user.
  5. Do not store passwords, connection strings, or other sensitive information in clear text or insecure formats on the client side.
  6. Remove comments in user-accessible production code that may reveal sensitive information.
  7. Disable auto-complete features on forms with sensitive information, including authentication.
  8. Support the removal of sensitive data when no longer required.
  9. Implement access controls for sensitive data stored on the server, including cached data, temporary files, and data accessible only by specific users.

Database Querying Security

Database Security is essential for ensuring the confidentiality and integrity of your application’s data. This section includes practices like using strongly typed parameterized queries, input validation, and output encoding to prevent SQL injection attacks. It also emphasizes the importance of utilizing secure credentials for database access, storing connection strings securely, and minimizing privileges when interacting with the database. The primary goal is to protect your database from unauthorized access and data breaches, ensuring that sensitive information remains secure and confidential. Effective database security practices help safeguard your application’s most critical asset – its data.

Best practices:
  1. Use strongly typed parameterized queries.
  2. Utilize input validation and output encoding and be sure to address meta characters. If these fail, do not run the database command.
  3. Limit the privileges granted to the application when interacting with the database to minimize the potential impact of security breaches.
  4. Connection strings should not be hard coded within the application. Connection strings should be stored in a separate configuration file on a trusted system and they should be encrypted.
  5. Use stored procedures to abstract data access and allow for the removal of permissions to the base tables in the database.
  6. Close the connection as soon as possible.
  7. Remove or change all default database administrative passwords. Utilize strong passwords/phrases or implement multi-factor authentication.
  8. Disable any default accounts that are not required to support business requirements.

File Management

File Management is all about handling files securely within your application. This section includes practices like not passing user-supplied data directly to dynamic include functions, authenticating file uploads, validating file types, and avoiding saving files in the same web context as the application. The primary goal is to prevent malicious file uploads, limit access to files, and ensure that files are handled safely to avoid security vulnerabilities. Effective file management practices help maintain the integrity and security of your application’s file system and protect it from potential threats.

Best practices:
  1. Avoid directly passing user-supplied data to dynamic include functions to prevent code execution vulnerabilities.
  2. Require authentication before allowing a file to be uploaded.
  3. Allow only specific types of files to be uploaded that are relevant to the application’s business requirements.
  4. Validate uploaded files are the expected type by checking file headers. Checking for file type by extension alone is not sufficient.
  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. Turn off execution privileges on file upload directories.
  7. Do not pass directory or file paths, use index values mapped to pre-defined list of paths.
  8. Never send the absolute file path to the client.
  9. Ensure application files and resources are read-only.
  10. Implement virus and malware scanning for files uploaded by users to prevent malicious content from entering the application.

Memory Management

Memory Management involves handling memory securely in your application. This section emphasizes practices like input and output control for untrusted data, checking buffer sizes to prevent buffer overflows, and avoiding known vulnerable functions. The goal is to ensure that your application efficiently manages memory, mitigates memory-related vulnerabilities, and avoids potential security risks associated with memory handling. Proper memory management contributes to the overall security and reliability of your software.

Best practices:
  1. Employ input and output controls to manage data from untrusted sources, ensuring that the data is processed safely and securely.
  2. Verify that buffer sizes match the expected size to prevent buffer overflows and memory corruption vulnerabilities.
  3. Limit the length of input strings to a reasonable size before using copy and concatenation functions to prevent buffer overflows.
  4. Explicitly close resources such as connection objects and file handles instead of relying on garbage collection to ensure timely resource deallocation.
  5. Avoid the use of known vulnerable functions (e.g., printf, strcat, strcpy etc.)
  6. Ensure that dynamically allocated memory is correctly deallocated at the end of functions and at all exit points to prevent memory leaks.

Please visit or #CyberTechTalk WIKI pages for much more information about designing reliable systems, monitoring and information security.

Be ethical, save your privacy!

subscribe to newsletter

and receive weekly update from our blog

By submitting your information, you're giving us permission to email you. You may unsubscribe at any time.

Leave a Comment

Discover more from #cybertechtalk

Subscribe now to keep reading and get access to the full archive.

Continue reading