示例#1
0
 def __init__(self, *args, **kwargs):
     super(NNToolShellSettings, self).__init__(*args, **kwargs)
     for k, v in DEFAULT_OPT_DESCRIPTIONS.items():
         self.add_settable(Settable(k, v['type'], v['descr'],
                                    choices=v['choices'] if 'choices' in v.keys() else None))
     for k, v in DEFAULT_GEN_OPTS_DESCRIPTIONS.items():
         self.add_settable(Settable(k, v['type'], v['descr'],
                                    choices=v['choices'] if 'choices' in v.keys() else None))
     self.settings = {
         'load_quantization': False,
         'fusions': False,
         'adjust_order': False,
         'weight_equalization': False,
         'equalization_threshold': 0.1,
         'adjust_image': False,
         'image_width': -1,
         'image_height': -1,
         'image_mode': "",
         'image_transpose': False,
         'input_norm_func': "",
         'input_divisor': 1,
         'input_offset': 0,
         'input_shift': 0,
         'log_level': 'INFO',
         'graph_file': "",
         'tensor_file': "",
         'template_file': ""
     }
     self.settings.update(DEFAULT_GEN_OPTS)
示例#2
0
 def __init__(self):
     super().__init__()
     # Make maxrepeats settable at runtime
     self.resultStep4Outputs = set()
     self.resultStep4Inputs = set()
     self.maxrepeats = 3
     self.add_settable(Settable('maxrepeats', int, 'max repetitions for speak command'))
示例#3
0
    def __init__(self):
        super().__init__()
        path = PosixPath('~/.pynndb').expanduser()
        Path.mkdir(path, exist_ok=True)
        if not path.is_dir():
            self.pfeedback('error: unable to open configuration folder')
            exit(1)
        self._data = path / 'local_data'
        self._base = path / 'registered'
        self._line = path / '.readline_history'
        Path.mkdir(self._data, exist_ok=True)
        Path.mkdir(self._base, exist_ok=True)
        if not self._data.is_dir() or not self._base.is_dir():
            self.pfeedback('error: unable to open configuration folder')
            exit(1)

        # self.settable.update({'limit': 'The maximum number of records to return'})
        self.add_settable(Settable('limit', int, 'The maximum number of records to return'))
        self.prompt = self._default_prompt

        self.do_shell = None
        self.do_edit = None
        self.do_load = None
        self.do_pyscript = None
        self.do_py = None
示例#4
0
    def __init__(self, dev_driver, *args, **kwargs):
        """Instantiate cmd based cli class.

        Args:
            dev_driver (obj): The device driver used to communicate with the
                device.
            persistent_history_file (str): Path to history file,
                defaults to ~/.mm_history.
        """
        self.logger = self.logger = logging.getLogger(self.__class__.__name__)
        self.dev_driver = dev_driver
        phf = 'persistent_history_file'
        kwargs[phf] = kwargs.pop(
            phf, os.path.join(os.path.expanduser("~"), ".mm_history"))
        super().__init__(allow_cli_args=False, *args, **kwargs)
        self.loglevel = logging.getLevelName(logging.root.level)
        self.add_settable(
            Settable('loglevel',
                     str,
                     'Logging Level',
                     choices=[
                         'NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR',
                         'CRITICAL'
                     ],
                     onchange_cb=self._onchange_loglevel))
示例#5
0
    def set(self, app: Cmd):
        """ Adds settings to cmd2 application"""

        #make sure there is not a setting collision
        if hasattr(app, 'special_setting'):
            raise SettingCollisionError

        app.special_setting = 33
        app.add_settable(Settable('special_setting', int, 
            'Special Setting'))
示例#6
0
        def __init__(self):
            super(WithSettablesA, self).__init__()

            self._arbitrary = Arbitrary()
            self._settable_prefix = 'addon'
            self.my_int = 11

            self.add_settable(
                Settable(
                    'arbitrary_value',
                    int,
                    'Some settable value',
                    settable_object=self._arbitrary,
                    settable_attrib_name='some_value',
                ))
示例#7
0
        def __init__(self):
            super(WithSettablesNoPrefix, self).__init__()

            self._arbitrary = Arbitrary()
            self._settable_prefix = ''
            self.my_int = 11

            self.add_settable(
                Settable(
                    'another_value',
                    float,
                    'Some settable value',
                    settable_object=self._arbitrary,
                    settable_attrib_name='some_value',
                ))
示例#8
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.TABLE_PRETTY_FORMAT = "psql"
     # hide unwanted settings
     settings_to_hide = ["debug"]
     for setting_name in settings_to_hide:
         self.remove_settable(setting_name)
     f = Figlet(font="slant")
     intro = []
     intro.append(style(f.renderText("Faraday Cli"), fg="red"))
     if active_config.faraday_url and active_config.token:
         intro.append(
             style(f"Server: {active_config.faraday_url}", fg="green"))
         self.api_client = FaradayApi(
             active_config.faraday_url,
             ignore_ssl=active_config.ignore_ssl,
             token=active_config.token,
         )
     else:
         self.api_client = FaradayApi()
         intro.append(
             style(f"Missing faraday server, run 'auth'", fg="yellow"))
     self.intro = "\n".join(intro)
     self.data_queue = queue.Queue()
     self.custom_plugins_path = None
     self.update_prompt()
     self.add_settable(
         Settable(
             "custom_plugins_path",
             str,
             "Path of custom plugins",
             onchange_cb=self._onchange_custom_plugins_path,
         ))
     self.plugins_manager = PluginsManager(
         active_config.custom_plugins_folder)
     self.report_analyzer = ReportAnalyzer(self.plugins_manager)
     self.command_analyzer = CommandAnalyzer(self.plugins_manager)
示例#9
0
    def __init__(self):
        super().__init__()

        # remove built-in commands
        try:
            del Cmd.do_alias
            del Cmd.do_edit
            del Cmd.do_macro
            del Cmd.do_run_pyscript
            del Cmd.do_run_script
            del Cmd.do_shortcuts
            del Cmd.do_py
            del Cmd.do_pyscript  # removed in cmd2 v0.9.15
            del Cmd.do_load  # removed in cmd2 v0.9.15
        except AttributeError:
            pass

        # remove built-in settings
        for key in [
                'allow_style', 'editor', 'debug', 'echo', 'feedback_to_output',
                'quiet', 'timing', 'max_completion_items'
        ]:
            try:
                self.remove_settable(key)
            except:
                pass

        # set config variables
        self.redshell_directory = os.getcwd()
        self.proxychains_config = "{}/proxychains_redshell.conf".format(
            self.redshell_directory)
        self.cs_directory = '/opt/cobaltstrike'
        self.cs_host = ''
        self.cs_port = ''
        self.cs_user = ''
        self.cs_pass = ''
        self.socks_port = ''
        self.beacon_pid = ''
        self.bid = ''
        self.socks_port_connected = False
        self.cs_process = None
        self.password = ''

        # initialze user settable options
        self.add_settable(
            Settable('redshell_directory',
                     str,
                     'redshell install directory',
                     completer_method=Cmd.path_complete,
                     onchange_cb=self._onchange_redshell_directory))
        self.add_settable(
            Settable('proxychains_config',
                     str,
                     'proxychains config file',
                     completer_method=Cmd.path_complete))
        self.add_settable(
            Settable('cs_directory',
                     str,
                     'Cobalt Strike install directory',
                     completer_method=Cmd.path_complete))
        self.add_settable(
            Settable('cs_host', str, 'Cobalt Strike team server host'))
        self.add_settable(
            Settable('cs_port', str, 'Cobalt Strike team server port'))
        self.add_settable(
            Settable('cs_user',
                     str,
                     'Cobalt Strike user',
                     onchange_cb=self._onchange_cs_user))
        self.add_settable(
            Settable(
                'password', str,
                'Password for beacon_exec commands. Invoke with $password.'))
示例#10
0
def test_commandset_settables():
    # Define an arbitrary class with some attribute
    class Arbitrary:
        def __init__(self):
            self.some_value = 5

    # Declare a CommandSet with a settable of some arbitrary property
    class WithSettablesA(CommandSetBase):
        def __init__(self):
            super(WithSettablesA, self).__init__()

            self._arbitrary = Arbitrary()
            self._settable_prefix = 'addon'
            self.my_int = 11

            self.add_settable(
                Settable(
                    'arbitrary_value',
                    int,
                    'Some settable value',
                    settable_object=self._arbitrary,
                    settable_attrib_name='some_value',
                ))

    # Declare a CommandSet with an empty settable prefix
    class WithSettablesNoPrefix(CommandSetBase):
        def __init__(self):
            super(WithSettablesNoPrefix, self).__init__()

            self._arbitrary = Arbitrary()
            self._settable_prefix = ''
            self.my_int = 11

            self.add_settable(
                Settable(
                    'another_value',
                    float,
                    'Some settable value',
                    settable_object=self._arbitrary,
                    settable_attrib_name='some_value',
                ))

    # Declare a commandset with duplicate settable name
    class WithSettablesB(CommandSetBase):
        def __init__(self):
            super(WithSettablesB, self).__init__()

            self._arbitrary = Arbitrary()
            self._settable_prefix = 'some'
            self.my_int = 11

            self.add_settable(
                Settable(
                    'arbitrary_value',
                    int,
                    'Some settable value',
                    settable_object=self._arbitrary,
                    settable_attrib_name='some_value',
                ))

    # create the command set and cmd2
    cmdset = WithSettablesA()
    arbitrary2 = Arbitrary()
    app = cmd2.Cmd(command_sets=[cmdset], auto_load_commands=False)
    setattr(app, 'str_value', '')
    app.add_settable(
        Settable('always_prefix_settables', bool, 'Prefix settables', app))
    app._settables['str_value'] = Settable('str_value', str, 'String value',
                                           app)

    assert 'arbitrary_value' in app.settables.keys()
    assert 'always_prefix_settables' in app.settables.keys()
    assert 'str_value' in app.settables.keys()

    # verify the settable shows up
    out, err = run_cmd(app, 'set')
    assert 'arbitrary_value: 5' in out
    out, err = run_cmd(app, 'set arbitrary_value')
    assert out == ['arbitrary_value: 5']

    # change the value and verify the value changed
    out, err = run_cmd(app, 'set arbitrary_value 10')
    expected = """
arbitrary_value - was: 5
now: 10
"""
    assert out == normalize(expected)
    out, err = run_cmd(app, 'set arbitrary_value')
    assert out == ['arbitrary_value: 10']

    # can't add to cmd2 now because commandset already has this settable
    with pytest.raises(KeyError):
        app.add_settable(
            Settable('arbitrary_value', int, 'This should fail', app))

    cmdset.add_settable(
        Settable('arbitrary_value',
                 int,
                 'Replaced settable',
                 settable_object=arbitrary2,
                 settable_attrib_name='some_value'))

    # Can't add a settable to the commandset that already exists in cmd2
    with pytest.raises(KeyError):
        cmdset.add_settable(
            Settable('always_prefix_settables', int, 'This should also fail',
                     cmdset))

    # Can't remove a settable from the CommandSet if it is elsewhere and not in the CommandSet
    with pytest.raises(KeyError):
        cmdset.remove_settable('always_prefix_settables')

    # verify registering a commandset with duplicate settable names fails
    cmdset_dupname = WithSettablesB()
    with pytest.raises(CommandSetRegistrationError):
        app.register_command_set(cmdset_dupname)

    # unregister the CommandSet and verify the settable is now gone
    app.unregister_command_set(cmdset)
    out, err = run_cmd(app, 'set')
    assert 'arbitrary_value' not in out
    out, err = run_cmd(app, 'set arbitrary_value')
    expected = """
Parameter 'arbitrary_value' not supported (type 'set' for list of parameters).
"""
    assert err == normalize(expected)

    # Add a commandset with no prefix
    cmdset_nopfx = WithSettablesNoPrefix()
    app.register_command_set(cmdset_nopfx)

    with pytest.raises(ValueError):
        app.always_prefix_settables = True

    app.unregister_command_set(cmdset_nopfx)

    # turn on prefixes and add the commandset back
    app.always_prefix_settables = True

    with pytest.raises(CommandSetRegistrationError):
        app.register_command_set(cmdset_nopfx)

    app.register_command_set(cmdset)

    # Verify the settable is back with the defined prefix.
    assert 'addon.arbitrary_value' in app.settables.keys()

    # rename the prefix and verify that the prefix changes everywhere
    cmdset._settable_prefix = 'some'
    assert 'addon.arbitrary_value' not in app.settables.keys()
    assert 'some.arbitrary_value' in app.settables.keys()

    out, err = run_cmd(app, 'set')
    assert 'some.arbitrary_value: 5' in out
    out, err = run_cmd(app, 'set some.arbitrary_value')
    assert out == ['some.arbitrary_value: 5']

    # verify registering a commandset with duplicate prefix and settable names fails
    with pytest.raises(CommandSetRegistrationError):
        app.register_command_set(cmdset_dupname)

    cmdset_dupname.remove_settable('arbitrary_value')

    app.register_command_set(cmdset_dupname)

    with pytest.raises(KeyError):
        cmdset_dupname.add_settable(
            Settable(
                'arbitrary_value',
                int,
                'Some settable value',
                settable_object=cmdset_dupname._arbitrary,
                settable_attrib_name='some_value',
            ))
示例#11
0
 def __init__(self):
     super().__init__()
     # Make maxrepeats settable at runtime
     self.maxrepeats = 3
     self.add_settable(Settable('maxrepeats', int, 'max repetitions for speak command'))
     self.prompt = 'iotA>> '
示例#12
0
    def __init__(self):
        super().__init__()

        # remove built-in commands
        try:
            del Cmd.do_alias
            del Cmd.do_edit
            del Cmd.do_macro
            del Cmd.do_run_pyscript
            del Cmd.do_run_script
            del Cmd.do_shortcuts
            del Cmd.do_py
        except AttributeError:
            pass

        # remove built-in settings
        for key in [
                'allow_style', 'always_show_hint', 'editor', 'echo',
                'feedback_to_output', 'quiet', 'timing', 'max_completion_items'
        ]:
            try:
                self.remove_settable(key)
            except:
                pass

        # check/create redshell user dir
        home_dir = os.path.expanduser("~")
        self.redshell_user_directory = f"{home_dir}/.redshell/"

        if not os.path.exists(self.redshell_user_directory):
            os.makedirs(self.redshell_user_directory)

        # set cobalt strike directory, if exists
        if os.path.exists('/opt/cobaltstrike'):
            self.cs_directory = '/opt/cobaltstrike'
        else:
            self.cs_directory = ''

        # set config variables
        self.redshell_directory = os.getcwd()
        self.proxychains_config = f"{self.redshell_directory}/proxychains_redshell.conf"
        self.cs_host = ''
        self.cs_port = ''
        self.cs_user = ''
        self.cs_pass = ''
        self.cs_process = None
        self.cs_beacon_pid = ''
        self.cs_beacon_id = ''
        self.cs_beacon_user = ''
        self.cs_beacon_computer = ''
        self.cs_beacon_ip = ''
        self.context_ip = ''
        self.context_dns_name = ''
        self.context_netbios_name = ''
        self.context_user_name = ''
        self.context_pid = ''
        self.socks_host = ''
        self.socks_port = ''
        self.socks_port_connected = False
        self.password = ''

        # initialze user settable options
        self.add_settable(
            Settable('redshell_directory',
                     str,
                     'redshell install directory',
                     self,
                     completer=Cmd.path_complete,
                     onchange_cb=self._onchange_redshell_directory))
        self.add_settable(
            Settable('proxychains_config',
                     str,
                     'proxychains config file',
                     self,
                     completer=Cmd.path_complete))
        self.add_settable(
            Settable('cs_directory',
                     str,
                     'Cobalt Strike install directory',
                     self,
                     completer=Cmd.path_complete))
        self.add_settable(
            Settable('cs_host', str, 'Cobalt Strike team server host', self))
        self.add_settable(
            Settable('cs_port', str, 'Cobalt Strike team server port', self))
        self.add_settable(
            Settable('cs_user',
                     str,
                     'Cobalt Strike user',
                     self,
                     onchange_cb=self._onchange_cs_user))
        self.add_settable(
            Settable(
                'password', str,
                'Password for beacon_exec commands. Invoke with $password.',
                self))

        # start logger
        now = datetime.now()
        timestamp = now.strftime("%Y_%m_%d_%H_%M_%S")
        basefilename = f"{self.redshell_user_directory}redshell_{timestamp}"
        Logger.open_logfile(basefilename)
示例#13
0
 def __init__(self, *args, **kwargs):
     super().__init__(persistent_history_file="~/.faraday-cli_history",
                      *args,
                      **kwargs)
     self.hidden_commands += ["EOF", "cd", "alias", "macro"]
     self.shell_mode = False
     self.TABLE_PRETTY_FORMAT = "psql"
     # hide unwanted settings
     settings_to_hide = ["debug"]
     for setting_name in settings_to_hide:
         self.remove_settable(setting_name)
     intro = [style(f"{logo}\nv:{__version__}", fg=COLORS.CYAN)]
     (
         self.update_available,
         self.latest_version,
     ) = self.check_update_available()
     if self.update_available:
         intro.append(
             style(
                 f"A new version of faraday-cli ({self.latest_version}) is available!!",
                 fg=COLORS.RED,
             ))
     if active_config.faraday_url and active_config.token:
         intro.append(
             style(f"Server: {active_config.faraday_url}", fg=COLORS.GREEN))
         self.api_client = FaradayApi(
             active_config.faraday_url,
             ignore_ssl=active_config.ignore_ssl,
             token=active_config.token,
         )
     else:
         self.api_client = FaradayApi()
         intro.append(
             style("Missing faraday server, run 'auth'", fg=COLORS.YELLOW))
     self.custom_plugins_path = active_config.custom_plugins_path
     self.ignore_info_severity = active_config.ignore_info_severity
     self.auto_command_detection = active_config.auto_command_detection
     self.intro = "\n".join(intro)
     self.data_queue = queue.Queue()
     self.update_prompt()
     self.add_settable(
         Settable(
             "custom_plugins_path",
             str,
             "Path of custom plugins folder",
             onchange_cb=self._onchange_custom_plugins_path,
             settable_object=self,
         ))
     self.add_settable(
         Settable(
             "ignore_info_severity",
             bool,
             "Ignore Informational vulnerabilities "
             "from reports and commands",
             onchange_cb=self._onchange_ignore_info_severity,
             settable_object=self,
         ))
     self.add_settable(
         Settable(
             "auto_command_detection",
             bool,
             "Enable/disable automatic command detection",
             onchange_cb=self._onchange_auto_command_detection,
             settable_object=self,
         ))
     self._create_plugin_manager()