예제 #1
0
def _get_best_keyring():
    """
    Return the best keyring backend for the given environment based on
    priority.
    """
    keyrings = backend.get_all_keyring()
    # rank by priority
    keyrings.sort(key=lambda x: -x.priority)
    # get the most recommended one
    return keyrings[0]
예제 #2
0
def _get_best_keyring():
    """
    Return the best keyring backend for the given environment based on
    priority.
    """
    keyrings = backend.get_all_keyring()
    # rank by priority
    keyrings.sort(key = lambda x: -x.priority)
    # get the most recommended one
    return keyrings[0]
예제 #3
0
    def get_cookies(self):
        salt = b'saltysalt'
        length = 16
        if sys.platform == 'darwin':
            # running Chrome on OSX
            key = None
            # Look for key in all keychains, if nothing matches continue using
            # None as key
            for k in backend.get_all_keyring():
                try:
                    my_pass = k.get_password('Chrome Safe Storage', 'Chrome')
                    if my_pass is not None:
                        my_pass = my_pass.encode('utf8')
                        iterations = 1003
                        key = PBKDF2(my_pass, salt, length, iterations)
                        break
                except Exception as e:
                    pass

        elif sys.platform.startswith('linux'):
            # running Chrome on Linux
            my_pass = '******'.encode('utf8')
            iterations = 1
            key = PBKDF2(my_pass, salt, length, iterations)

        elif sys.platform == 'win32':
            key = None
        else:
            raise BrowserCookieError('Unsupported operating system: ' +
                                     sys.platform)

        for cookie_file in self.cookie_files:
            with create_local_copy(cookie_file) as tmp_cookie_file:
                con = sqlite3.connect(tmp_cookie_file)
                cur = con.cursor()
                cur.execute('SELECT host_key, path, is_secure, expires_utc, '
                            'name, value, encrypted_value FROM cookies;')
                for item in cur.fetchall():
                    host, path, secure, expires, name = item[:5]
                    try:
                        # Any error around creating the cookie oject or
                        # decrypting its value will cause the exception
                        # error message to be printed out on the console.
                        # However the exception shouldn't halt the whole
                        # process, and we should continue processing rest of
                        # the cookies.
                        value = self._decrypt(item[5], item[6], key=key)
                        yield create_cookie(host, path, secure, expires, name,
                                            value)
                    except Exception as e:
                        print(e)
                con.close()
예제 #4
0
파일: __init__.py 프로젝트: vmware/vca-cli
    def get_cookies(self):
        salt = b'saltysalt'
        length = 16
        if sys.platform == 'darwin':
            # running Chrome on OSX
            key = None
            # Look for key in all keychains, if nothing matches continue using
            # None as key
            for k in backend.get_all_keyring():
                try:
                    my_pass = k.get_password('Chrome Safe Storage', 'Chrome')
                    if my_pass is not None:
                        my_pass = my_pass.encode('utf8')
                        iterations = 1003
                        key = PBKDF2(my_pass, salt, length, iterations)
                        break
                except Exception as e:
                    pass

        elif sys.platform.startswith('linux'):
            # running Chrome on Linux
            my_pass = '******'.encode('utf8')
            iterations = 1
            key = PBKDF2(my_pass, salt, length, iterations)

        elif sys.platform == 'win32':
            key = None
        else:
            raise BrowserCookieError('Unsupported operating system: ' +
                                     sys.platform)

        for cookie_file in self.cookie_files:
            with create_local_copy(cookie_file) as tmp_cookie_file:
                con = sqlite3.connect(tmp_cookie_file)
                cur = con.cursor()
                cur.execute('SELECT host_key, path, is_secure, expires_utc, '
                            'name, value, encrypted_value FROM cookies;')
                for item in cur.fetchall():
                    host, path, secure, expires, name = item[:5]
                    try:
                        # Any error around creating the cookie oject or
                        # decrypting its value will cause the exception
                        # error message to be printed out on the console.
                        # However the exception shouldn't halt the whole
                        # process, and we should continue processing rest of
                        # the cookies.
                        value = self._decrypt(item[5], item[6], key=key)
                        yield create_cookie(host, path, secure, expires, name,
                                            value)
                    except Exception as e:
                        print(e)
                con.close()
예제 #5
0
파일: core.py 프로젝트: hvan021/dotfiles-1
def init_backend():
    """first try to load the keyring in the config file, if it has not
    been decleared, assign a defult keyring according to the platform.
    """
    #select a backend according to the config file
    keyring = load_config()

    # if the user dose not specify a keyring, we apply a default one
    if keyring is None:

        keyrings = backend.get_all_keyring()
        # rank according the supported
        keyrings.sort(lambda x, y: y.supported() - x.supported())
        # get the most recommend one
        keyring = keyrings[0]

    set_keyring(keyring)
예제 #6
0
def init_backend():
    """first try to load the keyring in the config file, if it has not
    been decleared, assign a defult keyring according to the platform.
    """
    #select a backend according to the config file
    keyring = load_config()

    # if the user dose not specify a keyring, we apply a default one
    if keyring is None:

        keyrings = backend.get_all_keyring()
        # rank according the supported
        keyrings.sort(lambda x, y: y.supported() - x.supported())
        # get the most recommend one
        keyring = keyrings[0]

    set_keyring(keyring)
예제 #7
0
def init_backend():
    """Load a keyring from a config file or for the default platform.

    First try to load the keyring in the config file, if it has not
    been declared, assign a default keyring according to the platform.
    """
    # select a backend according to the config file
    keyring = load_config()

    # if the user doesn't specify a keyring, we apply a default one
    if keyring is None:

        keyrings = backend.get_all_keyring()
        # rank according to the supported result
        keyrings.sort(key=lambda x: -x.supported())
        # get the most recommended one
        keyring = keyrings[0]

    set_keyring(keyring)
예제 #8
0
def keyring_status(unavailable):
    if keg_keyring is None:
        keyring_notify_no_module()
        return
    import keyring
    import keyring.backend as kb
    viable = kb.get_all_keyring()

    # call get_all_keyring() before this so we are sure all keyrings are loaded
    # on KeyringBackend
    if unavailable:
        click.echo('Unavailable backends')
        for cls in kb.KeyringBackend._classes:
            try:
                cls.priority
            except Exception as e:
                click.echo('    {0.__module__}:{0.__name__} - {1}'.format(
                    cls, e))

    click.echo('\nAvailable backends (backends with priority < 1 are not'
               ' recommended and may be insecure)')
    for backend in viable:
        click.echo('    {0.__module__}:{0.__name__} (priority: {1})'.format(
            backend.__class__, backend.priority))

    click.echo('\nDefault backend')
    backend = keyring.get_keyring()
    click.echo('    {0.__module__}:{0.__name__}'.format(backend.__class__))
    if hasattr(backend, 'file_path'):
        click.echo('    file path: {}'.format(backend.file_path))

    if not flask.current_app.keyring_enabled:
        click.echo(
            '\nKeyring functionality for this app has been DISABLED through the config'
            ' setting KEG_KEYRING_ENABLE.')
    elif not flask.current_app.keyring_manager.verify_backend():
        click.echo('\nWARNING: the current backend is insecure,'
                   ' keyring substitution unavailable.')
        if platform.system() == 'Linux':
            click.echo(
                '\nTRY THIS: use the SecretStorage Setup utility to get a more secure'
                ' keyring backend.')
            click.echo('https://pypi.python.org/pypi/SecretStorage-Setup\n')
예제 #9
0
def init_backend():
    """Load a keyring from a config file or for the default platform.

    First try to load the keyring in the config file, if it has not
    been declared, assign a default keyring according to the platform.
    """
    # select a backend according to the config file
    keyring = load_config()

    # if the user doesn't specify a keyring, we apply a default one
    if keyring is None:

        keyrings = backend.get_all_keyring()
        # rank according to the supported result
        keyrings.sort(key = lambda x: -x.supported())
        # get the most recommended one
        keyring = keyrings[0]

    set_keyring(keyring)
예제 #10
0
    def get_cookies(self):
        salt = b'saltysalt'
        length = 16
        if sys.platform == 'darwin':
            # running Chrome on OSX
            key = None
            for k in backend.get_all_keyring():
                try:
                    my_pass = k.get_password('Chrome Safe Storage', 'Chrome')
                    if my_pass is not None:
                        my_pass = my_pass.encode('utf8')
                        iterations = 1003
                        key = PBKDF2(my_pass, salt, length, iterations)
                        break
                except:
                    pass

        elif sys.platform.startswith('linux'):
            # running Chrome on Linux
            my_pass = '******'.encode('utf8')
            iterations = 1
            key = PBKDF2(my_pass, salt, length, iterations)

        elif sys.platform == 'win32':
            key = None
        else:
            raise BrowserCookieError('Unsupported operating system: ' + sys.platform)

        for cookie_file in self.cookie_files:
            with create_local_copy(cookie_file) as tmp_cookie_file:
                con = sqlite3.connect(tmp_cookie_file)
                cur = con.cursor()
                cur.execute('SELECT host_key, path, secure, expires_utc, name, value, encrypted_value FROM cookies;')
                for item in cur.fetchall():
                    host, path, secure, expires, name = item[:5]
                    try:
                        value = self._decrypt(item[5], item[6], key=key)
                        yield create_cookie(host, path, secure, expires, name, value)
                    except:
                        pass
                con.close()
예제 #11
0
파일: cli.py 프로젝트: guruofgentoo/keg
def keyring_status(unavailable):
    if keg_keyring is None:
        keyring_notify_no_module()
        return
    import keyring
    import keyring.backend as kb
    viable = kb.get_all_keyring()

    # call get_all_keyring() before this so we are sure all keyrings are loaded
    # on KeyringBackend
    if unavailable:
        click.echo('Unavailable backends')
        for cls in kb.KeyringBackend._classes:
            try:
                cls.priority
            except Exception as e:
                click.echo('    {0.__module__}:{0.__name__} - {1}'.format(cls, e))

    click.echo('\nAvailable backends (backends with priority < 1 are not'
               ' recommended and may be insecure)')
    for backend in viable:
        click.echo('    {0.__module__}:{0.__name__} (priority: {1})'
                   .format(backend.__class__, backend.priority))

    click.echo('\nDefault backend')
    backend = keyring.get_keyring()
    click.echo('    {0.__module__}:{0.__name__}'.format(backend.__class__))
    if hasattr(backend, 'file_path'):
        click.echo('    file path: {}'.format(backend.file_path))

    if not flask.current_app.keyring_enabled:
        click.echo('\nKeyring functionality for this app has been DISABLED through the config'
                   ' setting KEG_KEYRING_ENABLE.')
    elif not flask.current_app.keyring_manager.verify_backend():
        click.echo('\nWARNING: the current backend is insecure,'
                   ' keyring substitution unavailable.')
        if platform.system() == 'Linux':
            click.echo('\nTRY THIS: use the SecretStorage Setup utility to get a more secure'
                       ' keyring backend.')
            click.echo('https://pypi.python.org/pypi/SecretStorage-Setup\n')
예제 #12
0
def ensure_keyring_backends():
    # Ensure that keyring backends are initialized before running any tests, as
    # EncryptedKeyring cannot be initialized (on macOS, at least) while
    # pyfakefs is in effect.
    get_all_keyring()
예제 #13
0
def ensure_keyring_backends() -> None:
    # Ensure that keyring backends are initialized before running any tests
    get_all_keyring()
예제 #14
0
def keyring_lookup(service_name, username):
    """
    Determine a keyring backend to use for storing & retrieving credentials as
    follows:

    - If the user has specified a backend explicitly via the
      ``PYTHON_KEYRING_BACKEND`` environment variable or a ``keyringrc.cfg``
      file, use that backend without checking whether it's usable (If it's not,
      the user messed up).

    - Otherwise, query the default backend (which is guaranteed to already have
      the requisite dependencies installed) for the credentials for the given
      service name and username.  If this completes without error (regardless
      of whether the backend contains any such credentials), use that backend.

    - If the query fails (e.g., because a GUI is required but the session is in
      a plain terminal), try using the ``EncryptedKeyring`` backend.

      - If the default backend *was* the ``EncryptedKeyring`` backend, error.

      - If the ``EncryptedKeyring`` backend is not in the list of available
        backends (likely because its dependencies are not installed, though
        that shouldn't happen if dandi was installed properly), error.

      - If ``EncryptedKeyring``'s data file already exists, use it as the
        backend.

      - If ``EncryptedKeyring``'s data file does not already exist, ask the
        user whether they want to start using ``EncryptedKeyring``.  If yes,
        then set ``keyringrc.cfg`` (if it does not already exist) to specify it
        as the default backend, and return the backend.  If no, error.

    Returns a keyring backend and the password it holds (if any) for the given
    service and username.
    """

    kb = load_env() or load_config()
    if kb:
        return (kb, kb.get_password(service_name, username))
    kb = get_keyring()
    try:
        password = kb.get_password(service_name, username)
    except KeyringError as e:
        lgr.info("Default keyring errors on query: %s", e)
        if isinstance(kb, EncryptedKeyring):
            lgr.info(
                "Default keyring is EncryptedKeyring; abandoning keyring procedure"
            )
            raise
        # Use `type(..) is` instead of `isinstance()` to weed out subclasses
        kbs = [k for k in get_all_keyring() if type(k) is EncryptedKeyring]
        assert (
            len(kbs) == 1
        ), "EncryptedKeyring not available; is pycryptodomex installed?"
        kb = kbs[0]
        if op.exists(kb.file_path):
            lgr.info("EncryptedKeyring file exists; using as keyring backend")
            return (kb, kb.get_password(service_name, username))
        lgr.info("EncryptedKeyring file does not exist")
        if click.confirm(
            "Would you like to establish an encrypted keyring?", default=True
        ):
            keyring_cfg = Path(keyringrc_file())
            if keyring_cfg.exists():
                lgr.info("%s exists; refusing to overwrite", keyring_cfg)
            else:
                lgr.info(
                    "Configuring %s to use EncryptedKeyring as default backend",
                    keyring_cfg,
                )
                keyring_cfg.parent.mkdir(parents=True, exist_ok=True)
                keyring_cfg.write_text(
                    "[backend]\n"
                    "default-keyring = keyrings.alt.file.EncryptedKeyring\n"
                )
            return (kb, None)
        raise
    else:
        return (kb, password)