Exemplo n.º 1
0
    def get_credentials(self, section=None):
        """
        Return a Credentials object containing the configured credentials.

        Args:
            section (str): The credential section to retrieve.

        Returns:
            Credentials: The credentials retrieved from that source.

        Raises:
            CredentialError: If there is any error retrieving the credentials.
        """
        if section is None:
            section = 'default'
        if self._cached_credentials is None:
            new_creds = {}
            cred_files = [
                p for p in self._search_path if self._security_check(p)
            ]
            if not cred_files:
                raise CredentialError(
                    f"Unable to locate credential file(s) from {self._search_path}"
                )
            raw_cred_files = [
                str(p) for p in cred_files
            ]  # needed to support 3.6.0 correctly & for error message
            try:
                parser = configparser.ConfigParser()
                parser.read(raw_cred_files)
                for sect in parser.sections():
                    new_creds[sect] = Credentials(
                        {name: value
                         for (name, value) in parser.items(sect)})
            except configparser.Error as e:
                raise CredentialError(
                    f"Unable to read credential file(s) {raw_cred_files}"
                ) from e
            self._cached_credentials = new_creds
        if section in self._cached_credentials:
            return self._cached_credentials[section]
        raise CredentialError(
            f"Section {section} not found in credential file(s)")
Exemplo n.º 2
0
def test_get_credentials_fail_open_base_key(monkeypatch, mox):
    """Test getting the credentials from the credential provider, but the base key won't open."""
    monkeypatch.setattr(sys, "platform", "win32")
    sut = RegistryCredentialProvider('Software\\Test')
    mox.StubOutWithMock(sut, '_open_key')
    mox.StubOutWithMock(sut, '_read_value')
    sut._open_key(HKEY_CURRENT_USER, 'Software\\Test').AndRaise(
        CredentialError("Unable to open registry subkey"))
    mox.ReplayAll()
    with pytest.raises(CredentialError) as e:
        sut.get_credentials('default')
    assert "Unable to open registry subkey" in str(e.value)
    mox.VerifyAll()
Exemplo n.º 3
0
def test_read_str_exceptions(monkeypatch, mox):
    """Test reading strings from the registry in ways that throw exceptions."""
    monkeypatch.setattr(sys, "platform", "win32")
    sut = RegistryCredentialProvider()
    mox.StubOutWithMock(sut, '_read_value')
    stub_key = StubKeyObject()
    sut._read_value(stub_key, "Alpha").AndReturn((42, REG_DWORD))
    sut._read_value(stub_key,
                    "Bravo").AndRaise(CredentialError("Unable to read"))
    mox.ReplayAll()
    with pytest.raises(CredentialError) as e1:
        sut._read_str(stub_key, "Alpha")
    assert "not of string type" in str(e1.value)
    with pytest.raises(CredentialError) as e2:
        sut._read_str(stub_key, "Bravo")
    assert "Unable to read" in str(e2.value)
    mox.VerifyAll()
Exemplo n.º 4
0
def test_read_bool_exceptions(monkeypatch, mox):
    """Test reading boolean values from the registry, in ways that generate exceptions."""
    monkeypatch.setattr(sys, "platform", "win32")
    sut = RegistryCredentialProvider()
    mox.StubOutWithMock(sut, '_read_value')
    stub_key = StubKeyObject()
    sut._read_value(stub_key, "Alpha").AndReturn(("!Funky!Stuff!", REG_SZ))
    sut._read_value(stub_key,
                    "Bravo").AndRaise(CredentialError("Unable to read"))
    mox.ReplayAll()
    with pytest.raises(CredentialError) as e1:
        sut._read_bool(stub_key, "Alpha")
    assert "not of integer type" in str(e1.value)
    with pytest.raises(CredentialError) as e2:
        sut._read_bool(stub_key, "Bravo")
    assert "Unable to read" in str(e2.value)
    mox.VerifyAll()
    def get_credentials(self, section=None):
        """
        Return a Credentials object containing the configured credentials.

        Args:
            section (str): The credential section to retrieve.

        Returns:
            Credentials: The credentials retrieved from that source.

        Raises:
            CredentialError: If there is any error retrieving the credentials.
        """
        if section in self._creds:
            return self._creds[section]
        else:
            raise CredentialError(
                f"section {section} not found in credentials")
Exemplo n.º 6
0
    def __init__(self, *args, **kwargs):
        """
        Initialize the CBCloudAPI object.

        Args:
            *args (list): List of arguments to pass to the API object.
            **kwargs (dict): Keyword arguments to pass to the API object.

        Keyword Args:
            profile (str): Use the credentials in the named profile when connecting to the Carbon Black server.
                Uses the profile named 'default' when not specified.
        """
        super(CBCloudAPI, self).__init__(*args, **kwargs)
        self._thread_pool_count = kwargs.pop('thread_pool_count', 1)
        self._lr_scheduler = None
        self._async_executor = None

        if not self.credentials.org_key:
            raise CredentialError("No organization key specified")
Exemplo n.º 7
0
    def _open_key(self, basekey, path):
        """
        Open a key for use.  This is a "test point" intended to be monkeypatched.

        Args:
            basekey (PyHKEY): The base key that the path supplied extends from.
            path (str): The path of the subkey to open from that base key.

        Returns:
            PyHKEY: The new subkey for use.

        Raises:
            CredentialError: If the subkey could not be opened for any reason.
        """
        try:
            return OpenKey(basekey, path)
        except OSError as e:
            raise CredentialError(
                f"Unable to open registry subkey: {path}") from e
Exemplo n.º 8
0
    def __init__(self, keypath=None, userkey=True):
        """
        Initialize the RegistryCredentialProvider.

        Args:
            keypath (str): Path from the selected base key to the key that will contain individual sections.
            userkey (bool): True if the keypath starts at HKEY_CURRENT_USER, False if at HKEY_LOCAL_MACHINE.

        Raises:
            CredentialError: If we attempt to instantiate this provider on a non-Windows system.
        """
        self._cached_credentials = {}
        self._usable = sys.platform.startswith("win32")
        if not self._usable:
            raise CredentialError(
                "Registry credential provider is only usable on Windows systems"
            )
        self._userkey = userkey
        self._keypath = keypath or DEFAULT_KEYPATH
Exemplo n.º 9
0
    def get_credentials(self, section=None):
        """
        Return a Credentials object containing the configured credentials.

        Args:
            section (str): The credential section to retrieve.

        Returns:
            Credentials: The credentials retrieved from that source.

        Raises:
            CredentialError: If there is any error retrieving the credentials.
        """
        if not section:
            raise CredentialError("Section must be specified")
        if section not in self._cached_credentials:
            with self._open_key(self._base_key(), self._keypath) as base_key:
                with self._open_key(base_key, section) as section_key:
                    self._cached_credentials[section] = self._read_credentials(
                        section_key)
        return self._cached_credentials[section]
Exemplo n.º 10
0
    def _read_bool(self, key, value_name):
        """
        Read a boolean value from the registry key specified.

        Args:
            key (PyHKEY): The key to read a value from.
            value_name (str): The name of the value to be returned.

        Returns:
            bool: The value read in. May return None if the value was not found.

        Raises:
            CredentialError: If there was an error reading the value, or if the value was of the wrong type.
        """
        val = self._read_value(key, value_name)
        if val:
            if val[1] != REG_DWORD:
                raise CredentialError(
                    f"value '{value_name}` is not of integer type")
            return val[0] != 0
        return None
Exemplo n.º 11
0
    def _read_value(self, key, value_name):
        """
        Read a value from the registry key specified.  This is a "test point" intended to be monkeypatched.

        Args:
            key (PyHKEY): The key to read a value from.
            value_name (str): The name of the value to be returned.

        Returns:
            tuple: First element of the tuple is the actual value. Second element is the data type as an index.
                May return None if the value was not found.

        Raises:
            CredentialError: If there was an unanticipated error reading the value.
        """
        try:
            return QueryValueEx(key, value_name)
        except FileNotFoundError:
            return None
        except OSError as e:
            raise CredentialError(
                f"Unable to read registry value: {value_name}") from e
Exemplo n.º 12
0
    def __init__(self, *args, **kwargs):
        super(CBCloudAPI, self).__init__(*args, **kwargs)
        self._lr_scheduler = None

        if not self.credentials.org_key:
            raise CredentialError("No organization key specified")