Quote

"Between stimulus and response there is a space. In that space is our power to choose our response.
In our response lies our growth and freedom"


“The only way to discover the limits of the possible is to go beyond them into the impossible.”


Showing posts with label Application Security. Show all posts
Showing posts with label Application Security. Show all posts

Monday, 5 October 2015

Essentials of Secure Coding


Build Security, Test Security or Both?


Generally it is easier to build a secure software than to correct security flaws later, let alone an eventuality of a security breach. Cost of a security breach can be humongous and unbearable at times. Security attacks are gradually shifting base to the application layer in the software ecosystem as shown by a study which reported more than 60% of attacks on the internet are against web applications.

Software security flaws can be introduced at any stage of software development life cycle. Possible stages/ways of introduction of security flaws are as follows:

  • Introduction of security flaws by design errors
  • Introduction of security flaws by undefined security requirements
  • Introduction of security flaws by bad coding practices
  • Introduction of security flaws by incorrect deployment
  • Introduction of security flaws in maintenance/fixes
  • Introduction of security flaws in software updates 

So What Do We Do?


To build a secure software  there are several to dos and must haves. While detection of security vulnerabilities using security testing is a reactionary approach a mature development model assimilating security into it is more likely to produce minimal vulnerabilities when the software system is security tested and subsequently released.


Software security maturity models recommend various practices, processes, training to achieve a secure software development and delivery ecosystem.  However eventually most essential base for developing secure software is to bring secure coding practices on the work floor and making it integral part of the entire echo system. Each and every developer should and must learn secure coding practices and make it a part of implementation while coding.


Explicitly State Security Requirements


Security requirements should be ‘a must have’ in requirements document. Just like any other requirement they need to be elaborated thoroughly before implementation. Focusing only on functional requirement has been the primary factor for slippage of vulnerabilities and hence the development of insecure software. Developers and related product teams should be aware that there are tools and proxies available to intercept, analyze and modify the application traffic/request /response. If vulnerabilities creep in these layers they are likely to be exploited and have consequences. 


Essential Security Checklist for Coders



Every coder should have essential security checklist in his mind when coding. High level headers in this checklist should include the following:

  • Data Protection
  • Input Validation
  • Output Encoding
  • Access control
  • Session Management
  • Authentication and Password Management
  • Database Security
  • Memory Management  
  • File Management
  • Cryptographic Techniques
  • System Configuration
  • Error Handling and Logging


Data Protection


Implement the system of least privilege and encrypt all sensitive information that is stored. Do not store passwords, connection strings, or other sensitive information in clear text. Protect backend code from download or comments revealing useful information. HTTP GET request parameters should not include sensitive information and disable/filter/encrypt client side caching. Application should also support removal of sensitive data when not required. 

Input Validation


Canonicalize input data i.e. all inputs should be encoded in common character set, such as UTF-8 before being validated. Input validation should be uniform and central to the entire application using a uniform set of rules for validation of input data. Validate expected data type, range, length, and ensure that header values in request and response contain only ASCII chars. If commonly known potential hazardous characters, such as < > " ' % ( ) & + \ \' \" are to be allowed in application input then make sure to have additional sanitization measures such as output encoding. Also make sure you check for the following if it is not a part of the standard input validation routine:
Check for null bytes ()
Check for new line characters (%0d, %0a, \r, \n)
Check for “dot-dot-slash" (../ or ..\) path alterations characters.

Output Encoding


All characters must be encoded unless the intended interpreter is known to be safe. Encoding must be done on a trusted system which is typically the server. Contextually sanitize all output of untrusted data to queries for LDAP, SQL and XML. An example of HTML entity encoding is as follows:
Convert > to &gt; 
Convert < to &lt; 
Convert “ to &quot;
Convert ‘ to &#x27;

Convert / to &#2F;

Access Control


Enforce authorization control on every request that comes from both: server side scripts and client side scripts. Restrict the following only to authorized users:

  • Access to protected URLs and functions
  • Direct object references
  • Access to services and application data
  • Policy information used for access controls


Limit number of transactions a single user/device can perform and revalidate long authentication sessions. Ensure the application supports disabling of account and forced logouts. 


Session Management


Every application requires a set of controls that help ensure web applications handle HTTP sessions in a secure manner. Set of common practices that help in secure session management are as follows:

  • Session inactivity timeout should be as short as possible
  • Always use frameworks session management controls on a trusted server
  • All pages protected by authorization should have logout
  • Logout should kill associated session or connection
  • Session information should not be revealed in URL
  • Re-authentication should always generate new session identifier
  • Disallow concurrent logins with same user ID
  • Cookies transported over TLS need to be set as ‘secure’
  • Replace the per session paradigm to per request for highly sensitive transactions
  • Always set cookies with HttpOnly attribute, until unavoidable  



These essentials when kept in mind while coding and designing build a strong foundation for a secure application development and delivery. Will try putting up more points to the checklist in following posts.

Thursday, 11 December 2014

Static or Dynamic Security? How to Prioritize Between SAST or DAST?



When it comes to picking up a security testing strategy there are multiple options and players with varied recommendations. One of the dilemma is to which of the testing strategies to choose between Static and Dynamic commonly known as SAST and DAST. 

The ideal way is obviously to have both but budget, technology and delivery considerations might throw up the questions, such as:

Which one to choose first? Which is more effective and needed?

Well the answers to these questions will obviously be dependent on the unique conditions of the project/domain/organization but knowing definitive aspects of SAST and DAST will help relate to circumstances.

SAST: Static Application Security Testing

As the name suggests SAST is static application security testing and is concerned with the static code analysis and finding vulnerabilities in code, binary, or the byte code. A running system is not required for vulnerability assessment in this technique of security testing. The advantages of this technique are:

ADVANTAGES of Using SAST

  • Get to know the security flaws while the code is being developed
  • Do not need a deployment environment to perform security testing
  • Earliest possible detection of security flaws
  • Encourages use of secure coding practices in organizations
  • Enables identification of root cause of security issues
  • Enables identification of developers following secure coding practices
  • Ideal for development phase
  • While it may seem that SAST is perfect it has its limitations most of which are addressed by dynamic application security testing.

DAST: Dynamic Application Security Testing

Dynamic application security testing technique aims at identifying security vulnerabilities in runtime environment. It aims at finding vulnerabilities by emulating hackers behaviors of attacking the application when it is fully deployed and running. This technique does not look at the source code or the binary to assess vulnerabilities in the application. The advantages of this technique are as follows:

ADVANTAGES of Using DAST
  • Simulates hacker behavior
  • Finds vulnerabilities created by the gaps in deployment
  • Can find flaws in business logic
  • Capable of detecting vulnerabilities in third party libraries
  • Code submission is not needed
  • Comparatively lower in cost
  • Easier to adopt
Since DAST is not associated with development cycle it generally does not provide valuable feedback for infusing security in the development process. It is more of a preventive technique rather making secure applications as a part of the organizational DNA. It is also difficult to trace the location or origin of the threat/vulnerability to the exact location in the code.

False Positives

Common issue with both techniques is the issue of false positives. Minimizing the false positives returned using both the techniques remains a challenge though with the growth in maturity of the security testing group they are easily identified. Most of the tools enabling SAST or DAST enable users to customize them in order to shut/modify the rules that return false positives.

SAST and DAST Both Needed

DAST being the relatively cheaper and the quick fix type of option should always be used before production deployment. This certifies the strength of the application to counter actual hacker threats. While SAST usage enhances the development practices in terms of application security and addresses most of the issues in the root. Identification of security fixes for the vulnerabilities found out using SAST are relatively easier to fix most of the times. Both the techniques complement each other and address threats at different levels.

Thursday, 13 November 2014

Managing the Ever Increasing Stack of Passwords



As per recent analysis 73 percent people use same password for accessing multiple sites, average number of characters used in a password is 6 and it takes around 3 minutes to crack an average password.

Remembering passwords is becoming increasingly difficult with ever increasing online functions and tasks. The increased consumer inclination/confidence towards online shopping/banking/travel etc has lead to generation of a heap of passwords. On the professional front as most offices are already computerized you have another set of passwords to remember, such as the Windows network logon, official e-mail account, your website's FTP password, online passwords (like website member account), etc. etc. etc. The list is endless. From office to home to travel you need them all the time. Not only you need to remember passwords but you are need to keep them strong and change from time to time.

Some use a common password for access to different systems but it has the risk that if the common password is hacked then all the resources can be hacked from e-mail to bank account. So while it is a recommendable practice to keep unique password for accessing each system, it again leaves us with the difficult task of managing plethora of passwords.

Using Password Managers

One of the solutions to this problem is the use of password manager applications such as KeePass, and LastPass. KeePass is a free open source password manager, which helps you to manage your passwords in a secure way. You can put all your passwords in one database, which is locked with one master key or a key file. So you only have to remember one single master password or select the key file to unlock the whole database. The databases are encrypted using the best and most secure encryption algorithms currently known (AES and Twofish). LastPass is another password manager which offers free as well as paid services for individual and enterprise password management solutions.  

Using a Private Pattern

The method of relying on another application/password manager is good but what about the cases when the system is down/unavailable? Or what about cases when the password to the password manager is compromised? Any data that is stored no matter how strong is the encryption or how safe is the place is vulnerable. Till date human brain is the safest place to store data if we can pull it out accurately when needed.

A solution to this problem is creating a pattern for generating unique passwords for each site. All we need to remember is the pattern for generating unique passwords. An example of a pattern used/suggested by a leading security expert is to split the pattern into two parts. First component would be the fixed and the second component is dependent of the domain name of the site you are accessing.

It is important to have the first/fixed part of 7 to 8 characters as complex as you can remember for example 1BeEradE
Now once you have decided on the fixed part, all you need to do is create a pattern based on the domain name of the site to be accessed. Pattern can be of your choice for example to increment or decrement first three or last three characters of the domain name of the site to be accessed. Let us say we need to access Flipkart.com and our pattern is to pick the next letter to the first three characters of the site name. So our password for Flipkart.com will be 1BeEradEgmj. Our password for snapdeal.com will be 1BeEradEtob.

Using this technique we can remember the passwords to any site that we access as all we need to remember is ONE fixed password and a secret pattern.  Wish you a Happy and a safe Browsing!

Friday, 8 August 2014

How to look at application security, Top-Down or Bottom-Up?


As a software professional I have been infatuated to application security more than once in my career purely out of interest as none of the assignments directly held me responsible for application security.

The more I tried to understand the subject top-down the more slippery and complex it appeared. After many slips I realized it is a subject better understood bottom-up. You need to first understand a specific vulnerability in a piece of code and how it can be exploited by hackers. Then keep running through the list of vulnerabilities and break them one by one.

Once you have the dots of the vulnerabilities solved you need to connect them to see the holistic framework of application security. I personally found this approach less fuzzy than trolling through endless definitions, tools, tips and tricks.

So let us begin with some vulnerable pieces of codes and analyze them to see how they can be exploited by hackers.

Code Block 1:


String objectCount =  request.getParams("ObjCount");
int numObjCount = Integer.parseInt(objectCount);
ObjectArray [] arrayofObjects = new ObjectArray[numObjCount];

This code works fine functionally and should not cause an issue until exploited by a hacker to build a huge array whose size is determined by a request parameter. A huge number passed as a parameter which is used for determining the array size can lead to memory leaks and consequently DoS (Denial of Service) type of attacks.

A simple check can deny a hacker the potential to exploit the vulnerability:

String objectCount =  request.getParams("ObjCount");
int numObjCount = Integer.parseInt(objectCount);
if(numObjCount <= protectedAcceptableNo)
ObjectArray [] arrayofObjects = new ObjectArray[numObjCount];


Code Block 2:



class CustomerDAO {

    … …

   public void createCustomer(CustInfo cust) 

                 throws CustCreationException {

       … …

           try {

            Connection conn = DAOFactory.getConnection();

            CallableStatement  calaStmt = conn.prepareCall(…);

          …  …             

           calStmt.executeUpdate();

           calStmt.close();

          conn.close();

       }  catch (java.sql.SQLException e) {

            throw CustCreationException (...);

       }

    }

}

As we can see in the code block above the connection is closed in the try block. If  a SQLException happens before the close() call then the connection will not be closed. If an attacker comes to know about this vulnerability, they can exploit it by sending multiple requests that result in SQLExceptions and hence exhausting the connection pool. A small change can make the code secure from such attacks.

class CustomerDAO {

    … …

   public void createCustomer(CustInfo cust) 

                 throws CustCreationException {

       … …

           try {

            Connection conn = DAOFactory.getConnection();

            CallableStatement  calaStmt = conn.prepareCall(…);

          …  …             

           calStmt.executeUpdate();

           calStmt.close();

          conn.close();

       }  catch (java.sql.SQLException e) {

            throw CustCreationException (...);

       }finally{
       if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) { /* ignored */}
    } 
}

    }
}

The above two examples show how gaps in code can be used to exploit and perpetrate DoS type of attacks on an application. In subsequent posts I will try to bring more vulnerable code examples to demonstrate different type of security threats. However the moot point that I wanted to drive is that: Application security risk mitigation or a contingency plan is better prepared using a bottom up approach instead of a top down approach.