Author Archives: rohit

Get Practical mobile forensics book for just $5 now!

5 Dollar - Social Media


Packt Publishing will be celebrating the holiday season with $5 offer.  From Thursday 18th December, every eBook and video will be available on the publisher’s website for just $5 till 6th January. Here is the link to grab a copy of Practical mobile forensics book for just $5!!


Posted by on December 24, 2014 in iPhone

1 Comment

A brief overview of same-origin policy

Can My JavaScript Access Your Page Elements?

We all know that using JavaScript you can do many things for example read elements on a page, analyze the DOM etc. Now assume that you logged into and in another browser tab visited The question is can a script present in access the elements on the page loaded by The answer is a big NO. Imagine the chaos it would have caused if the answer is yes! But the scripts loaded by can happily access the page elements. So how does the browser decide which script can access which page? This is where Same Origin Policy comes in! SOP is one of the most important security concepts that govern how the modern web browsers work. This article explores about SOP, SOP rules and some techniques to bypass SOP.

Same-Origin Policy

Same-Origin Policy permits scripts running on pages originating from the ‘same site’ or ‘same origin’ to access each other’s DOM with no specific restrictions, but prevents access to DOM on different sites. So the how does browser identify whether the script and the page are from ‘same origin’ or not? The origin is calculated based on the combination of scheme, host and port. For example the scheme, host and port for are calculated as below:

Scheme: https || Host: facebook || Port: 8080

Browsers consider two resources to be of the same origin if and only if all these values are exactly the same. For example and are not same origin because the host is different.

Note: IE browser has 2 exceptions while checking for same origin

  1. IE doesn’t include port while calculating ‘origin’
  2. Same origin policy is not applied for sites which are under highly trusted zone.

Also note that SOP is not just limited to JavaScript. It also applies for XMLHttpRequest, Cookies, and Flash etc. We will see more about the same in the below sections.

Exceptions to SOP and their risks

SOP poses significant problems to large website which use multiple domains (due to the difference in the hostname).  Hence there are some exceptions which can be used to relax it.

Scripts that set domain to the same value:

You can use JavaScript to set the value of document.domain property. If two pages contain scripts which set domain to the same value, the SOP is relaxed for these two windows, and each window can interact with the other. For example, consider the earlier scenario where a script present on cannot access the DOM of a page loaded by Now if this script (present on sets its document.domain to then the script can happily access the DOM. Also note that a script cannot set the value of document.domain to any hostname. It can set the value only to a suffix of the current domain.

Risk: This is relatively safe because we are only talking about sub domains of a site. So scope for someone exploiting this is relatively low unless the sub domain is compromised.

CORS [Cross Origin Resource Sharing]:

CORS is a HTML5 feature that allows one site to access another site’s resources even if both are of different domains. Hence with CORS, JavaScript on a webpage can initiate an AJAX request to another site. To allow this process, the server which implements CORS, adds a HTTP header named ‘Access-Control-Allow-Origin:’ in the response. Now the even though is not of same origin can access this server’s pages.

Risk: Developers often tend to use ‘*’ to get the things working. CORS, being relatively new concept, is often misunderstood. If a site sets Access-Control-Allow-Origin:* it means an attacker can initiate AJAX request to this site with his JavaScript and can access the resources.  Hence while security testing a HTML5 site which has CORS enabled, look for Access-Control-Allow-Origin header to check if it allows only the allowed sites.

CDM [Cross Document Messaging]:

CDM or Cross Document Messaging is also one of the features introduced in HTML 5. This feature allows documents to communicate with one another across different domains. For example, Document A present on can communicate with document X present on (assume its present as an iframe) by issuing the below request from JavaScript:

var c = document.getElementsByTagName(‘iframe’)[0];
c.contentWindow.postMessage(‘Hiee’, ‘’);

Upon receiving this request, the script present on can respond back using the event listener.

function receiver(event) {
     if (event.origin == '') {
         if ( == 'Hiee') {
            event.source.postMessage('how are you?', event.origin);
         else {
               } } }

Risk: If the origin checking of the sender site is not done properly, there is a chance to run malicious code from other domains. It is also recommended to check the format of the incoming data to make sure that it is in the expected format.


Repeating the golden rule – You cannot make a cross domain Ajax request to update a current page. Here it is important to note that SOP does not restrict a site from loading JavaScript files from a different domain. With JSOP, by adding a <script> element to the page you can load JSON response from different domain. Because the code is loaded by the <script> tag, it can be normally executed. The below figure sums up everything!


Risk: Suppose a page hosted on uses JSONP to access services provided by then, the site has to completely trust From security perspective, excessive trust on other sites is never good. If is malicious it can run malicious code on the page loaded by Also a malicious page can request and obtain JSON data of another site by using the <script> tag and hence can be used to launch CSRF attacks.

Getting Around SOP

There are ways to turn off same origin policy in browsers. This can be exploited by attackers during targeted attacks on certain individuals. If an attacker can have physical access to the target system, he can turn off the SOP in that browser and can then launch his attack later on to steal certain information from the websites browsed by the user. Below are the options to turn off SOP in different browsers.

Internet Explorer:
-> Go to the Security tab. For the current zone click the ‘Custom level’ button.
-> In the next window, look for ‘Miscellaneous > Access data sources across domains’ and set it to “Disable”.

IE security settings

-> Open the Mozilla browser and enter ‘about:config’
-> Search for security.fileuri.strict_origin_policy and change the value to false by double clicking it as shown below.

firefox security settings

Google Chrome:
-> Start the chrome by passing the below argument:
C:\Program Files\Chrome\Chrome.exe –disable-web-security

-> Start the Safari by passing the below argument:
C:\Program Files\Safari\Safari.exe –disable-web-security



Posted by on April 30, 2014 in web application hacking


Tags: , ,

Elliptic Curve Cryptography: A Case for Mobile Encryption

It is needless to start this article explaining about the rise of mobile devices in the last few years. We all know about how smart phones have swept the world. But with mobiles you always look for concepts or solutions which are computationally cheap. For example, Android OS uses a dex compiler to convert the Java Byte code to .dex files before compiling them. Why? Because dex files are optimized code for low memory and low processing systems. Similarly when it comes to encryption on mobile devices we look for solutions which are computationally cheap and yet secure. ECC (Elliptic Curve Cryptography) provides exactly the same. This article explains about the why and how ECC is different from the other encryptions.

What is the need for an alternative encryption scheme when you have RSA?

Mobile phones have 2 main limitations:

  1. Computational limitations – Because the processors used on mobile devices are less capable compared to the ones used on a desktop system. Although there are a few devices which use dual core/quad core, most of the mobiles in general are not equipped with these kinds of CPU’s. 2.
  2. Battery Life – Mobile devices run throughout the day and battery consumption is one of the important aspects for the success of a device. The more computations a device has to perform the more battery life is consumed.

Consider a normal user who visits a banking site on his mobile device to transfer money to his friend. A low processing powered mobile device would struggle with the 1024 bit computations of RSA. With major financial institutions, the smallest key size allowed for RSA is 1024 bits. This activity not only takes time to complete but also eats into the battery life of the device.

What is ECC?

Elliptical curve cryptography (ECC) is a public key encryption technique based on elliptic curve theory that can be used to create faster, smaller, and more efficient cryptographic keys. So let us analyze the ECC algorithm by considering 2 factors – Security & Efficiency.


When we talk about public key encryption algorithms, the first things that come to mind are RSA and Diffie-Hellman. Both these algorithms use 1024 bit keys for major transactions. But it’s important here to note that NIST (National Institute for Standards and Technology) has recommended 1024 bit parameters only till the year 2010. The RSA algorithm is into its 40th birthday and probably regarded as the standard public key exchange on the Internet. After 2010, NIST believes that the existing systems be upgraded to a different set up to provide more security (although we no longer believe NSA or NIST :)). One option is to simply increase the key size used with these algorithms. However you are not quite sure as to what is the safe key size. Other option is to switch to a different set up which is more secure. ECC here comes to rescue. ECC generates keys through the properties of the elliptic curve equation instead of the traditional method of generation as the product of very large prime numbers.

RSA’s security is based on the principle that factoring is slow and hard i.e. it is difficult to factor a large integer composed of two or more large prime factors. With the improvements in technology, the gap between factoring and multiplying is slowly reducing. In the coming years, certainly this is bound to break. Switching to a larger key size is one option but it would only give the breathing space for a few more years.

An elliptic curve is represented as a looping line intersecting two axes. ECC is based on properties of a particular type of equation created from the mathematical group derived from points where the line intersects the axes. Multiplying a point on the curve by a number will produce another point on the curve, but it is very difficult to find what number was used, even if you know the original point and the result. For elliptic-curve-based protocols, it is assumed that finding the discrete logarithm of a random elliptic curve element with respect to a publicly known base point is infeasible –this is called as the elliptic curve discrete logarithm problem or ECDLP. Equations based on elliptic curves have a characteristic that is very valuable for cryptography purposes: they are relatively easy to perform, and extremely difficult to reverse. Despite almost three decades of research, mathematicians still haven’t found an algorithm to solve this problem. To state in simple words, for numbers of the same size, solving elliptic curve discrete logarithms is significantly very much harder than factoring. ECC was developed by Certicom, a mobile e-business security provider. RSA has been developing its own version of ECC. Other manufacturers, including Motorola, Cylink, Siemens, and VeriFone etc have already included support for ECC in their products.

The curious case of Angela Merkel’s phone tapping 🙂

A few months back, the news that German Chancellor Angela Merkel’s phone was tapped by the US government has created quite a scene. Amid this controversy there was also news that Merkel used 2 phones – one BlackBerry (encrypted) and the other Nokia (not encrypted). In September, new government phones which were manufactured by the Canadian company BlackBerry were delivered to all government officials (including Merkel) after being updated by the German company Secusmart. They contain a special encryption card that scrambles speech and data before transmitting it. So this Secusmart card used the Elliptic curve cryptography to encrypt and decrypt the mobile speech. And just because it is encrypted doesn’t mean its safe. It all depends upon how difficult it is to crack the key.


In terms of efficiency, ECC wins the race by large margin. The below table explains it all. The following table gives the key sizes recommended by the National Institute of Standards and Technology to protect keys used in conventional encryption algorithms like the (DES) and (AES) together with the key sizes for RSA, Diffie-Hellman and elliptic curves that are needed to provide equivalent security.

crypto key sizes

For instance to protect 128-bit AES keys using RSA or Diffie-Hellman you need to use 3072-bit parameters. The equivalent key size for elliptic curves is only 256 bits. Also, as the symmetric key size increases, the corresponding RSA/Diffie Hellman key size increases at a much higher rate compared to ECC key size. This is particularly a strong case for moving towards ECC on low powered environments like mobile devices, wireless devices, smart cards etc.

Real word ECC – is it safe?

The reports leaked by Edward Snowden suggested that Dual Elliptic Curve Deterministic Random Bit Generation (or Dual_EC_DRBG) had been included as a NIST national standard due to the influence of NSA, which had included a deliberate weakness in the algorithm and the recommended elliptic curve. RSA Security then issued an advisory recommending that its customers discontinue using any software based on Dual_EC_DRBG. Wikipedia mentions “Implementations which used Dual_EC_DRBG would usually have gotten it via a library. At least RSA Security (BSAFE library), OpenSSL, Microsoft, and Cisco has libraries which included Dual_EC_DRBG, but only BSAFE used it by default. According to the Reuters article which revealed the secret $10 million deal between RSA Security and NSA, RSA Security’s BSAFE was most important distributor of the backdoored algorithm. There was a flaw in OpenSSL’s implementation of Dual_EC_DRBG that made it non-working outside test mode, from which OpenSSL’s Steve Marquess concludes that nobody used OpenSSL’s Dual_EC_DRBG implementation”. All these point out the dark side of the NSA 🙂

However there are several different standards which propose ways of selecting curves for use in elliptic-curve cryptography (ECC). Each of these standards tries to make sure that the elliptic-curve discrete-logarithm problem (ECDLP – the problem of finding an ECC user’s secret key, given the user’s public key) is difficult. Below are some of the standards in use:

  • ANSI X9.62
  • IEEE P136
  • SEC 2
  • NIST FIPS 186-2
  • ANSI X9.63
  • Brainpool
  • NSA Suite B
  • ANSSI FRP256V1

Hence selecting the right curve and parameters is also important to ensure real world ECC security. More information can be found at the link:

To summarize,

-> ECC employs a relatively short encryption key. It is faster and requires less computing power than other first-generation encryption public key algorithms such as RSA, Diffie-Hellman. For example, a 160-bit ECC encryption key provides the same security as a 1024-bit RSA encryption key and can be up to 15 times faster, depending on the platform on which it is implemented.

-> Extremely helpful for use on low memory and low computing environments such as mobile devices, wireless devices etc.

-> Elliptic curves are supported by all modern browsers, and most certification authorities offer elliptic curve certificates.

Elliptic curve cryptography has proven to be a promising solution for the implementation of public-key cryptosystems. As widespread use of the internet and mobile devices continues to increase, transferring data the information with less computation and in a more secure manner has been the primary focus. With smaller key sizes and lower processing requirements, elliptic curve cryptography serves the purpose on mobile devices.


Posted by on February 28, 2014 in Android, iPhone

1 Comment

Tags: ,

SSL Attacks

In the last few years, we have witnessed a wide range of attacks on the SSL/TLS mechanism. In this article, we will try to cover various attacks that were prominent in the field of cryptography. Transport layer security (TLS) ensures integrity of data transmitted between two parties (server and client) and also provides strong authentication for both parties. The attacks launched in the last few years have exploited various features in the TLS mechanism. We are going to discuss these attacks one by one.

Browser Exploit Against SSL/TLS Attack (BEAST)

This attack was revealed at the Ekoparty Security Conference in 2011. BEAST is based on a type of cryptographic attack called the “chosen plain text attack”. Before I jump into explaining the details of this attack, let us take a look at some of the basic concepts to be understood.


There are two types of encryption schemes:
1. Symmetric key encryption: Encryption and decryption keys are the same.
2. Asymmetric key encryption: Encryption and decryption keys are not the same.

Symmetric-key encryption can use either stream ciphers or block ciphers. A stream cipher encrypts one bit at a time, while a block cipher encrypts plaintext in chunks. Let’s talk about block cipher. How is a message encrypted using block cipher? You don’t use the block cipher on the message directly but instead you first need to choose the “mode of operation” CBC (cipher block chaining) is one such mode used by the block ciphers.

In CBC mode, to make each message unique, an initialization vector (IV) is used in the first block. An IV is a random string that is XORed with the plaintext message prior to encryption. Each block of plaintext is XORed with the previous cipher text block before being encrypted. In other words, each cipher text block depends on all plaintext blocks processed up to that point as shown in the figure below. It’s important to note that here IV is not a secret; it only adds randomness to the output. IV is sent along with the message in clear text format. With this background information, let us know focus on how the BEAST attack is accomplished.

cbc mode

How Is the Attack Accomplished?

It was noticed that TLS 1.0, when dealing with multiple packets, allows the following packets to use an IV that is the last cipher text block of the previous packet. In other words, an attacker who can see the encrypted traffic can note the IV used for session cookie (Why? Because the cookie’s location is predictable). Simply put, an active attacker will be able to gather the IVs for each record just by sniffing the network. So if the attacker can “guess” a plaintext message, he can make a guess at the session cookie and see if the cipher text matches. [Note that, since this is a MITM attack, the attacker can mix his traffic with the victim traffic to see the results].

Practical Example

Now let us consider the message: JSESSIONID=Gxs36NepewqeMI763Hej31pkl.

This is a plaintext and will have to be XORed with the IV (which is cipher text of the previous block). The attacker has this IV value in his hands. Now if he can “predict” this plaintext value and XOR with IV, he can check whether it corresponds to the cipher text value. Understandably, it’s not easy to predict such a random value, but he can guess it a single character at a time. For example “JSESSIONID=G” can be guessed by trying different characters. Once the first character is recovered, he can shift the attack to the next character. This way he can guess one character at a time and accomplish the attack. This attack is not so straightforward and has some limitations:

  1. The attacker has to be in the same network and play a MITM attack.
  2. The attacker has to modify the traffic to see if the results match; as a result, multiple requests have to be sent in this process.
  3. The attacker can guess only one block at a time.


This is a vulnerability in block ciphers that use the CBC mode of operation. It was identified in TLS 1.0. However it was addressed in TLS 1.1 and TLS 1.2 by the use of “explicit IVs” for each block. Hence, TLS 1.1 and TLS 1.2 are not exposed to this attack. Some of the browsers have attempted to implement a solution to address the vulnerability while still remaining compatible with the SSL 3.0/TLS 1.0 protocol. Apple’s Safari, even though it has released a mitigation, has chosen to keep it disabled by default.

Google: Update to Chrome 16 or later.
Microsoft: Apply the patch MS12-006.
Mozilla: Update to Firefox 10 or later.

SSL Renegotiation Attack

A vulnerability was discovered in the SSL renegotiation procedure that allows an attacker to inject plaintext into the victim’s requests. For instance, it allows an attacker who can hijack an HTTPS connection to add their own requests to the conversation the client has with the web server. Note that the attacker cannot decrypt the client-server communication.


SSL renegotiation is helpful when the routine SSL session is already established and the client authentication has to take place. For example, say you are browsing an online shopping site which uses SSL, i.e., HTTPS. Initially, you browse through the site anonymously, add items to the cart, etc. But when you decide to purchase you will be asked to log in to the site, so now the SSL connection needs to be adjusted to allow the authentication. Whatever information is gathered prior to this authentication (e.g., items added to the cart) has to be maintained even after the authentication. So the new SSL session that has to be established uses the already existing connection. Note that renegotiation can be requested either by the client or by the server at any time. For the client to request renegotiation the client sends a “Client Hello” message in the already-established encrypted channel and the server responds with a “Server Hello” and then the negotiation follows the normal handshake process. The server can initiate the renegotiation by sending the client a “Hello Request” message. When the client receives the request, the client sends the “Client Hello” message and the handshake process takes place. This explains the basic SSL renegotiation process.

How Is the Attack Accomplished?

Using the renegotiation attack, an attacker can inject commands into an HTTPS session, downgrade a HTTPS connection to a HTTP connection, inject custom responses, perform denial of service, etc. That explains to some extent how serious the problem is. It is easier to understand how the attack is accomplished through the following example.

Practical Example

The action corresponding to each of the numbers present in the below figure are explained in the order below:

SSL renegotiation attack

  1. Assume that a client wants to connect to a online banking site. He initiates the routine TLS handshake process
  2. The client blocks the request and holds the packets.
  3. The attacker initiates a new session and completes a full TLS handshake.
  4. The attacker sends a GET request (asking to send money to his account) to the bank application.
  5. Server asks for renegotiation.
  6. The TLS handshake initiated at step 1 and blocked by the attacker will now be forwarded to the server, which a new TLS handshake over the previously established encrypted TLS session 2. So the client now is authenticated and has a valid cookie.
  7. Due to this renegotiation, the server now assumes that the previously sent request in step 4 was actually sent by the client. Hence the request which goes to the server is as follows; it will be interpreted by the server as a legitimate request and then executed.

    GET /bank/sendmoney.asp?acct=attacker&amount=100000
    Ignore the rest: GET /ebanking
    Cookie: validcookie 


One way to fix the renegotiation vulnerability for SSLv3 is to completely disable renegotiation on the server side. As a permanent fix for the vulnerability, a renegotiation indication extension was proposed for TLS that will require the client and server to include and verify information about previous handshakes in any renegotiation handshakes.

Compression Ratio Info-leak Made Easy Attack (CRIME)

This is a side-channel attack on SSL/TLS that can be used to predict sensitive information, such as the session tokens, etc. This is done based on the compressed size of the requests. This attack is known to work against SSL compression and SPDY, which use deflate/gzip data compression techniques. SPDY is not widely used, but SSL compression is one technique which is very much in use.


Before we see the details of the actual attack, let me explain a few things about “compression.” Web pages are generally compressed before the responses are sent out (this is called HTTP compression), primarily to make efficient use of available bandwidth and to provide greater transmission speeds. With compressed data, we can send the same amount of data to the destination but using fewer bits. The browser usually tells the server (through “accept-encoding” header), what compression methods it supports and the server accordingly compresses the content and sends it across. If the browser does not support any compression, then the response is not compressed. The most commonly used compression algorithms are gzip and deflate.

Accept-Encoding: gzip, deflate

When the content arrives, it is uncompressed by the browser and processed. So, basically with SSL-enabled web sites, the content is first compressed, then encrypted and sent. But you can determine the length of this compressed content even when it’s wrapped by SSL.

How Is the Attack Accomplished?

A CRIME attack is based on observing how the compressed length changes for different input values. Initially the attacker observes the size of cipher text sent by the browser and then makes multiple requests to the target website to observe the compressed response sizes. The attack primarily works by taking leverage of the “compressed size” of the text when there are repetitive terms. The attack can be best understood by following the below example, which demonstrates how an attacker can exploit it in real time.

Practical Example

Consider the below POST request made by a valid user.

POST / HTTP /1.1
User -Agent: Mozilla /5.0 (Windows NT 6.1; WOW64; rv :14.0) Gecko /20100101 Firefox /14.0.1
Cookie: secretcookie =5db98j64wa23pq1cb4cb0031ln481nx1
Accept -Language: en -US ,en;


As mentioned earlier, this content is first compressed and then encrypted and sent. But note that the size of this encrypted piece can still be found out just by sniffing the network traffic. Now the attacker’s target is to get the value of “secretcookie.” The attacker now can make the victim click on a link and, using JavaScript, he can trigger the below request.

Request triggered by the attacker:

POST /secretcookie =0 HTTP /1.1
User -Agent: Mozilla /5.0 (Windows NT 6.1; WOW64; rv :14.0) Gecko /20100101 Firefox /14.0.1
Cookie: secretcookie =5db98j64wa23pq1cb4cb0031ln481nx1
Accept -Language: en -US ,en;


In the above request, “secretcookie =0″ is the attacker-controlled input. When repetitive terms are encountered during the compression, instead of displaying it a second time the compressor says “This text is found 67 characters ago.” So this reduces the overall size of the compressed output. In the above request, since the word “secretcookie” is repeated, the compression is done accordingly by taking note of it. Now the attacker sends the below POST requests and observes the compressed sizes.

POST /secretcookie =0….
POST /secretcookie =1…
POST /secretcookie =2…
POST /secretcookie =3…
POST /secretcookie =4…
POST /secretcookie =5…

Now can you guess which POST request would be best compressed, i.e., which POST request would have the smallest compressed size? The one with “secretcookie =5″ would compress the best. This is because it has more repetitive characters. In other words, “secretcookie =5″ is repeated twice and hence the compressed size is less. Thus the attacker can confirm that 5 is the first character of the secretcookie. Going ahead with this logic, he can brute-force the other characters as well and extract the entire cookie value.


CRIME can be remediated by preventing the use of compression at the server end. It can also be prevented at the client end by disabling the compression of HTTPS requests. This is because, in TLS 1.2, the client sends the server a list of compression algorithms that are supported by it and the server picks one of them. If the client sends no compression algorithm, then the data cannot be compressed.

Timing Info-leak Made Easy Attack

In spite of being a very interesting attack, CRIME majorly suffers from two drawbacks:

  1. The attacker must be the man in the middle (to be able to read the messages) and he must also control the plaintext (which is sent as input to the application).
  2. CRIME was very soon mitigated by disabling the TLS compression.

The TIME attack overcomes both of these problems. So this attack doesn’t need an attacker to sniff the network. Instead of focusing on the HTTP request, it focuses on the HTTPS responses. To explain this attack in simple terms, all an attacker needs to do is redirect a user to a malicious website that will run some JavaScript to get the encrypted secret data.


The basic concept here is that, in order to find out if there is difference in the length of two messages, we can observer the time it takes to send these messages across the network. The larger the difference, the more time it’s going to take.

How Is the Attack Accomplished?

The basic goal of the attacker is to force the length of compressed data to overflow into an additional TCP packet. The attacker then pads the remaining data. When the maximum size is crossed, any additional packet created (due to wrong guess), introduces an additional full round trip with a significant delay. Consider a simple user input (say “secret = data”). Assume that the value is reflected in the response along with the “secret.” In other words, whatever the user inputs is reflected in the response. Let us say in the first request, the user sends “secret = anything” and receives a response with a size of 1024 bytes. If the user input is “secret=a” in the second request, the response size will be less and hence it will take less time to reach than the first request. Likewise, it is possible to predict the every character in every position of our payload by observing the response times (to be precise by observing the “shortest response times”). This attack is little difficult to comprehend and so I have mentioned a video link here which could give you a better insight for the folks who are interested.

Black hat video link:


Including CSRF, CAPTCHA tokens in the request could avoid the multiple requests that an attacker makes using the JavaScript. Adding random timing delays to the decryption for any timing attack can be reasonable to disrupt this attack, but it may not be completely helpful. The application should take care of the reflection of user input in the response.


Posted by on December 31, 2013 in web application hacking

1 Comment

Tags: , , ,

BREACH Attack Explained

Back in 2012, when Juliano Rizzo and Thai Duong announced the CRIME attack, TLS / SSL Compression attack against HTTPS, the ability to recover selected parts of the traffic through side channel attacks has been proved. This attack was mitigated by disabling the TLS / SSL level compression by most of the browsers. This year at Black Hat, a new attack called BREACH (Browser Reconnaissance and Exfiltration via Adaptive Compression of Hypertext) was announced which commanded the attention of entire industry. This presentation which came up with the title “SSL Gone in 30 seconds” is something that is not properly understood and hence there seems to be some confusion about how to mitigate this. So I felt this article would give some detailed insight into how notorious the attack is, how it works, how practical it is and what needs to be done to mitigate it. So let’s proceed and have a look at the same.

BREACH Attack:

Unlike the previously known attacks such as BEAST, LUCKY etc, BREACH is not an attack against TLS. BREACH is basically an attack against the HTTP. If you are familiar with the famous Oracle Padding attack, BREACH is somewhat easy to understand. A BREACH attack can extract login tokens, email addresses or other sensitive information from TLS encrypted web traffic in as little as 30 seconds (depending on the number of bytes to be extracted). The attacker just needs to trick the victim to visit a malicious link for executing the attack. Before going into the details, let me explain a little bit more about the basic things to know. Web pages are generally compressed before the responses are sent out, which is called HTTP Compression, primarily to make better use of available bandwidth and to provide greater transmission speeds. Browser usually tells the server (through ‘Accept-Encoding’ header), what compression methods it supports and server accordingly compresses the content and sends it across. If the browser does not support any compression then the response is not compressed. The most commonly used compression algorithms are gzip and deflate.

Accept-Encoding: gzip, deflate

When the content arrives, it is uncompressed by the browser and processed. So basically with SSL enabled web sites, the content is first compressed, then encrypted and sent. But you can determine the length of this compressed content even when it’s wrapped by SSL.

How it works?

The attack primarily works by taking leverage of the ‘compressed size’ of the text when there are repetitive terms. So here is a small example which explains how deflate takes advantage of repetitive terms to reduce the compressed size of the response.

1. Consider the below search page which is present after logging into this site:

Breach example - search page

2. Observe that the text highlighted in red box is the username. Now enter any text (say ‘random’) and click search.


Breach example - search page2

3. So you can control the response through the input parameter in the URL. Now imagine what if the search term is ‘Pentesting’ (which is the username in this case).


Breach example - search page3

Now when deflate algorithm is compressing the above response, it finds that the term ‘Pentesting’ is repeated more than once in the response. So instead of displaying it second time the compressor says ‘this text is found 101 characters ago’. So this reduces the size of the compressed output. In other words, by controlling the input search parameter you can guess the username. How? The compressed size would be least when the search parameter matches the username. This concept is the base for the BREACH attack.

Practical Attack:

Now let us see how an attacker would practically exploit this issue and steal any sensitive information. Consider the below site and assume a legitimate user has just signed in.

Breach Sample search page

[Before signing in to the application]

Breach Sample search after login

[Search page which is accessible after logging in]

As shown in the above figure, also assume that there is some sensitive data which is present in the Search page for example let card number be one such sensitive data in the application. When the user searches for something (say ‘test’) below is the message displayed.

Breach Sample search page2

Now an attacker, using all the social engineering techniques, could lure this currently signed in user to click on a link. The link would be simple html page that has a JavaScript in it which will request searches continuously for search terms ‘100-1000’. For example the JavaScript would request the below URL’s.





Now the attacker can also get the corresponding compressed sizes of the responses for each of these requests. Can you guess why the compresses sizes for each of these responses would differ and can you guess which request would have the smallest compressed size? Below would be the request with the smallest compressed sizes.





Below is the explanation as to why the above requests have least compressed sizes. Now take the first request. Below would be the response from the server.

 URL: http://localhost/demo/Search?p=4545

Breach Sample search page3

As shown above, when the deflate algorithm encounters this, it makes an easy representation of the repetitions and thus results in a least compressed size. So by analyzing the compressed size for each of the requests from 100-10000, an attacker can simply deduce what the card number is in this case. This the beauty of this attack lies in the fact that we did not decrypt any traffic but just by analyzing the size of the responses we were able to predict the text.

To summarize in simple steps, for an application to be vulnerable to this breach attack, below are the conditions that it must fulfill:

1. The server should be using HTTP level compression.
2. A parameter which reflects the input text. (This will be controlled by the attacker).
3. The page should contain some sensitive text which would be of interest to the attacker.


Turning off the HTTP Compression would save the day but that cannot be a possible solution since all the servers rely on it to effectively manage the bandwidth. Here are some of the other solutions that can be tried:

  1. Protect the vulnerable pages with a CSRF token
  2. Adding random bytes to the response so as to hide the actual compressed length.
  3. Separating the sensitive data from pages where input text is displayed.



Posted by on November 30, 2013 in web application hacking

Leave a comment

Tags: , ,

Android Master Key Vulnerability POC

A few weeks back, a vulnerability dubbed as ‘Android Master key vulnerability’ was revealed. This vulnerability allows attackers to inject malicious code into legitimate Android applications without invalidating the digital signature. It’s very easy for hackers and attackers to take leverage of this vulnerability and exploit it. The news is already out that there are apps currently in the market which are taking advantage of this vulnerability.  So let’s find out  what the issue is, how hackers can exploit it and what needs to be done to fix it.

How Android apps work?

Android applications are .APK files (Android Packages) which are nothing but a collection of ZIP archives. For easy understanding let us try to open an APK file for an application and find out the same. Consider the application MyFirstApp.apk application which is signed by own my certificate. Before we go ahead, let us spend some time on android’s signing process.

It is mandatory that all installed applications in android be digitally signed with a certificate whose private key is held by the application’s developer. The Android system uses this certificate as a means of identifying the author of an application and establishing trust relationships between applications. The Android system will not install or run an application that is not signed. Hence after building an application and signing it with a certificate, you have an apk file at the end.


Assume that MyFirstApp.apk is any random application and looks like this when installed on the emulator.

Sample Android app

APK files are nothing but collection of zip files. So if you rename an .apk extension with .zip you will be able to see the contents of the file.

apk file contents

As shown in the above figure, the APK file consists of subdirectory called META-INF, which contains signed checksums for all the other files in the package. Now if you modify any of the files in this package, Android will block the package to prevent the users from harmful activities. Android does this by verifying the checksum. Now in order to verify the checksum of each of these files, android has to extract each of these files from the APK archive. This is accomplished using the Java unzipping library which will parse the ZIP-format APK file, extracts each file object and matches it up with the corresponding checksum mentioned in the manifest file in META-INF:

Android app meta-inf folder

Now try to modify any of these files, for example, try to modify  the launch image file present inside\res\drawable-hdpi , rebuild it and try to install it on the device using the adb and you will find that android rightly notices that and shows the below message.

Android app signature mismatch

How the attack is accomplished?

The attack successfully bypasses this verification process and installs the application with any changes the hacker embeds in the code. The attack is based on the concept of placing two different files in the APK archive with the same name. Regular ZIP software generally do not allow you to have two files with the same name in one archive. But the ZIP format itself doesn’t prevent duplicated filenames, and you can take advantage of this to create an archive with repeated file names as shown below. The ic_launcher.png file is something that I have added to the existing file and created a new apk file named

zip with duplicated filenames

Now rename this file to HackedFile.apk and try to install it and observe that android accepts it this time. It runs successfully without any complaints. Observe that I was able to replace the launch image successfully without using any certificate and android happily accepts the same.

Android app with modified image

How is this even possible?

This is possible because Android verifies the first version of any file in archive but the installer verifies and extracts the last version of the file. Thus the legitimate file is checked by the cryptographic verifier and the one added by the hacker is installed by the installer. In simple words, what gets installed is a fake but what gets verified for signature is legitimate part.

What are the implications?

The implications are huge. Most important thing to note is almost all version of Android are vulnerable to this attack. The impact of this vulnerability and its exploitation is only limited by imagination of an hacker. For instance he can spy on your communication or he can go a step further and send premium rate sms without the users knowledge, make background calls,  take pictures and forward to mails etc.

Some of the built in apps which come along with the phone have higher privileges than the other applications which are installed from the play store. So an attacker can take leverage of this and create apps which would have system level privileges. Bluebox team has successfully demonstrated this and changed the name of the kernel etc.


Google has already released patches for this but as everyone knows it will certainly take some time for the handset makers to update all of their models. Google is now verifying all the applications in the play store to check for the master key vulnerability. But the other third party stores and the side loading of apps aren’t going to help the cause.



Posted by on October 28, 2013 in Android

1 Comment

Tags: ,