Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Bruteforcing algorithm by Niklas Rosenstein, All rights reserved.
- Check out the main() function to see how it works.
- """
- # # # # # # # # # # # # # # # # # # # # # #
- # imports
- # # # # # # # # # # # # # # # # # # # # # #
- import string
- from time import time
- from threading import Thread, Lock
- from traceback import print_exc
- # # # # # # # # # # # # # # # # # # # # # #
- # class definitions
- # # # # # # # # # # # # # # # # # # # # # #
- class SharedGenerator(object):
- """
- Enables sharing an iterable between threads.
- Initialize with generator or any other
- iterable object.
- If /iterable/ is not iterable, an error is raised.
- """
- def __init__(self, iterable):
- self.it = iter(iterable)
- self.lock = Lock()
- self.stop = False
- def __iter__(self):
- return self
- def next(self):
- if self.stop is True:
- raise StopIteration
- self.lock.acquire() # enable lock, no other thread can use this object
- try:
- # StopIteration will be raised automatically
- # if the generator ends.
- # (we don't have an except - clause)
- return self.it.next()
- finally:
- self.lock.release() # release lock, free for the next thread
- class Bruteforce(object):
- """
- A class to generate bruteforce attacks.
- """
- # special methods
- # # # # # # # # # # #
- def __init__(self, charset, length = 0):
- if not charset:
- raise ValueError, "charset must be a not-empty string"
- charset = self.ClearedCharset(charset)
- self.charset = charset
- self.char = min(charset)
- self._alive = True
- self.subchar = None
- if length > 0:
- for i in xrange(length-1):
- self.Extend(charset)
- def __len__(self):
- cnt = 1
- c = self.subchar
- while c:
- cnt += 1
- c = c.subchar
- return cnt
- def __iter__(self):
- def iterator():
- while True:
- yield self.Next()
- if not self.alive:
- yield self.Next(); break
- return iterator()
- # properties
- # # # # # # # # # # # # # # # # # # # #
- @ property
- def alive(self):
- if self.subchar:
- return self._alive or self.subchar.alive
- else:
- return self._alive
- @ property
- def length(self):
- """
- Returns the number of possibilites, assuming every character
- uses the same charset.
- """
- return len(self.charset) ** (len(self))
- # interaction
- # # # # # # # # # # # # # # # # # # # #
- def ClearedCharset(self, set):
- nSet = ""
- for c in set:
- if c not in nSet: nSet += c
- return nSet
- def SetSubchar(self, subchar):
- if isinstance(subchar, basestring):
- self.subchar = self.__class__(subchar)
- else:
- self.subchar = subchar
- return self.subchar
- def Extend(self, charset = None):
- if charset is None:
- charset = self.charset
- char = self
- while True:
- nchar = char.subchar
- if nchar is None:
- break
- char = nchar
- char.SetSubchar(charset)
- def Reset(self, subchars = True):
- self.char = min(self.charset)
- if self.subchar and subchars:
- self.subchar.Reset()
- self._alive = True
- def IncreaseChar(self):
- cIndex = ord(self.char)
- cIndex += 1
- cIndex %= 256
- while chr(cIndex) not in self.charset:
- cIndex += 1
- cIndex %= 256
- self.char = chr(cIndex)
- if self.char == max(self.charset):
- self._alive = False
- def Next(self):
- chr = self.Get()
- if self.subchar and self.subchar.alive:
- self.subchar.Next()
- else:
- self.IncreaseChar()
- if self.subchar \
- and not self.subchar.alive:
- self.subchar.Reset(True)
- return chr
- def Get(self):
- if self.subchar:
- return self.char + \
- self.subchar.Get()
- else:
- return self.char
- def ForceWithThreads(self, num, function, args = [], kwargs = {}, doStart = True, doJoin = True, timeout = None):
- gen = SharedGenerator(self)
- # create a wrapper function for the Thread
- def wrapped():
- # the generator stops when /function/ returns True.
- try:
- gen.stop = function(gen, *args, **kwargs)
- except:
- print_exc()
- gen.stop()
- threads = []
- append = threads.append
- for n in xrange(num):
- t = Thread(target = wrapped)
- append(t)
- if doStart:
- t.start()
- if doStart & doJoin:
- for t in threads:
- t.join(timeout)
- return threads
- # # # # # # # # # # # # # # # # # # # # # #
- # main
- # # # # # # # # # # # # # # # # # # # # # #
- from sys import argv, exit
- from random import choice
- try:
- from multiprocessing import cpu_count
- except ImportError:
- cpu_count = lambda: 1
- def main():
- # check sys.argv
- if len(argv) < 3:
- print "Use:"
- print "python bruteforce.py //charset// //length//"
- print "For instance: python bruteforce.py '0123456789abc' 5"
- exit(0)
- tStart = time()
- # obtain data from commandline call
- charset = argv[1]
- try:
- length = int(argv[2])
- except ValueError:
- print "invalid length:", length
- exit(0)
- try:
- numThreads = int(argv[3])
- except IndexError:
- numThreads = cpu_count()
- except ValueError:
- numThreads = cpu_count()
- # generate random password
- password= ""
- for i in xrange(length):
- password += choice(charset)
- # create Bruteforce object
- bc = Bruteforce(charset, length)
- # create function which comapres the bruted strings
- # with the password
- def worker(chars):
- for c in chars:
- if c == password:
- print "Password cracked:", c
- print "Time to evaluate:", time() - tStart
- print "- " * 30
- return True # return True to stop all threads
- bc.ForceWithThreads(numThreads, worker)
- return True
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement