Secure coding checklist

I wrote this book so that you can have a bible of application security to use on a daily basis in your career. I want this book to contain practical scenarios as much as possible, such as the checklist mentioned in this section. Filling words in a book are not my style—I like actions (quick quote: planning without actions is just a dream), and the upcoming checklist contains straightforward rules that you can use both as a security guideline for developers and as a checklist for you when you manually inspect the source code:

Authentication and credentials management:

 √ 

Authentication credentials must use TLS and not HTTP cleartext.

Authentication must be enforced on all pages, except the ones intended to be public.

The error messages (in the login page, reset password page, and registration page) should not lead to information-gathering disclosure (for example, in the case of an invalid username).

Authentication logic must be validated on the server side.

Authentication passwords must be saved under secure hashing algorithms (mot MD5 or SHA1), and salting is preferable.

The password's hashing logic must be on the server side.

Validate the authentication data after the completion of all the data entry by the end user.

If the application is interacting with third-party web services, you will need to ensure the authentication as well as these endpoints.

The authentication credentials to interact with third-party web services should be encrypted and not be in cleartext (check the config file; developers will leave it there).

Enforce password complexity/length requirements established by policy or regulation.
Use the following common best practices:

  • Minimum  length of 10 characters
  • Minimum  of one  capital letter
  • Minimum  of one  special character
  • Minimum  of one number

Ensure that all password fields do not echo the user's password when it is entered, and that the password fields have autocomplete disabled.

Password reset questions should support sufficiently random answers (for example, What is your favorite color is a bad question because Red is a very common answer).

If using email-based resets, only send email to a preregistered address with a temporary random link/password (short expiration time).

The temporary passwords must be changed for the next usage.

Alert users by email or SMS when a user changes or resets their password.

Enforce account disabling after a number of login failures (five attempts is a commonly used limit). The account must be disabled for a period of time sufficient to discourage the brute-force guessing of credentials, but not so long as to allow for a denial-of-service attack to be performed.

Reauthenticate users prior to performing critical operations.

Use multifactor authentication for highly sensitive or high-value transactional accounts.

Disable remember me functionality for password fields.

 

Authorization and access control:

√  

Authorization must be developed on the server side.

Deny all access if the application cannot access its security configuration information (for example, if the application cannot connect to the database).

Authorization must exist on every web request (for example, the Web API endpoint).

Access to files (for example, source code, configuration files) and resources (including protected URLs and web services ) must be restricted to admins; only they should be allowed to access those resources.

If authorization data must be stored on the client side, then you must encrypt it.

Use the Referer header as an additional check, but be careful not to depend on it because it can be spoofed.

OS/application service accounts should have the least privilege.

Authorize only HTTP methods: GET, POST, PUT, and DELETE.

Make sure that you apply authorization changes right away after submitting them to the server by forcing the user to log out from the application.

 

Session management

√  

Sessions must be managed on the server side.

Session identifier (session ID) must be random (hackers should not be able to predict it).

Logout functionality should totally terminate your session and should be available on all the authenticated pages.

Establish a session timeout after inactivity. To calculate the timeout period properly, you need to calculate the security risk of that resource.

Do not put session IDs in URLs, logs, and error messages (the session ID is located in the cookie header).

Set the secure attribute for cookies.

Set the HttpOnly attribute for cookies.

 

Cryptography:

√  

Any cryptographic functionality to protect data should be implemented on the server side.

Critical data (for example, database-connection strings, passwords, keys, and so on) must be encrypted and should not be in cleartext.

Cryptographic keys must be protected from unauthorized users (only super admins should have access to them).

All generated random items—such as numbers, file names, and strings—must use highly cryptographic random generators.

All cryptographic algorithms must use the latest and greatest secure algorithms. Refer to the NIST organization at https://csrc.nist.gov to get all the information that you need.

 

Input validation:

√  

All data validation must be performed on the server side.

Encode data before validation.

All validation failures should be rejected in a custom error message.

The validation should happen on anything that is processed in the backend, including hidden form values, URLs, and header contents (it should not be limited to form inputs).

Hazardous characters, such as <>" ' % () & + /should be validated.

You should also validate the following:

  • Null bytes (%00)
  • New line ( , ,%0d,%0a)
  • dot dot slash (../ or ..)
√ 

Confirm that no hardcoded SQL queries exist in the source code.

√ 

Truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.

 

Output encoding:

√  

Conduct all the output encoding logic on the server side.

Sanitize all the output of untrusted data for SQL, XML, LDAP, and operating system commands.

 

Logging and error handling:

  

Do not disclose sensitive information in error messages, including debugging information, such as a stack trace.

Use custom error messages and error pages.

Logging controls must be executed on the server side.

Logging events must be raised on both success and failure actions.

Log data must be clear enough to be able to understand what happened.

Log data must be sanitized if it's dependent on an input.

Log functions must be centralized and managed in the same class or module.

Make sure that you log the following events:

  • Validation failures
  • Authentication attempts
  • Authorization failures
  • Tampering events (for example, URL manipulation for SQL injection)
  • Using invalid or expired sessions
  • All the administrative functions
  • Cryptographic module failures
  • Access from certain countries
  • High frequency of web requests

When exceptions occur, you need to be able to exit that function securely.

Error or monitoring logs should not be saved on the same server to avoid DOS attacks (by filling the disk drive with random data).

 

Data protection:

√  

Temporary sensitive data (for example, caches, or transferred files) must be stored in a secure location, and those items must be purged as soon as possible.

Remove comments in the source code that may reveal critical information about the application.

Make sure that you protect files on the web server, and that only the intended files are called by clients. Protect config files, backup files, deployment scripts (or any script), documentation that is not intended for the public, temporary files, and any file that contains confidential information.

Sensitive information should not be used in the URL query string.

Disable caching for pages that handle confidential information. Use Cache-Control:no-store and Pragma:no-cache for this.

Data in transit must be encrypted with the latest and greatest TLS algorithms.

Carefully use the HTTP referrer when dealing with external domains.

 

Miscellaneous:

 

Make sure that you remove test codes (not intended for production) before deployment.

Avoid disclosing your unwanted directory structure in the robots.txt file. Instead, create a parent directory and put all the hidden directories and files within it rather than disallowing each directory/file in robots.txt

Remove any unnecessary information from the HTTP header (for example, the OS version, web server version, and programming frameworks).

If, for any reason, the application must elevate its privileges, make sure that you drop them as soon as possible.

When designing a REST web API, you have so many options for error codes other than 200 for success and 404 for errors. Proper error codes may help to validate the incoming requests properly. Here are some best practices to consider for each REST API status return code:

  • 200 OK: The action is successful.
  • 202 Accepted: The request to create a resource is accepted.
  • 204 No Content: The POST request did not include a client-generated ID.
  • 400 Bad Request: The request is malformed.
  • 401 Unauthorized: Wrong authentication ID or credentials.
  • 403 Forbidden: An authenticated user does not have the permission to access the resource.
  • 404 Not Found: Requesting a nonexistant resource.
  • 405 Method Not Allowed: Unexpected HTTP method in the request.
  • 429 Too Many Requests: This error may occur when a DOS attack is detected.
√ 

Make sure that the following headers exist:

  • X-frame-options
  • X-content-type-options
  • Strict-transport-security
  • Content-security-policy
  • X-permitted-cross-domain-policies
  • X-XSS-protection:1;mode=block
  • X-content-type-options:nosniff

Properly free allocated memory upon the completion of functions and at all exit points.

 

File management:

√  

The user must be authenticated before uploading any files into the application.

Limit the type of files that can be uploaded into the application.

Validate uploaded files by checking the file headers. Checking the extension by itself is not sufficient.

Uploaded files should be saved on a separate server rather than the web server. 

Carefully check and validate (or remove if necessary) the uploaded files that will be executed and interpreted by the web server.

Execution privileges must be turned off on the file upload server.

Antiviruses and endpoint security must exist on the upload file server.

Do not pass directory or file paths; instead use index values mapped to a predefined list of paths. Never send the full absolute path in the response to the client.

The web application files and resources must be in read-only format.

 

Third-party libraries:

√  

Use checksums to verify the integrity of files (such as libraries and scripts) downloaded from the internet.

Ensure that the library that is downloaded and used in the application is the latest stable version.

Use a third-party libraries scanner (for example, Sonatype, Blackduck).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.228.35