Keyring ubuntu что это

Обновлено: 03.07.2024

The Python keyring library provides an easy way to access the system keyring service from python. It can be used in any application that needs safe password storage.

These recommended keyring backends are supported:

Freedesktop Secret Service supports many DE including GNOME (requires secretstorage)

Other keyring implementations are available through Third-Party Backends.

On Linux, the KWallet backend relies on dbus-python, which does not always install correctly when using pip (compilation is needed). For best results, install dbus-python as a system package.

The basic usage of keyring is pretty simple: just call keyring.set_password and keyring.get_password :

Command-line Utility¶

Keyring supplies a keyring command which is installed with the package. After installing keyring in most environments, the command should be available for setting, getting, and deleting passwords. For more information on usage, invoke with no arguments or with --help as so:

The command-line functionality is also exposed as an executable package, suitable for invoking from Python like so:

The python keyring lib contains implementations for several backends. The library will attempt to automatically choose the most suitable backend for the current environment. Users may also specify the preferred keyring in a config file or by calling the set_keyring() function.

Config file path¶

The configuration is stored in a file named “keyringrc.cfg” found in a platform-specific location. To determine where the config file is stored, run the following:

Some keyrings also store the keyring data in the file system. To determine where the data files are stored, run:

Config file content¶

To specify a keyring backend, set the default-keyring option to the full path of the class for that backend, such as keyring.backends.OS_X.Keyring .

If keyring-path is indicated, keyring will add that path to the Python module search path before loading the backend.

For example, this config might be used to load the SimpleKeyring from the simplekeyring module in the ./demo directory (not implemented):

In addition to the backends provided by the core keyring package for the most common and secure use cases, there are additional keyring backend implementations available for other use-cases. Simply install them to make them available:

keyrings.cryptfile - Encrypted text file storage.

keyring_jeepney - a pure Python backend using the secret service DBus API for desktop Linux.

keyrings.alt - “alternate”, possibly-insecure backends, originally part of the core package, but available for opt-in.

gsheet-keyring - a backend that stores secrets in a Google Sheet. For use with ipython-secrets.

bitwarden-keyring - a backend that stores secrets in the BitWarden password manager.

sagecipher - an encryption backend which uses the ssh agent protocol’s signature operation to derive the cipher key.

keyrings.osx_keychain_keys - OSX keychain key-management, for private, public and symmetric keys.

The interface for the backend is defined by keyring.backend.KeyringBackend . Every backend should derive from that base class and define a priority attribute and three functions: get_password() , set_password() , and delete_password() . The get_credential() function may be defined if desired.

See the backend module for more detail on the interface of this class.

Keyring employs entry points to allow any third-party package to implement backends without any modification to the keyring itself. Those interested in creating new backends are encouraged to create new, third-party packages in the keyrings namespace, in a manner modeled by the keyrings.alt package. See the setup.cfg file in that project for a hints on how to create the requisite entry points. Backends that prove essential may be considered for inclusion in the core library, although the ease of installing these third-party packages should mean that extensions may be readily available.

To create an extension for Keyring, please submit a pull request to have your extension mentioned as an available extension.

Keyring additionally allows programmatic configuration of the backend calling the api set_keyring() . The indicated backend will subsequently be used to store and retrieve passwords.

To invoke set_keyring :

In many cases, uninstalling keyring will never be necessary. Especially on Windows and macOS, the behavior of keyring is usually degenerate, meaning it will return empty values to the caller, allowing the caller to fall back to some other behavior.

In some cases, the default behavior of keyring is undesirable and it would be preferable to disable the keyring behavior altogether. There are several mechanisms to disable keyring:

Uninstall keyring. Most applications are tolerant to keyring not being installed. Uninstalling keyring should cause those applications to fall back to the behavior without keyring. This approach affects that Python environment where keyring would otherwise have been installed.

Configure the Null keyring in the environment. Set PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring in the environment, and the Null (degenerate) backend will be used. This approach affects all uses of Keyring where that variable is set.

Permanently configure the Null keyring for the user by running keyring --disable or python -m keyring --disable . This approach affects all uses of keyring for that user.

Keyring provides a mechanism to alter the keyring’s behavior through environment variables. Each backend implements a KeyringBackend.set_properties_from_env , which when invoked will find all environment variables beginning with KEYRING_PROPERTY_ and will set a property for each on the keyring. This method is invoked during initialization for the default/configured keyring.

This mechanism may be used to set some useful values on various keyrings, including:

keychain; macOS, path to an alternate keychain file

appid; Linux/SecretService, alternate ID for the application

The following is a complete transcript for installing keyring in a virtual environment on Ubuntu 16.04. No config file was used:

It is possible to use the SecretService backend on Linux systems without X11 server available (only D-Bus is required). In this case:

Install the GNOME Keyring daemon.

Start a D-Bus session, e.g. run dbus-run-session -- sh and run the following commands inside that shell.

Run gnome-keyring-daemon with --unlock option. The description of that option says:

Read a password from stdin, and use it to unlock the login keyring or create it if the login keyring does not exist.

When that command is started, enter a password into stdin and press Ctrl+D (end of data). After that, the daemon will fork into background (use --foreground option to block).

Now you can use the SecretService backend of Keyring. Remember to run your application in the same D-Bus session as the daemon.

It is possible to use keyring with the SecretService backend in Docker containers as well. All you need to do is install the necessary dependencies and add the –privileged flag to avoid any Operation not permitted errors when attempting to unlock the system’s keyring.

The following is a complete transcript for installing keyring on a Ubuntu 18:04 container:

The keyring lib has a few functions:

get_keyring() : Return the currently-loaded keyring implementation.

get_password(service, username) : Returns the password stored in the active keyring. If the password does not exist, it will return None.

get_credential(service, username) : Return a credential object stored in the active keyring. This object contains at least username and password attributes for the specified service, where the returned username may be different from the argument.

set_password(service, username, password) : Store the password in the keyring.

delete_password(service, username) : Delete the password stored in keyring. If the password does not exist, it will raise an exception.

In all cases, the parameters ( service , username , password ) should be Unicode text.

Exceptions¶

The keyring lib raises following exceptions:

keyring.errors.KeyringError : Base Error class for all exceptions in keyring lib.

keyring.errors.InitError : Raised when the keyring cannot be initialized.

keyring.errors.PasswordSetError : Raised when password cannot be set in the keyring.

keyring.errors.PasswordDeleteError : Raised when the password cannot be deleted in the keyring.

Python keyring lib is an open community project and eagerly welcomes contributors.

Available as part of the Tidelift Subscription.

This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

Each builtin backend may have security considerations to understand before using this library. Authors of tools or libraries utilizing keyring are encouraged to consider these concerns.

As with any list of known security concerns, this list is not exhaustive. Additional issues can be added as needed.

Any Python script or application can access secrets created by keyring from that same Python executable without the operating system prompting the user for a password. To cause any specific secret to prompt for a password every time it is accessed, locate the credential using the Keychain Access application, and in the Access Control settings, remove Python from the list of allowed applications.

No analysis has been performed

No analysis has been performed

No analysis has been performed

This project makes use of automated releases continuous integration. The simple workflow is to tag a commit and push it to Github. If it passes tests in CI, it will be automatically deployed to PyPI.

Other things to consider when making a release:

Check that the changelog is current for the intended release.

Tests are continuously run in Github Actions.

To run the tests locally, install and invoke tox.

The project was based on Tarek Ziade’s idea in this post. Kang Zhang initially carried it out as a Google Summer of Code project, and Tarek mentored Kang on this project.

Delete the password for the user in the specified service.

Get a Credential for the specified service.

Get current keyring backend.

Get password from the specified service.

keyring. set_keyring ( keyring ) ¶

Set current keyring backend.

Eventually, I decided to keep them here together as I googled all it in the same scope and the are related to each other.

So, in this post we will speak about the next:

  • what is the keyring at all
  • what is the difference between the Linux keyring and GNOME keyring, and do they relate to each other
  • what keyring implementations are
  • what is the org.freedesktop Secret Service and how it relates to the GNOME keyring
  • what is D-Bus, and how we can use it to see how a keyring service is working
  • and a couple of examples with Linux Keyring, GNOME Keyring, KWallet, and KeePass as a keyring backend

This post was written by a long-long googling, so here will be a lot of links to documents and other materials that were used.


What is the Keyring?

In cryptography, a keyring stores known encryption keys (and, in some cases, passwords).

Much like a keyring in real life allows you to keep certain sets of keys together, a keyring in Passwords and Keys allows you to keep passwords and keys in separate groups.

a keyring service that enables internal server components and plugins to securely store sensitive information for later retrieval

The Linux key-management facility is primarily a way for various kernel components to retain or cache security data, authentication keys, encryption keys, and other data in the kernel.

Linux keyring vs gnome-keyring

Useful links used:

GNOME Keyring is a collection of components in GNOME that store secrets, passwords, keys, certificates and make them available to applications.

Summary

Keyrings implementations

Beside that, python-keyring mention:

And this list is not full.

Also, there a bunch of client applications to be used with those keyrings, again the list is not full:

Passwords interception from the gnome-keyting

What is the Secret Service?

What is it doing in the Linux and how can I touch it?

Also, the Secret Service API supported not only by the GNOME Keyring and KWallet but also for example by the KeePass and other applications.

The Secret Service glossary

    : a password itself, or any other secret data : each such a secret plus its set of attributes makes up an item
  • collection: a set of such items makes a collection (similar to the keyring or wallet concepts)
  • collections and items represented by D-Bus objects, each with its unique path : client applications without special conditions have to save items to the default collection which has to be accessible via the /org/freedesktop/secrets/aliases/default D-Bus path

Not its time to try to recall with is the D-Bus so often mentioned in the previous parts, and how to deal with it.

And in short about main concepts and terms in D-Bus:

D-Bus tools

For example d-feet , install it:


Keyrings examples

And a few examples of how those backends can be used from a Python or CLI utilities.

Linux keyring

You can use the keyctl utility from the keyutils , and systemd-ask-password .

And from the documentation:

Each process subscribes to three keyrings: a thread-specific keyring, a process-specific keyring, and a session-specific keyring.

If you use automatic login in Ubuntu or other Linux distributions, you might have come across a pop-up message of this sort:

Enter password to unlock your login keyring
The login keyring did not get unlocked when you logged into your computer.

It keeps on popping up several times before disappearing if you keep on clicking cancel. You may wonder why do you keep seeing this keyring message all the time?

Surprised? Let me explain the keyring concept in Linux.

What is keyring in Linux and why is it used?

Why do you use a keyring (also called keychain) in the real life? You use it to keep one or more keys grouped together so that they are easy to find and carry.

Most desktop environments like GNOME, KDE, Xfce etc use an implementation of gnome-keyring to provide this keyring feature in Linux.

This keyring keeps your ssh keys, GPG keys and keys from applications that use this feature, like Chromium browser. By default, the keyring is locked with a master password which is often the login password of the account.

The problem comes when you switch to auto-login in Ubuntu. This means that you login to the system without entering the password. In such case, your keyring is not unlocked automatically.

Keyring is a security feature

Remember I told you that the keyring was a security feature? Now imagine that on your Linux desktop, you are using auto-login. Anyone with access to your desktop can enter the system without password but you have no issues with that perhaps because you use it to browse internet only.

If this keyring always exited, why you never saw it?

You can easily manage the keyring and passwords

You can use this GUI application to see what application use the keyring to manage/lock passwords.

This is slightly better than keeping a list of passwords in a text file. At least in this case your passwords can be viewed only when you unlock the keyring with password.

One potential problem here is that if you format your system, the manually saved passwords are definitely lost. Normally, you make backup of personal files, not of all the user specific data such as keyring files.

There is way to handle that. The keyring data is usually stored in

So, let me summarize what you have learned so far:

Change keyring password

Suppose you changed your account password. Now when you login, your system tries to unlock the keyring automatically using the new login password. But the keyring still uses the old login password.

In such a case, you can change the keyring password to the new login password so that the keyring gets unlocked automatically as soon as you login to your system.

Open the Password and Keys application from the menu:

Now, right click on the Login keyring and click on Change Password:

It will ask for your confirmation:

Alternatively, you may also manually delete the keyring files in

When the old keyring is removed and you try to use Chrome/Chromium, it will ask you to create new keyring.

You can use the new login password so that the keyring gets unlocked automatically.

Disable keyring password

The process is similar to changing keyring password. Open Password and Keys application and go on to change the keyring password.

This way, the keyring will have no password and it remains unlocked all the time.

Like what you read? Please share it with others.

About Abhishek Prakash

Creator of It's FOSS. An ardent Linux user & open source promoter. Huge fan of classic detective mysteries ranging from Agatha Christie and Sherlock Holmes to Detective Columbo & Ellery Queen. Also a movie buff with a soft corner for film noir.

Is there a way to make the login window always show on the active desktop? I could do this with devilspie2 if I knew the application or window name.

Chromium и keyring

Chromium без keyring

Попробуем получить пароль из базы с Chromium без keyring.

Set the password store to use. The default is to automatically detect based on the desktop environment. basic selects the built in, unencrypted password store. gnome selects Gnome keyring. kwallet selects (KDE) KWallet. (Note that KWallet may qdbus --session org.freedesktop.DBus / org.freedesktop.DBus.GetConnectionUnixProcessID org.freedesktop.secrets Could not get PID of name 'org.freedesktop.secrets': no such name

Создаём каталог для данных Chromium:

chromium --user-data-dir=/tmp/data-chrome-test-1 --password-store=basic

Логинимся куда-то, сохраняем пароль, закрываем браузер, проверяем базу:

sqlite3 /tmp/data-chrome-test-1/Default/Login\ Data 'select username_value, password_value from logins;'

Кстати, просмотреть все поля и их типы в таблице logins можно с помощью .schema :

/.config/chromium/Default/Login\ Data '.schema logins'

CREATE TABLE IF NOT EXISTS "logins" (origin_url VARCHAR NOT NULL, action_url VARCHAR, \ username_element VARCHAR, username_value VARCHAR, password_element VARCHAR, password_value BLOB \

Chromium с keyring

Запускаем браузер, но теперь указываем --password-store=gnome , и меняем user-data-dir , что бы использовать чистую SQLite базу с паролями:

chromium --user-data-dir=/tmp/data-chrome-test-2 --password-store=gnome

Ещё раз логинимся, сохраняем пароль, проверяем базу:

sqlite3 /tmp/data-chrome-test-2/Default/Login\ Data 'select username_value, password_value from logins;'

Chromium passwords decrypt

Теперь попробуем разобраться:

Chrome v10 vs v11

Сейчас узнаем почему.

Начнём с конца файла, с функции DecryptString() :

    DecryptString() : в version сохраняет версию (v10 или v11):

Так что всё оказалось намного проще:

Python скрипт для получения паролей

Среди прочего видим, что для шифрования используется AES 128 bit CBC:

Далее в функции GetEncryptionKey() смотрим, как создаётся ключ для шифрования:

Chromium && Secret Service

Добавляем папку для новой базы данных Chromium:

Запускаем Chromium с каталогом данных data-chrome-test-2 из неё и указываем --password-store=gnome :

chromium --user-data-dir=/tmp/data-chrome-test-2/ --password-store=gnome
  1. Chrome Safe Storage Control
  2. Chromium Safe Storage


Можно посмотреть через D-Bus и Secret Service, что бы проверить коллекцию:

[/org/freedesktop/secrets/collection/Main/f0fdc4706ef44958b716e28c13d66bed]

Теперь попробуем использовать этот пароль (значение атрибута secret выше) из Chromium Safe Storage в качестве значения переменной pb_pass в нашем скрипте.

Выходим из Chromium, что бы разлочить базу, иначе будет ошибка вида:

for url, user, encrypted_password in get_encrypted_data(db_path): File "./get_chrome_pass.py", line 15, in get_encrypted_data data = cursor.execute('SELECT action_url, username_value, password_value FROM logins')

В скрипте меняем базу (путь к ней):

Decrypting the string: b'v11\xfc\x82\xf7H\n!@\x86\xb7\x982\xa8\x1fjA\xfd'

Вывод

Читайте также: