Think right scenarios

Thing right scenarios

Many organizations are aiming the most optimal product quality while development and QA processes. One side developer develop the product according the specifications provided by the business teams. Other side tester and QA teams test the product quality by various quality assurance processes, manual and automated testing and attempt to find the maximum defects during the QA process and testing. During this process QA team trying to ensure that client and/or end user consuming the product should not see the abnormality with respect to product functioning and it’s feature.

While designing the software product, BA, developer and tester’s goal is design or craft the right architecture, right test cases scenario, to make sure that particular application and product platform the way it is supposed to. At one hand it is absolute important to verify that the product perform it’s function as per the functional need, on the other hand it is equally or more important to verify that application or product gracefully handle the abnormal situations. It is obvious that most of the engineering and QA teams are working on the stated functionality by business teams and develop the software and test cases.

Handling of abnormal scenarios depends on the developers and tester’s creativity and knowledge/experience of eco system. But relying on developer and tester creativity cannot ensure the best quality product. For this we need to do more. In this paper I will discuss the right and wrong scenarios.

What are Positive and Negative Scenarios?

Positive scenario: Generally while defining the business scenario we define the happy situation.

Case1: Taking very basic two examples of the positive scenarios. Let’s take the case of user entry form of kid’s school admission and user input is “Date of Birth” of kids and parents “Date of Birth”. In the happy scenario developer provides a date control and tester create test case input field containing the date of birth for the kid and parent both.

Case2: As a complex example let’s consider that consumer withdraw money from the bank ATM.

# Business Scenario Steps Expected Result
1 Withdraw Money from the ABC Bank ATM –        Insert/Swipe the card in ATM.

–        Authorize and select Account

–        Enter Amount to withdraw.

–        Confirm the transaction

–        Collect cash

–        Collect Receipt

–        Money will be dispense from the ATM

–        Account will be debited.

–        User receives SMS and mail notification.


Developer will create the application based on the functionality provided in the above use case. These scenarios are “Happy Scenarios” and generally works fine because developer and tester both are focusing on the same.

Negative Scenarios: Now in all the above cases negative scenarios makes an impact for the quality of application/product. We dill discuss all the cases for the negative scenarios and also the owner of the scenarios.


  • In case of “Date of Birth” Date should be always less than the current date else someone can put the future date.
  • Parent date should always be greater than the kid’s birthday; otherwise data entry operator can enter the parent date of birth in kid’s date of birth field.
  • Most important that for the school kids age should be greater than ‘X’ month. It cannot be yesterday in the kid birthday field.


  • If customer inserts the card machine is not accepting the other bank’s card.
  • If customer is of same bank he enter wrong pin.
  • If customer enters the amount more than the limit of ATM money combination to dispense.
  • If customer is about the complete the transaction at the same time machine dispense system is malfunctioning and his money is debited in his book of accounts.

For thinking negative scenarios there are multiple owners and their creativity.

  • “Date of Birth” should be less than current date scenario should be covered by the designer, developer and QA team,
  • Parent’s date should be always less than kid date of birth also be covered by designer, developer and QA team
  • While for third case business team must define Age factor, this cannot be left on the developer and tester creativity.

In the above scenarios if everyone start right user cannot make mistake, so if BA defines possible negative business cases in requirement, developer define the technical negative scenarios and develop and tester defines the usability negative test cases and test in order to provide the softer to have expected output of product.

Factors to consider the negative scenarios:

Following are factors, which should be considered to define the negative scenarios.

  • Usability and handling mistakes
  • Business driven negative scenarios
  • Human Errors
  • Technology malfunctions
  • Environmental Glitches
  • Development Time Scenarios

Let’s discuss this in details.

Usability and Handling Mistakes

In the above example if data entry operator interchange the parent and kid date of birth then it is usability and handling mistake and for this developer and tester and BA should make it fool proof. In order to handle this there should be a check that parent DOB should always be greater than kid DOB.

Also DOB should always be less then current date. It is very similar to credit card expiry date field where month and year is always greater or equal to current date.

Business Driven Negative Scenarios

Business driven negative scenarios are those scenarios where BA must define the proper handling of business failure cases and negative scenarios. Like kids can start school after 36 month or amount in the ATM machine cannot exceed to a limit are basic examples.

Human Errors

Human errors are very common and it needs to be taken care in the system. For example user leaves certain column blank, or enters the wrong value in relevant field. Such cases require basic checks and negative scenarios of testing and in general making eliminates 90% of errors of the system.

Technology Malfunctions

None of the technology is perfect, every technology malfunction some or other time. ATM machine consist of many important technologies like machine, modem, Internet, and electricity, in this any part can malfunction. So all the failure scenarios must be defined in the negative scenarios.

Environmental Glitches

Many times system expected output changes because of the environment where system is operated. For example poor network can result in the non-performance of application while graphics loading; heavy pages may not be transmitted accurately but still it is part of allocation and system is not working as expected. So while developing and testing these things should be taken care.

Development Time Scenarios – Technical Exception

These are called technical exception handlings. Technical exceptions happen when a technical component of a business process acts in an unexpected way. When using Java based systems, this often results in a literal code Exception being thrown by the system. Technical components used in a process can fail in a way that cannot be described using process. In this case, it’s important to handle these exceptions in expected ways.

Generally developer creates a try catch and finally block and for all the exceptions they are using single exception, which is not correct. Every different exception scenario must be handled independently.

Let’s discuss some scenarios, which should be taken care by different roles.

Negative Scenarios and Exceptions Thinking

Business Exception Handling.

A business scenario is essentially a complete description of a business problem, both in business and in architectural terms, which enables individual requirements to be viewed in relation to one another in the context of the overall problem. Without such a complete description to serve as context:

  • There is a danger of the architecture being based on an incomplete set of requirements that do not add up to a whole problem description, and that can therefore misguide architecture work. So clearly create define all the alternative paths.
  • The business value of solving the problem is unclear
  • The relevance of potential solutions is unclear

Also, because the technique requires the involvement of business line management and other stakeholders at an early stage in the architecture project, it also plays an important role in gaining the buy-in of these key personnel to the overall project and its end-product – the IT architecture. Thinking of the business exception scenario can only be done by the business stakeholders, though developer and tester can add value but it is not their prime area to work on.

Creating a business scenario involves the following

1 – Identifying, documenting and ranking the problem driving the scenario

2 – Identify the business and technical environment of the scenario and documenting it in scenario models

3 – Identifying and documenting desired objectives (the results of handling the problems successfully)

4 – Identifying the human actors (participants) and their place in the business model

5 – Identifying computer actors (computing elements) and their place in the technology model

6 – Identifying and documenting roles, responsibilities and measures of success per actor; documenting the required scripts per actor, and the results of handling the situation

7 – Checking for “fitness for purpose” and refining only if necessary.

Technical Exception Handling

There are multiple areas in technical design and development which need to be taken care while handling negative scenarios, and these consists of the coding, information store, network, deployment etc. Here are some cases of Java, DB (oracle) ways to handle exception and negative scenarios.

  • Handle the common use negative scenarios
  • Use appropriate validation at each input and output level
  • Use Checked Exception for Recoverable error and Unchecked Exception for programming error.
  • Close or release resource in finally block
  • Including cause of Exception in stack-trace
  • Always provide meaning full message on Exception
  • Avoid overusing Checked Exception
  • Converting Checked Exception into Runtime Exception
  • Remember Exceptions are costly in terms of performance
  • Avoid empty catch blocks
  • Use Standard Exceptions
  • Document Exception thrown by any method
  • Have proper database exceptions handles at each level.

Below are oracle database standard exception and messages to deal the negative scenario.

Exception Name ORA Error SQLCODE Raised When …
ACCESS_INTO_NULL 06530 -6530 A program attempts to assign values to the attributes of an uninitialized object
CASE_NOT_FOUND 06592 -6592 None of the choices in the WHEN clauses of a CASE statement is selected, and there is no ELSE clause.
COLLECTION_IS_NULL 06531 -6531 A program attempts to apply collection methods other than EXISTS to an uninitialized nested table or v-array, or the program attempts to assign values to the elements of an uninitialized nested table or v-array.
CURSOR_ALREADY_OPEN 06511 -6511 A program attempts to open an already open cursor. A cursor must be closed before it can be reopened. A cursor FOR loop automatically opens the cursor to which it refers, so your program cannot open that cursor inside the loop.
DUP_VAL_ON_INDEX 00001 -1 A program attempts to store duplicate values in a column that is constrained by a unique index.
INVALID_CURSOR 01001 -1001 A program attempts a cursor operation that is not allowed, such as closing an unopened cursor.
INVALID_NUMBER 01722 -1722 n a SQL statement, the conversion of a character string into a number fails because the string does not represent a valid number. (In procedural statements,VALUE_ERROR is raised.) This exception is also raised when theLIMIT-clause expression in a bulkFETCH statement does not evaluate to a positive number.
LOGIN_DENIED 01017 -1017 A program attempts to log on to the database with an invalid username or password.
NO_DATA_FOUND 01403 +100 A SELECT INTO statement returns no rows, or your program references a deleted element in a nested table or an uninitialized element in an index-by table.

Because this exception is used internally by some SQL functions to signal completion, you must not rely on this exception being propagated if you raise it within a function that is invoked as part of a query.

NOT_LOGGED_ON 01012 -1012 A program issues a database call without being connected to the database.
PROGRAM_ERROR 06501 -6501 PL/SQL has an internal problem.
ROWTYPE_MISMATCH 06504 -6504 The host cursor variable and PL/SQL cursor variable involved in an assignment have incompatible return types. When an open host cursor variable is passed to a stored subprogram, the return types of the actual and formal parameters must be compatible.
SELF_IS_NULL 30625 -30625 A program attempts to invoke a MEMBER method, but the instance of the object type was not initialized. The built-in parameter SELF points to the object, and is always the first parameter passed to a MEMBER method.
STORAGE_ERROR 06500 -6500 PL/SQL ran out of memory or memory was corrupted.
SUBSCRIPT_BEYOND_COUNT 06533 -6533 A program references a nested table or v-array element using an index number larger than the number of elements in the collection.
SUBSCRIPT_OUTSIDE_LIMIT 06532 -6532 A program references a nested table or v-array element using an index number (-1 for example) that is outside the legal range.
SYS_INVALID_ROWID 01410 -1410 The conversion of a character string into a universal rowid fails because the character string does not represent a valid rowid.
TIMEOUT_ON_RESOURCE 00051 -51 A time out occurs while the database is waiting for a resource.
TOO_MANY_ROWS 01422 -1422 A SELECT INTO statement returns more than one row.
VALUE_ERROR 06502 -6502 An arithmetic, conversion, truncation, or size-constraint error occurs. For example, when your program selects a column value into a character variable, if the value is longer than the declared length of the variable, PL/SQL stops the assignment and raises VALUE_ERROR. In procedural statements, VALUE_ERROR is raised if the conversion of a character string into a number fails. (In SQL statements INVALID_NUMBER is raised.)
ZERO_DIVIDE 01476 -1476 A program attempts to divide a number by zero.

At the end I would like to emphasis  on the need of negative scenarios and exception handling and every team must define the negative scenarios in their capacity and understanding, it should start from the business team then designer, developer and at the end by testers. It is good if we involve the customer as well in this Journey.

Daya Shanker
Date: 5 Sept 2015


Secure CodingIntroduction

This Blog is intended to provide Secure Coding Practices in software development lifecycle and details of how to implement coding practice.

This Blog provides coding practices that can be translated into coding requirements without the need for the developer to have an in depth understanding of security vulnerabilities and exploits. However, other members of the development team should have the responsibility, adequate training, tools and resources to validate that the design and implementation of the entire system is secure.

Guidance on implementing a secure software development framework is beyond the scope of this paper, however the following additional general practices and resources are recommended:

Clearly define roles and responsibilities

  • Provide development teams with adequate software security training
  • Implement a secure software development lifecycle
  • Establish secure coding standards
  • Build a re-usable object library
  • Verify the effectiveness of security controls
  • Establish secure outsourced development practices including defining security

Software Security and Risk Principles Overview

Building secure software requires a basic understanding of security principles. While a comprehensive review of security principles is beyond the scope of this guide, a quick overview is provided.

The goal of software security is to maintain the confidentiality, integrity, and availability of information resources in order to enable successful business operations. This goal is accomplished through the implementation of security controls. This guide focuses on the technical controls specific to mitigating the occurrence of common software vulnerabilities. While the primary focus is web /mobile applications and their supporting infrastructure, most of the guidance can be applied to any software deployment platform.

It is helpful to understand what is meant by risk, in order to protect the business from unacceptable risks associated with its relevance on software. Risk is a combination of factors that threaten the success of the business. This can be described conceptually as follows: a threat agent interacts with a system, which may have a vulnerability that can be exploited in order to cause an impact. While this may seem like an abstract concept, think of it this way: a car burglar (threat agent) goes through a parking lot checking cars (the system) for unlocked doors (the vulnerability) and when they find one, they open the door (the exploit) and take whatever is inside (the impact). All of these factors play a role in secure software development.

There is a fundamental difference between the approach taken by a development team and that taken by someone attacking an application. A development team typically approaches an application based on what it is intended to do. In other words, they are designing an application to perform specific tasks based on documented functional requirements and use cases. An attacker, on the other hand, is more interested in what an application can be made to do and operates on the principle that “any action not specifically denied, is allowed”. To address this, some additional elements need to be integrated into the early stages of the software lifecycle. These new elements are security requirements and abuse cases. This guide is designed to help with identifying high level security requirements and addressing many common abuse scenarios.

It is important for web /mobile app development teams to understand that client side controls like client based input validation, hidden fields and interface controls (e.g., pull downs and radio buttons), provide little if any security benefit. An attacker can use tools like client side web proxies (e.g. OWASP Web Scarab, Burp) or network packet capture tools (e.g., Wire Shark) to analyse application traffic and submit custom built requests, bypassing the interface all together. Additionally, Flash, Java Applets and other client side objects can be decompiled and analysed for flaws.

Software security flaws can be introduced at any stage of the software development lifecycle, including:

  • Not identifying security requirements up front
  • Creating conceptual designs that have logic errors
  • Using poor coding practices that introduce technical vulnerabilities
  • Deploying the software improperly
  • Introducing flaws during maintenance or updating

Furthermore, it is important to understand that software vulnerabilities can have a scope beyond the software itself. Depending on the nature of the software, the vulnerability and the supporting infrastructure, the impacts of a successful exploitation can include compromises to any or all of the following:

  • The software and its associated information
  • The operating systems of the associated servers
  • The backend database
  • Other applications in a shared environment
  • The user’s system
  • Other software that the user interacts with

Secure Coding Practice Checklist

Input Validation

  • Conduct all data validation on a trusted system (e.g., The server)
  • Identify all data sources and classify them into trusted and untrusted. Validate all data from
  • Untrusted sources (e.g., Databases, file streams, etc.)
  • There should be a centralized input validation routine for the application
  • Specify proper character sets, such as UTF-8, for all sources of input
  • Encode data to a common character set before validating (Canonicalize)
  • All validation failures should result in input rejection
  • 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 parameters, URLs and HTTP
  • Header content (e.g. Cookie names and values). Be sure to include automated post backs from
  • JavaScript, Flash or other embedded code
  • Verify that header values in both requests and responses contain only ASCII characters
  • Validate data from redirects (An attacker may submit malicious content directly to the target of  the redirect, thus circumventing application logic and any validation performed before the
  • redirect)
  • Validate for expected data types
  • Validate data range
  • Validate data length
  • Validate all input against a “white” list of allowed characters, whenever possible
  • If any potentially hazardous characters must be allowed as input, be sure that you implement
  • additional controls like output encoding, secure task specific APIs and accounting for the
  • Utilization of that data throughout the application. Examples of common hazardous characters  include: < > ” ‘ % ( ) & + \ \’ \”
  • If your standard validation routine cannot address the following inputs, then they should be
  • checked discretely
  • Check for null bytes (%00)
  • Check for new line characters (%0d, %0a, \r, \n)
  • Check for “dot-dot-slash” (../ or ..\) path alterations characters. In cases where UTF-8 extended
  • character set encoding is supported, address alternate representation like: %c0%ae%c0%ae/
  • (Utilize canonicalization to address double encoding or other forms of obfuscation attacks)

Output Encoding

  • Conduct all encoding on a trusted system (e.g., The server)
  • Utilize a standard, tested routine for each type of outbound encoding
  • Contextually output encode all data returned to the client that originated outside the Application’s trust boundary. HTML entity encoding is one example, but does not work in all cases.
  • Encode all characters unless they are known to be safe for the intended interpreter
  • Contextually sanitize all output of un-trusted data to queries for SQL, XML, and LDAP
  • Sanitize all output of un-trusted data to operating system commands


Authentication and Password Management

  • Require authentication for all pages and resources, except those specifically intended to be public
  • All authentication controls must be enforced on a trusted system (e.g., The server)
  • Establish and utilize standard, tested, authentication services whenever possible
  • Use a centralized implementation for all authentication controls, including libraries that call external authentication services
  • Segregate authentication logic from the resource being requested and use redirection to and from the centralized authentication control
  • All authentication controls should fail securely
  • All administrative and account management functions must be at least as secure as the primary authentication mechanism
  • If your application manages a credential store, it should ensure that only cryptographically strong one-way salted hashes of passwords are stored and that the table/file that stores the passwords and keys is writeable only by the application. (Do not use the MD5 algorithm if it can be avoided)  Password hashing must be implemented on a trusted system (e.g., the server).
  • Validate the authentication data only on completion of all data input, especially for sequential authentication implementations
  • Authentication failure responses should not indicate which part of the authentication data was incorrect. For example, instead of “Invalid username” or “Invalid password”, just use “Invalid username and/or password” for both. Error responses must be truly identical in both display and source code
  • Utilize authentication for connections to external systems that involve sensitive information or functions
  • Authentication credentials for accessing services external to the application should be encrypted and stored in a protected location on a trusted system (e.g., the server). The source code is NOT a secure location
  • Use only HTTP POST requests to transmit authentication credentials
  • Only send non-temporary passwords over an encrypted connection or as encrypted data, such as in an encrypted email. Temporary passwords associated with email resets may be an exception
  • Enforce password complexity requirements established by policy or regulation. Authentication credentials should be sufficient to withstand attacks that are typical of the threats in the deployed environment. (e.g., requiring the use of alphabetic as well as numeric and/or special characters)
  • Enforce password length requirements established by policy or regulation. Eight characters is commonly used, but 16 is better or consider the use of multi-word pass phrases
  • Password entry should be obscured on the user’s screen. (e.g., on web forms use the input type “password”)
  • Enforce account disabling after an established number of invalid login attempts (e.g., five attempts is common). The account must be disabled for a period of time sufficient to discourage brute force guessing of credentials, but not so long as to allow for a denial-of service attack to be performed
  • Password reset and changing operations require the same level of controls as account creation and authentication.
  • Password reset questions should support sufficiently random answers. (e.g., “favorite book” is a bad question because “The Bible” is a very common answer)
  • If using email based resets, only send email to a pre-registered address with a temporary link/password
  • Temporary passwords and links should have a short expiration time
  • Notify users when a password reset occurs
  • Prevent password re-use
  • Passwords should be at least one day old before they can be changed, to prevent attacks on password reuse
  • Enforce password changes based on requirements established in policy or regulation. Critical systems may require more frequent changes. The time between resets must be administratively controlled
  • Disable “remember me” functionality for password fields
  • The last use (successful or unsuccessful) of a user account should be reported to the user at
  • their next successful login
  • Implement monitoring to identify attacks against multiple user accounts, utilizing the same password. This attack pattern is used to bypass standard lockouts, when user IDs can be harvested or guessed
  • Change all vendor-supplied default passwords and user IDs or disable the associated accounts
  • Re-authenticate users prior to performing critical operations
  • Use Multi-Factor Authentication for highly sensitive or high value transactional accounts
  • If using third party code for authentication, inspect the code carefully to ensure it is not affected by any malicious code

Session Manangement

Use the server or framework’s session management controls. The application should only recognize these session identifiers as valid

  • Session identifier creation must always be done on a trusted system (e.g., The server)
  • Session management controls should use well vetted algorithms that ensure sufficiently random session identifiers
  • Set the domain and path for cookies containing authenticated session identifiers to an appropriately restricted value for the site
  • Logout functionality should fully terminate the associated session or connection
  • Logout functionality should be available from all pages protected by authorization
  • Establish a session inactivity timeout that is as short as possible, based on balancing risk and business functional requirements. In most cases it should be no more than several hours
  • 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 mitigate negative impacts
  • If a session was established before login, close that session and establish a new session after a successful login
  • Generate a new session identifier on any re-authentication
  • Do not allow concurrent logins with the same user ID
  • Do not expose session identifiers in URLs, error messages or logs. Session identifiers should only be located in the HTTP cookie header. For example, do not pass session identifiers as GET parameters
  • Protect server side session data from unauthorized access, by other users of the server, by implementing appropriate access controls on the server
  • Generate a new session identifier and deactivate the old one periodically. (This can mitigate certain session hijacking scenarios where the original identifier was compromised)
  • Generate a new session identifier if the connection security changes from HTTP to HTTPS, as can occur during authentication. Within an application, it is recommended to consistently utilize HTTPS rather than switching between HTTP to HTTPS
  • Supplement standard session management for sensitive server-side operations, like account management, by utilizing per-session strong random tokens or parameters. This method can be used to prevent Cross Site Request Forgery attacks
  • Supplement standard session management for highly sensitive or critical operations by utilizing perrequest, as opposed to per-session, strong random tokens or parameters Set the “secure” attribute for cookies transmitted over an TLS connection
  • Set cookies with the HttpOnly attribute, unless you specifically require client-side scripts within your application to read or set a cookie’s value

Access Control

Use only trusted system objects, e.g. server side session objects, for making access authorization decisions

  • Use a single site-wide component to check access authorization. This includes libraries that call external authorization services
  • Access controls should fail securely
  • Deny all access if the application cannot access its security configuration information
  • Enforce authorization controls on every request, including those made by server side scripts, “includes” and requests from rich client-side technologies like AJAX and Flash
  • Segregate privileged logic from other application code
  • Restrict access to files or other resources, including those outside the application’s direct control, to only authorized users
  • Restrict access to protected URLs to only authorized users
  • Restrict access to protected functions to only authorized users
  • Restrict direct object references to only authorized users
  • Restrict access to services to only authorized users
  • Restrict access to application data to only authorized users
  • Restrict access to user and data attributes and policy information used by access controls
  • Restrict access security-relevant configuration information to only authorized users
  • Server side implementation and presentation layer representations of access control rules must match
  • If state data must be stored on the client, use encryption and integrity checking on the server side to catch state tampering.
  • Enforce application logic flows to comply with business rules
  • 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
  • Use the “referrer” header as a supplemental check only, it should never be the sole authorization check, as it is can be spoofed
  • If long authenticated sessions are allowed, periodically re-validate a user’s authorization to ensure that their privileges have not changed and if they have, log the user out and force them to re-authenticate
  • Implement account auditing and enforce the disabling of unused accounts (e.g., After no more than 30 days from the expiration of an account’s password.)
  • The application must support disabling of accounts and terminating sessions when authorization ceases (e.g., Changes to role, employment status, business process, etc.)
  • Service accounts or accounts supporting connections to or from external systems should have the least privilege possible
  • Create an Access Control Policy to document an application’s business rules, data types 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

Cryptographic Practice

All cryptographic functions used to protect secrets from the application user must be implemented on a trusted system (e.g., The server)

  • Protect master secrets from unauthorized access
  • Cryptographic modules should fail securely
  • All random numbers, random file names, random GUIDs, and random strings should be generated using the cryptographic module’s approved random number generator when these random values are intended to be un-guessable
  • Cryptographic modules used by the application should be compliant to FIPS 140-2 or an equivalent standard. (See
  • Establish and utilize a policy and process for how cryptographic keys will be managed
  • Log all system exceptions
  • Log all administrative functions, including changes to the security configuration settings
  • Log all backend TLS connection failures
  • Log cryptographic module failures
  • Use a cryptographic hash function to validate log entry integrity

Error Handling and Logging

  • Do not disclose sensitive information in error responses, including system details, session identifiers or account information
  • Use error handlers that do not display debugging or stack trace information
  • Implement generic error messages and use custom error pages
  • The application should handle application errors and not rely on the server configuration
  • Properly free allocated memory when error conditions occur
  • Error handling logic associated with security controls should deny access by default
  • All logging controls should be implemented on a trusted system (e.g., The server)
  • Logging controls should support both success and failure of specified security events
  • Ensure logs contain important log event data
  • Ensure log entries that include un-trusted data will not execute as code in the intended log viewing interface or software
  • Restrict access to logs to only authorized individuals
  • Utilize a master routine for all logging operations
  • Do not store sensitive information in logs, including unnecessary system details, session identifiers or passwords
  • Ensure that a mechanism exists to conduct log analysis
  • Log all input validation failures
  • Log all authentication attempts, especially failures
  • Log all access control failures
  • Log all apparent tampering events, including unexpected changes to state data
  • Log attempts to connect with invalid or expired session tokens

Data Protection

  • Implement least privilege, restrict users to only the functionality, data and system information that is required to perform their tasks
  • Protect all cached or temporary copies of sensitive data stored on the server from unauthorized access and purge those temporary working files a soon as they are no longer required.
  • Encrypt highly sensitive stored information, like authentication verification data, even on the server side.

Always use well vetted algorithms, see “Cryptographic Practices” for additional guidance

  • Protect server-side source-code from being downloaded by a user
  • Do not store passwords, connection strings or other sensitive information in clear text or in any non- cryptographically secure manner on the client side. This includes embedding in insecure formats like: MSviewstate, Adobe flash or compiled code
  • Remove comments in user accessible production code that may reveal backend system or other sensitive information
  • Remove unnecessary application and system documentation as this can reveal useful information to attackers
  • Do not include sensitive information in HTTP GET request parameters
  • Disable auto complete features on forms expected to contain sensitive information, including authentication
  • Disable client side caching on pages containing sensitive information. Cache-Control: no-store, may be used in conjunction with the HTTP header control “Pragma: no-cache”, which is less effective, but is HTTP/1.0 backward compatible
  • The application should support the removal of sensitive data when that data is no longer required. (e.g. personal information or certain financial data)
  • Implement appropriate access controls for sensitive data stored on the server. This includes cached data, temporary files and data that should be accessible only by specific system users

Communication Security

  • Implement encryption for the transmission of all sensitive information. This should include TLS for protecting the connection and may be supplemented by discrete encryption of sensitive files or non-HTTP based connections
  • TLS certificates should be valid and have the correct domain name, not be expired, and be installed with intermediate certificates when required
  • Failed TLS connections should not fall back to an insecure connection
  • Utilize TLS connections for all content requiring authenticated access and for all other sensitive information
  • Utilize TLS for connections to external systems that involve sensitive information or functions
  • Utilize a single standard TLS implementation that is configured appropriately
  • Specify character encodings for all connections
  • Filter parameters containing sensitive information from the HTTP referrer, when linking to external sites

System Configuration

  • Ensure servers, frameworks and system components are running the latest approved version
  • Ensure servers, frameworks and system components have all patches issued for the version in use  Turn off directory listings
  • Restrict the web server, process and service accounts to the least privileges possible
  • When exceptions occur, fail securely
  • Remove all unnecessary functionality and files
  • Remove test code or any functionality not intended for production, prior to deployment
  • Prevent disclosure of your directory structure in the robots.txt file by placing directories not intended for public indexing into an isolated parent directory. Then “Disallow” that entire parent directory in the robots.txt file rather than Disallowing each individual directory
  • Define which HTTP methods, Get or Post, the application will support and whether it will be handled differently in different pages in the application
  • Disable unnecessary HTTP methods, such as WebDAV extensions. If an extended HTTP method that supports file handling is required, utilize a well-vetted authentication mechanism
  • If the web server handles both HTTP 1.0 and 1.1, ensure that both are configured in a similar manor or insure that you understand any difference that may exist (e.g. handling of extended HTTP methods)
  • Remove unnecessary information from HTTP response headers related to the OS, web-server version and application frameworks
  • The security configuration store for the application should be able to be output in human readable form to support auditing
  • Implement an asset management system and register system components and software in it
  • 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
  • Implement a software change control system to manage and record changes to the code both in development and production

Database Security

  • Use strongly typed parameterized queries
  • Utilize input validation and output encoding and be sure to address Meta characters. If these fail, do not run the database command
  • Ensure that variables are strongly typed
  • The application should use the lowest possible level of privilege when accessing the database
  • Use secure credentials for database access
  • 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.
  • Use stored procedures to abstract data access and allow for the removal of permissions to the base tables in the database
  • Close the connection as soon as possible
  • Remove or change all default database administrative passwords. Utilize strong passwords/phrases or implement multi-factor authentication
  • 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 (surface area reduction))

File Management

  • Do not pass user supplied data directly to any dynamic include function
  • Require authentication before allowing a file to be uploaded
  • 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 by checking file headers. Checking for file type by extension alone is not sufficient
  • Do not save files in the same web context as the application. Files should either go to the content server or in the database.
  • Prevent or restrict the uploading of any file that may 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 path or the chrooted environment
  • 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
  • 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 pre-defined list of paths
  • Never send the absolute file path to the client
  • Ensure application files and resources are read-only
  • Scan user uploaded files for viruses and malware

Memory Management

  • Utilize input and output control for un-trusted data  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
  • Specifically close resources, don’t rely on garbage collection. (e.g., connection objects, file handles, etc.)
  • Use non-executable stacks when available
  • Avoid the use of known vulnerable functions (e.g., printf, strcat, strcpy etc.)
  • Properly free allocated memory upon the completion of functions and at all exit points

General Coding Practice

  • Use tested and approved managed code rather than creating new unmanaged code for common tasks
  • 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 checksums or hashes to verify the integrity of interpreted code, libraries, executables, and configuration files
  • Utilize locking to prevent multiple simultaneous requests or use a synchronization mechanism to prevent race conditions
  • Protect shared variables and resources from inappropriate concurrent access
  • Explicitly initialize all your variables and other data stores, either during declaration or just before the first usage
  • 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
  • Remove unnecessary default vendor content (e.g., sample schemas)
  • Disable any default accounts that are not required to support business requirements
  • The application should connect to the database with different credentials for every trust distinction (e.g., user, read-only user, guest, administrators)

OWASP Top 10 Vulnerabilities

The names of the risks in the Top 10 stem from the type of attack, the type of weakness, or the type of impact they cause. We chose the name that is best known and will achieve the highest level of awareness.

Injection flaws, such as SQL, OS, and LDAP injection, occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing unauthorized data.
Cross Site Scripting (XSS)
XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation and escaping. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.
Broken Authentication and Session Management
Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys, session tokens, or exploit other implementation flaws to assume other users’ identities.
Insecure Direct Object References
A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data.
Cross Site Request Forgery (CSRF)
A CSRF attack forces a logged-on victim’s browser to send a forged HTTP request, including the victim’s session cookie and any other automatically included authentication information, to a vulnerable web application. This allows the attacker to force the victim’s browser to generate requests the vulnerable application thinks are legitimate requests from the victim.
Security Misconfiguration
Good security requires having a secure configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform. All these settings should be defined, implemented, and maintained as many are not shipped with secure defaults. This includes keeping all software up to date, including all code libraries used by the application.
Insecure Cryptographic Storage
Many web applications do not properly protect sensitive data, such as credit cards, SSNs, and authentication credentials, with appropriate encryption or hashing. Attackers may steal or modify such weakly protected data to conduct identity theft, credit card fraud, or other crimes.
Failure to Restrict URL Access
Many web applications check URL access rights before rendering protected links and buttons. However, applications need to perform similar access control checks each time these pages are accessed, or attackers will be able to forge URLs to access these hidden pages anyway.
Insufficient Transport Layer Protection
Applications frequently fail to authenticate, encrypt, and protect the confidentiality and integrity of sensitive network traffic. When they do, they sometimes support weak algorithms, use expired or invalid certificates, or do not use them correctly.
Unvalidated Redirects and Forwards
Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.