Advertisement
nux95

Python Threaded Bruteforce

Jul 2nd, 2011
758
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.79 KB | None | 0 0
  1. """
  2. Bruteforcing algorithm by Niklas Rosenstein, All rights reserved.
  3. Check out the main() function to see how it works.
  4. """
  5.  
  6. # # # # # # # # # # # # # # # # # # # # # #
  7. # imports
  8. # # # # # # # # # # # # # # # # # # # # # #
  9.  
  10. import  string
  11. from    time        import time
  12. from    threading   import Thread, Lock
  13. from    traceback   import print_exc
  14.  
  15.  
  16. # # # # # # # # # # # # # # # # # # # # # #
  17. # class definitions
  18. # # # # # # # # # # # # # # # # # # # # # #
  19.  
  20. class SharedGenerator(object):
  21.     """
  22.    Enables  sharing an iterable between threads.
  23.    Initialize with generator or any other
  24.    iterable object.
  25.    If /iterable/ is not iterable, an error is raised.
  26.    """
  27.     def __init__(self, iterable):
  28.         self.it     = iter(iterable)
  29.         self.lock   = Lock()
  30.         self.stop   = False
  31.  
  32.     def __iter__(self):
  33.         return self
  34.  
  35.     def next(self):
  36.         if self.stop is True:
  37.             raise StopIteration
  38.  
  39.         self.lock.acquire()     # enable lock, no other thread can use this object
  40.         try:
  41.             # StopIteration will be raised automatically
  42.             # if the generator ends.
  43.             # (we don't have an except - clause)
  44.  
  45.             return self.it.next()
  46.         finally:
  47.             self.lock.release() # release lock, free for the next thread
  48.    
  49.  
  50. class Bruteforce(object):
  51.     """
  52.    A class to generate bruteforce attacks.
  53.    """
  54.  
  55.     # special methods
  56.     # # # # # # # # # # #
  57.  
  58.     def __init__(self, charset, length = 0):
  59.         if not charset:
  60.             raise ValueError, "charset must be a not-empty string"
  61.  
  62.         charset                = self.ClearedCharset(charset)
  63.  
  64.         self.charset     = charset
  65.         self.char            = min(charset)
  66.         self._alive        = True
  67.         self.subchar     = None
  68.  
  69.         if length > 0:
  70.             for i in xrange(length-1):
  71.                 self.Extend(charset)
  72.  
  73.     def __len__(self):
  74.         cnt            = 1
  75.         c                = self.subchar
  76.         while c:
  77.             cnt += 1
  78.             c        = c.subchar
  79.         return cnt
  80.  
  81.     def __iter__(self):
  82.         def iterator():
  83.             while True:
  84.                 yield self.Next()
  85.                 if not self.alive:
  86.                     yield self.Next(); break
  87.         return iterator()
  88.  
  89.     # properties
  90.     # # # # # # # # # # # # # # # # # # # #
  91.  
  92.     @ property
  93.     def alive(self):
  94.         if self.subchar:
  95.             return self._alive or self.subchar.alive
  96.         else:
  97.             return self._alive
  98.  
  99.     @ property
  100.     def length(self):
  101.         """
  102.         Returns the number of possibilites, assuming every character
  103.         uses the same charset.
  104.         """
  105.         return len(self.charset) ** (len(self))
  106.  
  107.     # interaction
  108.     # # # # # # # # # # # # # # # # # # # #
  109.  
  110.     def ClearedCharset(self, set):
  111.         nSet        = ""
  112.         for c in set:
  113.             if c not in nSet: nSet += c
  114.         return nSet
  115.  
  116.     def SetSubchar(self, subchar):
  117.         if isinstance(subchar, basestring):
  118.             self.subchar = self.__class__(subchar)
  119.         else:
  120.             self.subchar = subchar
  121.  
  122.         return self.subchar
  123.  
  124.     def Extend(self, charset = None):
  125.         if charset is None:
  126.             charset = self.charset
  127.         char            = self
  128.         while True:
  129.             nchar     = char.subchar
  130.             if nchar is None:
  131.                 break
  132.             char        = nchar
  133.         char.SetSubchar(charset)
  134.  
  135.     def Reset(self, subchars = True):
  136.         self.char         = min(self.charset)
  137.         if self.subchar and subchars:
  138.             self.subchar.Reset()
  139.         self._alive        = True
  140.  
  141.     def IncreaseChar(self):
  142.         cIndex     = ord(self.char)
  143.         cIndex    += 1
  144.         cIndex    %= 256
  145.  
  146.         while chr(cIndex) not in self.charset:
  147.             cIndex    += 1
  148.             cIndex    %= 256
  149.  
  150.         self.char    = chr(cIndex)
  151.  
  152.         if self.char == max(self.charset):
  153.             self._alive = False
  154.  
  155.     def Next(self):
  156.         chr    = self.Get()
  157.         if self.subchar and self.subchar.alive:
  158.             self.subchar.Next()
  159.         else:
  160.             self.IncreaseChar()
  161.             if self.subchar \
  162.             and not self.subchar.alive:
  163.                 self.subchar.Reset(True)
  164.         return chr
  165.  
  166.     def Get(self):
  167.         if self.subchar:
  168.             return self.char + \
  169.             self.subchar.Get()
  170.         else:
  171.             return self.char
  172.  
  173.     def ForceWithThreads(self, num, function, args = [], kwargs = {}, doStart = True, doJoin = True, timeout = None):
  174.         gen     = SharedGenerator(self)
  175.  
  176.         # create a wrapper function for the Thread
  177.         def wrapped():
  178.             # the generator stops when /function/ returns True.
  179.             try:
  180.                 gen.stop    = function(gen, *args, **kwargs)
  181.             except:
  182.                 print_exc()
  183.                 gen.stop()
  184.  
  185.         threads = []
  186.         append  = threads.append
  187.         for n in xrange(num):
  188.             t   = Thread(target = wrapped)
  189.             append(t)
  190.             if doStart:
  191.                 t.start()
  192.  
  193.         if doStart & doJoin:
  194.             for t in threads:
  195.                 t.join(timeout)
  196.  
  197.         return threads
  198.  
  199.  
  200. # # # # # # # # # # # # # # # # # # # # # #
  201. # main
  202. # # # # # # # # # # # # # # # # # # # # # #
  203.  
  204. from    sys         import argv, exit
  205. from    random      import choice
  206.  
  207.  
  208. try:
  209.     from    multiprocessing     import cpu_count
  210. except ImportError:
  211.     cpu_count   = lambda: 1
  212.  
  213.  
  214. def main():
  215.     # check sys.argv
  216.     if len(argv) < 3:
  217.         print "Use:"
  218.         print "python bruteforce.py //charset// //length//"
  219.         print "For instance: python bruteforce.py '0123456789abc' 5"
  220.         exit(0)
  221.  
  222.     tStart  = time()
  223.  
  224.     # obtain data from commandline call
  225.     charset = argv[1]
  226.     try:
  227.         length  = int(argv[2])
  228.     except ValueError:
  229.         print "invalid length:", length
  230.         exit(0)
  231.  
  232.     try:
  233.         numThreads  = int(argv[3])
  234.     except IndexError:
  235.         numThreads  = cpu_count()
  236.     except ValueError:
  237.         numThreads  = cpu_count()
  238.  
  239.     # generate random password
  240.     password= ""
  241.     for i in xrange(length):
  242.         password   += choice(charset)
  243.  
  244.     # create Bruteforce object
  245.     bc      = Bruteforce(charset, length)
  246.  
  247.  
  248.     # create function which comapres the bruted strings
  249.     # with the password
  250.     def worker(chars):
  251.         for c in chars:
  252.             if c == password:
  253.                 print "Password cracked:", c
  254.                 print "Time to evaluate:", time() - tStart
  255.                 print "- " * 30
  256.                 return True # return True to stop all threads
  257.  
  258.     bc.ForceWithThreads(numThreads, worker)
  259.  
  260.     return True
  261.  
  262.  
  263. if __name__ == "__main__":
  264.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement