Software Security Principles

  • Goal of software security:

    • Maintain the confidentiality, integrity and availability of information resources in order to enable successful business operations
    • It is accomplished through security controls
  • What is risk?

    • Risk is a combination of factors that threatens the success of the business
  • Secure coding checklist:

    • Data validation

    • Verify that the properties of all i/p and o/p data match what is expected by the application
    • Any potentially harmful data is made safe through the use of data removal, replacement, encoding, or escaping.
    • Conduct all data validation on the server side.
    • Encode data to a common character set before validating
    • Determine if the system supports UTF-8 extended character sets and if so, validate after UTF-8 decoding is completed.
    • Validate all client provided data before processing, including all form fields, URLs and HTTP header values.
    • URLs and HTTP header values.
    • Validate all input against a “white” list of allowed characters.
    • Sanitize any potentially hazardous characters that must be allowed, like: < > " ’ % ( ) & + \ , ;
    • Validate for expected data types.
    • Validate data range.
    • Validate data length.
    • Authentication and Password Management

    • Utilize standard security services when available, as they are designed to meet company requirements.
    • Change all vendor-supplied default passwords and user IDs or disable the associated accounts.
    • Utilize re-authentication for critical operations.
    • Use two factor authentication for highly sensitive or high value transactional accounts.
    • Log out functionality should be available from all pages.
    • Log out functionality must fully terminate the associated session or connection.
    • If non-standard authentication is used, it must address the following:
      • Validate the authentication data only on completion of all data input, especially for sequential authentication implementations.
      • Error conditions must not indicate which part of the authentication data was incorrect. Error responses must be truly identical in both display and source code.
      • Use only POST requests to transmit authentication credentials.
      • Only send passwords over an encrypted connection.
      • Enforce password complexity requirements. Passwords must include alphabetic as well as numeric and/or special characters.
      • Enforce password length requirements.
      • Enforce account disabling after no more than five invalid logon attempts.
      • Password recovery and changing operations require the same level of controls as account creation and authentication.
      • Password recovery should only send an email to a pre-registered email address with a temporary link/password which let’s the user reset the password.
      • Temporary passwords and links should have a short expiration time.
      • Password recovery questions should support sufficiently random answers.
      • Prevent password re-use.
      • Passwords must be at least one day old before they can be changed, to prevent attacks on password re-use.
      • Enforce password changes at least every 180 days. Critical systems may require more frequent changes.
      • Disable “remember me” functionality for password fields.
      • Log all authentication failures.
      • Report unsuccessful logon attempts to a User ID, at its next successful logon.
      • The last use of a User ID should be reported to the User ID at its next successful logon.
      • Segregate authentication logic and use redirection during login.
      • If your application manages credential storage, it should ensure that only the 1-way salted hashes of passwords are stored in the database, and that he table/file that stores the passwords and keys are “write”-able only to the application.
      • Implement monitoring to identify attacks against multiple user accounts, utilizing the same password. This attack pattern is used to bypass standard lockouts.
    • Authorization and Access Management

    • Ensure that all directories, files or other resources outside the application’s direct control have appropriate access controls in place.
    • If state data must be stored on the client, use encryption and integrity checking on the server-side to catch state tampering. The application should log all apparent tampering events.
    • Enforce application logic flows to comply with business rules.
    • Use a single site wide component to check access authorization.
    • Segregate privileged logic from other application code.
    • Limit the number of transactions a single user or device can perform in a given period of time. The transactions/time should be above the actual business requirement, but low enough to deter automated attacks.
    • Create an Access Control Policy (ACP) to documents an asset’s business rules and access authorization criteria and/or processes so that access can be properly provisioned and controlled. This includes identifying access requirements for both the data and system resources.
    • If long authenticated sessions are allowed, periodically revalidate a user’s authorization to ensure that their privileges have not changed.
    • Implement account auditing and enforce the disabling of unused accounts (After no more than 30 days from the expiration of an account’s password.).
    • The application must support disabling of accounts and terminating of sessions when authorization ceases (Causes include changes to role, employment status, business process, etc.).
    • 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.
    • Session Management

    • Establish a session inactivity timeout that is as short as possible. It should be no more than several hours.
    • If a session was established before login, close that session and establish a new session after a successful login.
    • Do not allow concurrent logins with the same user ID.
    • Session ID creation must always be done on the server side.
    • Do not pass session identifiers as GET parameters.
    • Server side session data should have appropriate access controls in place.
    • Generate a new session ID and deactivate the old one frequently.
    • Generate a new session token if a user’s privileges or role changes.
    • Generate a new session token if the connection security changes from HTTP to HTTPS.
    • Generate a new session token if the connection security changes from HTTP to HTTPS.
    • Only utilize the system generated session IDs for client side session (state) management. Avoid using parameters or other client data for state management.
    • Utilize per-page random tokens or parameters to supplement the main session token for critical operations.
    • Ensure cookies transmitted over an encrypted connection have the “secure” attribute set.
    • The application or system should log attempts to connect with invalid or expired session tokens.
    • Disallow persistent logins and enforce periodic session terminations, even when the session is active.
    • Especially for applications supporting rich network connections or connecting to critical systems.
    • Termination times should support business requirements and the user should receive sufficient notification to mitigation.
    • Sensitive Information Storage or Transmission

    • Implement approved encryption for the transmission of all sensitive information.
    • Encrypt highly sensitive stored information, like authentication verification data, even on the serverside.
    • Protect server side code from being downloaded.
    • Do not store passwords, connection strings or other sensitive information in clear text or in any noncryptographically secure manner on the client side. This includes embedding in insecure formats like: MS viewstate, Adobe flash or compiled code.
    • Do not store sensitive information in logs.
    • Implement least privilege, restrict users to just the functionality, data and system information that is required to perform their tasks.
    • Remove developer comments.
    • Remove unnecessary application and system documentation.
    • Turn off stack traces and other verbose system messages.
    • The application should handle application errors and not rely on the server configuration.
    • Filter GET parameters from the referer, when linking to external sites
    • System Configuration Management

    • Ensure servers, frameworks and system components are patched.
    • Ensure servers, frameworks and system components are running the latest approved version.
    • Use safe exception handlers.
    • Disable any unnecessary Extended HTTP methods. If an Extended HTTP method that supports file handling is required, utilize an approved authentication mechanism. (e.g., WebDav).
    • Turn off directory listing.
    • Ensure SSL certificates have the correct domain name and are not expired.
    • Restrict the web server, process and service accounts to the least privileges possible.
    • Implement generic error messages and custom error pages that do not disclose system information.
    • When exceptions occur, fail secure.
    • Remove all unnecessary functionality and files.
    • Remove any test code.
    • Log all exceptions.
    • Restrict access to logs.
    • Log all administrative functions.
    • Use hashing technology to validate log integrity.
    • General Coding Practices

    • 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.
    • Use tested and approved managed code rather than creating new unmanaged code for common tasks.
    • Utilize locking to prevent multiple simultaneous requests to the application or use a synchronization mechanism to prevent race conditions.
    • Explicitly initialize all your variables and other data stores, either during declaration or just before the first usage.
    • Properly free allocated memory upon the completion of functions and at all exit points including error conditions.
    • In cases where the application must run with elevated privileges, raise privileges as late as possible, and drop them as soon as possible.
    • 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.
    • Do not pass user supplied data to any dynamic execution function.
    • Restrict users from generating new code or altering existing code.
    • Review all secondary applications, third party code and libraries to determine business necessity and validate safe functionality, as these can introduce new vulnerabilities.
    • 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.
    • Database Security

    • Use strongly typed parameterized queries. Parameterized queries keep the query and data separate through the use of placeholders. The query structure is defined with place holders and then the application specifies the contents of each placeholder.
    • Utilize input validation and if validation fails, do not run the database command.
    • Ensure that the input does not include unintended SQL keywords.
    • Ensure that variables are strongly typed.
    • Escape meta characters in SQL statements.
    • The application should use the lowest possible level of privilege when accessing the database.
    • Use secure credentials for database access.
    • Do not provide connection strings or credentials directly to the client. If this is unavoidable, credentials must be encrypted.
    • Use stored procedures to abstract data access.
    • Turn off any database functionality (e.g., unnecessary stored procedures or services).
    • Eliminate default content.
    • Disable any default accounts that are not required to support business requirements.
    • Close the connection as soon as possible.
    • The application should connect to the database with different credentials for every trust distinction (e.g., user, read-only user, guest, administrators).
    • File Management

    • Do not pass user supplied data directly to any dynamic include function. Limit the type of files that can be uploaded to only those types that are needed for business purposes.
    • Validate uploaded files are the expected type.
    • Do not save files in the web space. If this must be allowed, prevent or restrict the uploading of any file that can be interpreted by the web server. Turn off execution privileges on file upload directories.
    • Implement safe uploading in UNIX by mounting the targeted file directory as a logical drive using the associated drive letter or the chrooted environment.
    • When referencing existing files, use a hard coded 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, use a hard coded default file value for the content instead.
    • 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.
    • Do not pass directory or file paths, use index values mapped to hard coded paths.
    • Never send the absolute file path to the user.
    • Ensure application files and resources are read-only.
    • Implement access controls for temporary files.
    • Remove temporary files as soon as possible.
    • Memory Management

    • Utilize input validation.
    • Double check that the buffer is as large as specified.
    • 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.
    • Check buffer boundaries if calling the function in a loop and make sure there is no danger of writing past the allocated space.Truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
    • Use Non-executable stacks when available.
    • Avoid the use of known vulnerable functions (e.g., printf, strcat, strcpy, etc).