Git Product home page Git Product logo

keyrings.cryptfile's Introduction

Summary

Encrypted plain file keyring backend for use with the keyring package.

Description

The project is mainly targeted on a sufficiently secure storage for plain text passwords (keyring) in a simple portable file, where the default keyring storage implementation of a usual desktop environment doesn't fit.

Cryptography

The keyring is secured with a keyring password. A raw Argon2($argon2id$v=19$m=65536,t=15,p=2) hash is generated from the keyring password, which is used as a key for encryption of plaintext passwords in one of the supported authenticated AES encryption schemes (CCM, EAX, GCM, OCB), where GCM is the default. The resulting encrypted data is persisted, together with the Argon2 salt, nonce and MAC. This value is stored with a service/userid reference in a text file (.ini format). The service/userid is taken into account as associated data for MAC calculation.

Initially, a static reference value, treated as a password is stored as well, and this value is used for verification of the keyring password in subsequent accesses.

Attack surface

The static reference value allow some form of attack, as it encrypts a well known value. Hopefully, the Argon2 hash, combined with the authenticated AES encryption scheme raises the effort to break the key sufficiently high.

The Argon2 parameterization is chosen in a way, that usual desktop and server systems as of today (2017) have to process a significant CPU and Memory load in order to calculate the hashes, which renders brute force attacks impractical.

The authenticated AES encryption scheme prevents tampering with the encrypted data as well as its reference (service/userid).

Quick start guide

In order to get you started, you will need to have a python3 environment and git available (preferably on a linux system).

You might want to provide the python packages argon2-cffi, keyring, pycryptodome and their dependencies (most notably SecretStorage and cryptography) with your system package management, or use a local venv, but that will depend on a properly working C compiler and some development packages installed (python-devel and openssl-devel at least).

Setup package and environment

$ git clone https://github.com/frispete/keyrings.cryptfile
$ cd keyrings.cryptfile
$ pyvenv env
$ . env/bin/activate
(env) $ pip install -e .

The last command should succeed without errors, some development packages might be missing otherwise.

Example session

Create an encrypted keyring, and store a test password into it. The process asks for the keyring password itself, that protects your stored keyring values.

(env) $ python3
Python 3.4.5 (default, Jul 03 2016, 12:57:15) [GCC] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from keyrings.cryptfile.cryptfile import CryptFileKeyring
>>> kr = CryptFileKeyring()
>>> kr.set_password("service", "user", "secret")
Please set a password for your new keyring: ******
Please confirm the password: ******
>>> ^d

Now retrieve the stored secret from the keyring again:

(env) $ python3
Python 3.4.5 (default, Jul 03 2016, 12:57:15) [GCC] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from keyrings.cryptfile.cryptfile import CryptFileKeyring
>>> kr = CryptFileKeyring()
>>> kr.get_password("service", "user")
Please enter password for encrypted keyring: ******
'secret'
>>> ^d

Note, that the KDF delays the {set,get}_password() operations for a few seconds (~1 sec. on a capable system).

Result

The resulting file might look similar to:

(env) $ cat ~/.local/share/python_keyring/cryptfile_pass.cfg
[keyring_2Dsetting]
password_20reference =
    eyJtYWMiOiAiWmVHU2lBalZ5WHd6Vmg3K2Z6TGx2UT09IiwgIm5vbmNlIjogIjB0b2dKa3RYdmdY
    TVpEU1F1QkFOZFE9PSIsICJzYWx0IjogInZ2dFYzN2JvWnVLRTQzVHJ6dGd6YVE9PSIsICJkYXRh
    IjogIk1UdnRzYUZ6OHdSaUZYbFBHOWZmL2dQZ0dmL3ROOG05In0=
scheme = [Argon2] AES128.GCM
version = 1.0

[service]
user =
    eyJtYWMiOiAiaTJ4MWhNVGJ1S0pTZExYSXQwR0dqUT09IiwgIm5vbmNlIjogIlJ5YU1DZmkyZ0JE
    NStlNHN6MGpQRWc9PSIsICJzYWx0IjogIjlIM1hJbDVhZmRZaVhkTUZyTWNOV2c9PSIsICJkYXRh
    IjogImhNVC9LaTRYIn0=

The values can be decoded like this:

(env) $ python3
>>> import base64
>>> base64.decodebytes(b"""
... eyJtYWMiOiAiaTJ4MWhNVGJ1S0pTZExYSXQwR0dqUT09IiwgIm5vbmNlIjogIlJ5YU1DZmkyZ0JE
... NStlNHN6MGpQRWc9PSIsICJzYWx0IjogIjlIM1hJbDVhZmRZaVhkTUZyTWNOV2c9PSIsICJkYXRh
... IjogImhNVC9LaTRYIn0=""")
b'{"mac": "i2x1hMTbuKJSdLXIt0GGjQ==",
   "nonce": "RyaMCfi2gBD5+e4sz0jPEg==",
    "salt": "9H3XIl5afdYiXdMFrMcNWg==",
    "data": "hMT/Ki4X"}'

Discussion

The items of the json dict constitute the encryption parameters and value. In theory, it should be sufficiently hard to get back to the plain value of data without knowledge of the password. Due to the association of the values reference (service and user here) with the authenticated encryption, modifications of values reference are detected/rejected as well.

The class hierarchy is inherited from the keyrings.alt project, which is not exactly easy to follow. The most interesting parts are in keyrings/cryptfile/cryptfile.py, which is quite concise itself, even if you're not fluent in python.

In order to control this process any further, you might want to subclass CryptFileKeyring and/or PlaintextKeyring.

Notes

You can avoid the interactive getpass() request for the keyring password by supplying kr.keyring_key = "your keyring password" before calling any other methods on the keyring.

from getpass import getpass
from os import getenv
from keyrings.cryptfile.cryptfile import CryptFileKeyring
kr = CryptFileKeyring()
kr.keyring_key = getpass()
keyring.set_keyring(kr)

or the keyring password can be provided via an environment variable

os.environ['KEYRING_CRYPTFILE_PASSWORD']='password'

from getpass import getpass
from os import getenv
from keyrings.cryptfile.cryptfile import CryptFileKeyring
kr = CryptFileKeyring()
keyring.set_keyring(kr)

Environment variables

KEYRING_CRYPTFILE_PATH can be used to customize the location of the encrypted file config KEYRING_CRYPTFILE_PASSWORD can be used to provide the password for the encrypted keyring database

Testing

Testing is done with pytest as usual. Just executing pytest should do the trick. A verbose test run is performed with pytest -v, while a single test is selected with pytest -vk test_wrong_password.

Feedback is always welcome.

keyrings.cryptfile's People

Contributors

altendky avatar cerealkella avatar clayote avatar ecederstrand avatar frispete avatar jaraco avatar krpatter-intc avatar nscuro avatar toyg avatar zacharyspector avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

keyrings.cryptfile's Issues

Request: add support for get_credential

I'm attempting to store a username and a password for a specific service. As far as I can understand the get_credential function is currently not supported.

Here is my workaround, but I'd like to get rid of it ... ;-)

def _active_backend_name(user_readable=True):
    return f"{keyring.get_keyring().__module__}.{type(keyring.get_keyring()).__name__}"

def _get_credential(service: str):
    if _active_backend_name() == "keyrings.cryptfile.cryptfile.CryptFileKeyring":
        username = keyring.get_password(service, "USERNAME")
        if username:
            password = keyring.get_password(service, username)
            return SimpleCredential(username, password)
        else:
            return None
    else:
        return keyring.get_credential(service, None)


def _keyring_set(service: str, cred: SimpleCredential):
    if _active_backend_name() == "keyrings.cryptfile.cryptfile.CryptFileKeyring":
        keyring.set_password(service, "USERNAME", cred.username)
    keyring.set_password(service, cred.username, cred.password)

Not on PyPi?

Hi,

Thanks for this package, it's really useful for what I'm doing at the moment. I'm currently mystified at how people distribute passwords to their microservices without something like this.

https://pypi.org/project/keyring/ mentions keyrings.cryptfile as an alternative backend, but it's not actually on PyPi as near as I can tell - the link to it 404's.

Is there a reason for this? It'd make dependency management a little easier. I can try to do it for you if you like, though I've no experience in such things.

And as an aside, it might be worth mentioning in the documentation that you can use

kr.keyring_key = "your keyring password"

to prevent it from querying using getpass() (eg: pulling it from an environment variable). It's a good feature, and I was glad when I found it, but it wasn't obvious to me.

Regards,

Wade

Change keyring password?

Hi,

is there a canonical way to change a keyring password? I cannot find it in doc or see anything obvious in the source code.

Cheers,
Tomasz

ValueError: MAC check failed after adding new user

Hi,
After I added a user to a service, when I use get_password('service','new_user') I get ValueError: mac check failed.
Here's the log:

Traceback (most recent call last):
  File "/home/reyhan/project/.virtualenvs/keras_tf/lib/python3.6/site-packages/keyrings/cryptfile/file_base.py", line 116, in get_password
    password = self.decrypt(password_encrypted, assoc).decode('utf-8')
  File "/home/reyhan/project/.virtualenvs/keras_tf/lib/python3.6/site-packages/keyrings/cryptfile/cryptfile.py", line 130, in decrypt
    return cipher.decrypt_and_verify(data['data'], data['mac'])
  File "/home/reyhan/project/.virtualenvs/keras_tf/lib/python3.6/site-packages/Crypto/Cipher/_mode_gcm.py", line 567, in decrypt_and_verify
    self.verify(received_mac_tag)
  File "/home/reyhan/project/.virtualenvs/keras_tf/lib/python3.6/site-packages/Crypto/Cipher/_mode_gcm.py", line 508, in verify
    raise ValueError("MAC check failed")
ValueError: MAC check failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 18, in <module>
    data["pass"] = file_kr.get_password(crd.getSID(tipe), json_data[tipe]["send"])
  File "/home/reyhan/project/.virtualenvs/keras_tf/lib/python3.6/site-packages/keyrings/cryptfile/file_base.py", line 119, in get_password
    password = self.decrypt(password_encrypted).decode('utf-8')
  File "/home/reyhan/project/.virtualenvs/keras_tf/lib/python3.6/site-packages/keyrings/cryptfile/cryptfile.py", line 130, in decrypt
    return cipher.decrypt_and_verify(data['data'], data['mac'])
  File "/home/reyhan/project/.virtualenvs/keras_tf/lib/python3.6/site-packages/Crypto/Cipher/_mode_gcm.py", line 567, in decrypt_and_verify
    self.verify(received_mac_tag)
  File "/home/reyhan/project/.virtualenvs/keras_tf/lib/python3.6/site-packages/Crypto/Cipher/_mode_gcm.py", line 508, in verify
    raise ValueError("MAC check failed")
ValueError: MAC check failed

Comment rather than issue?

Sounds interesting. To give some perspective (use case?), please add a more user facing README file?
Usage, examples, thoughts for further development?

Environment variable for cryptfile password key

I am trying to use your fantastic keyring module in automation, but it lacks a scriptet method to give it a password key for the cryptfile, it keeps using a console prompt.
I can find the code to use an environment variable in the main branch, but when does it get pushed to a new version 3.10 and to pypi?
Please?

Then I can use it in scripts and with the ansible keyring_info module..

Pull keyring storage password from an environment variable.

I'm trying to use this backend with PIP but the fact that the storage the password is always prompted for, breaks when pip prompts keyring for the actual password.

Is there a way to provide the storage password without user input? The readme shows an environment variable, but I think that's just an example for how a script could use it. Pip is always a process/subprocess so I dont have control of setting it in that manner.

Way to change "access password"

I failed to find in docs and --help a way to change the access password to the keyring itself. Is there a way to rotate the password?

Versions 1.4.x not on PyPI

Hello,

When you have moment, could you please post the latest version on PyPI?

It looks like PyPI didn't pick up the last two versions 1.4.0 and 1.4.1. PyPI seems to be stuck on 1.3.9.

Best Regards,
Matt

When importing CryptFileKeyring get error - ImportError: cannot import name 'properties' from 'keyring.util'

Getting the following error:

In [2]: from keyrings.cryptfile.cryptfile import CryptFileKeyring
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[2], line 1
----> 1 from keyrings.cryptfile.cryptfile import CryptFileKeyring

File ~/devel/keyrings.cryptfile/keyrings/cryptfile/cryptfile.py:7
      4 import json
      6 import configparser
----> 7 from keyring.util import properties
      9 from keyrings.cryptfile import __version__ as version
     10 from keyrings.cryptfile.file import EncryptedKeyring

ImportError: cannot import name 'properties' from 'keyring.util' (/home/user/miniconda3/lib/python3.9/site-packages/keyring/util/__init__.py)

I recently updated the keyring module from 23.9.3 --> 24.2.0. This is where this started. Wanted to bring this issue to your attention. Thank you.

Upgrading from 1.3.4 to 1.3.6 breaks existing cryptfile keyring

It seems, that upgrading keyrings.cryptfile from 1.3.4 to 1.3.6 breaks existing cryptfile-based keyrings, resulting in "MAC check failed" error message on reading.

Steps to reproduce are following:

python3.6 -m venv venv
source venv/bin/activate
pip install wheel
pip install keyrings.cryptfile==1.3.4
export XDG_DATA_HOME=`pwd`
# Please find set.py and get.py files attached below (get_set.tar.gz file)
./set.py # creates new keyring with a single service password
./get.py # correctly prints password retrieved from keyring (cryptfile)

pip install keyrings.cryptfile==1.3.6

./get.py
(...)
File "/home/tfruboes/work_2020_2/2020.10.cryptFileBug/venv/lib/python3.6/site-packages/Crypto/Cipher/_mode_gcm.py", line 508, in verify
    raise ValueError("MAC check failed")
ValueError: MAC check failed

Files needed to reproduce are inside this tarball: get_set.tar.gz .

Could you have a look on this?

Cannot cleanly install from setup.py

setup.py mentions keyring as a dependency, but also contains from keyrings.cryptfile.cryptfile import __version__ as version which only works if keyring is already installed. So keyrings.cryptfile cannot be installed in a clean environment.

The solution is to place __version__ in a file that does not contain external imports.

Cracking benchmark...?

The readme seems to indicate the last time this lib was checked for “crackability” was 2017. I’m not saying its claims are not true anymore (it’s still very likely safe), but it would be cool to have some way to check / benchmark it, like a dockerfile or aws script to run a test on a single key. I’m very much a newb at bruteforcing hashes, so if anybody has suggestions or anything already done, please post it here...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.