Best Practices for Secure Coding

Addressing security early in the software development life cycle is easier and less expensive than correcting issues found in late-stage testing or after an application has been released to production. The following best practices are an essential part of secure application coding and hosting.

Input Validation

  • Ensure applications validate input (network, keyboard, file, database) properly and restrictively, allowing only those types of input that are known to be correct, especially from untrusted sources.

Error Handling

  • Ensure applications execute proper error handling so that errors will not provide detailed system information, deny service, impair security mechanisms, or crash the system.

Authentication and Authorization

Access Control

  • Base access decisions for both developers and users on permission rather than exclusion, and adhere to the principle of least privilege.
  • Wherever feasible, provide access to applications based on role, affiliation, or membership, rather than by individual.
  • Ensure your code uses only privileges that are needed, dropping any elevated privileges as soon as possible.

Cryptographic Practices

  • Use well-known, properly reviewed, actively maintained cryptography libraries.
  • Encrypt external transmission for applications or software that maintain, process, transmit, or store sensitive data.
  • If possible, use encryption for sensitive data at rest.

Logging

Quality Assurance Checking

  • Use effective quality assurance techniques (for example, penetration testing, source code audits, application scanning) to identify and eliminate vulnerabilities.
  • Conduct application scanning before major changes or revisions are moved to production.

Code Management

  • Implement and maintain a change management process, including version control, for changes to existing software applications.
  • Comment your code well, and document all design decisions.

Vulnerability Management

  • Keep software and components (libraries, modules, dependencies) you use patched for known security vulnerabilities.
  • Have a mechanism for updating all of your code's dependencies regularly.
  • Use automated testing to ensure that the updates do not break your code's functionality.
  • Follow vulnerability management guidance to comply with Vulnerability Management (DS-21).

Session Management

  • Do not allow session tokens to be sent over HTTP (use HTTPS).
  • Do not create your own session token generation code.
  • Prevent session fixation attacks by creating a new token upon user login.
  • Keep session IDs out of URLs.

Resources

For resources and links to training to help you learn to implement these best practices, see Secure Coding: Guidance and Training Resources.