/usr/lib/python3/dist-packages/keyrings/alt/pyfs.py is in python3-keyrings.alt 3.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | import os
import base64
import sys
from six.moves import configparser
from keyring import errors
from keyring.util.escape import escape as escape_for_ini
from keyring.util import platform_, properties
from keyring.backend import KeyringBackend, NullCrypter
from . import keyczar
try:
import fs.opener
import fs.osfs
import fs.errors
import fs.path
import fs.remote
except ImportError:
pass
def has_pyfs():
"""
Does this environment have pyfs installed?
Should return False even when Mercurial's Demand Import allowed import of
fs.*.
"""
with errors.ExceptionRaisedContext() as exc:
fs.__name__
return not bool(exc)
class BasicKeyring(KeyringBackend):
"""BasicKeyring is a Pyfilesystem-based implementation of
keyring.
It stores the password directly in the file, and supports
encryption and decryption. The encrypted password is stored in base64
format.
Being based on Pyfilesystem the file can be local or network-based and
served by any of the filesystems supported by Pyfilesystem including Amazon
S3, FTP, WebDAV, memory and more.
"""
_filename = 'keyring_pyf_pass.cfg'
def __init__(self, crypter, filename=None, can_create=True,
cache_timeout=None):
super(BasicKeyring, self).__init__()
self._crypter = crypter
def_fn = os.path.join(platform_.data_root(), self.__class__._filename)
self._filename = filename or def_fn
self._can_create = can_create
self._cache_timeout = cache_timeout
@properties.NonDataProperty
def file_path(self):
"""
The path to the file where passwords are stored. This property
may be overridden by the subclass or at the instance level.
"""
return os.path.join(platform_.data_root(), self.filename)
@property
def filename(self):
"""The filename used to store the passwords.
"""
return self._filename
def encrypt(self, password):
"""Encrypt the password.
"""
if not password or not self._crypter:
return password or b''
return self._crypter.encrypt(password)
def decrypt(self, password_encrypted):
"""Decrypt the password.
"""
if not password_encrypted or not self._crypter:
return password_encrypted or b''
return self._crypter.decrypt(password_encrypted)
def _open(self, mode='r'):
"""Open the password file in the specified mode
"""
open_file = None
writeable = 'w' in mode or 'a' in mode or '+' in mode
try:
# NOTE: currently the MemOpener does not split off any filename
# which causes errors on close()
# so we add a dummy name and open it separately
if (self.filename.startswith('mem://') or
self.filename.startswith('ram://')):
open_file = fs.opener.fsopendir(self.filename).open('kr.cfg',
mode)
else:
if not hasattr(self, '_pyfs'):
# reuse the pyfilesystem and path
self._pyfs, self._path = fs.opener.opener.parse(
self.filename, writeable=writeable)
# cache if permitted
if self._cache_timeout is not None:
self._pyfs = fs.remote.CacheFS(
self._pyfs, cache_timeout=self._cache_timeout)
open_file = self._pyfs.open(self._path, mode)
except fs.errors.ResourceNotFoundError:
if self._can_create:
segments = fs.opener.opener.split_segments(self.filename)
if segments:
# this seems broken, but pyfilesystem uses it, so we must
fs_name, credentials, url1, url2, path = segments.groups()
assert fs_name, 'Should be a remote filesystem'
host = ''
# allow for domain:port
if ':' in url2:
split_url2 = url2.split('/', 1)
if len(split_url2) > 1:
url2 = split_url2[1]
else:
url2 = ''
host = split_url2[0]
pyfs = fs.opener.opener.opendir(
'%s://%s' % (fs_name, host))
# cache if permitted
if self._cache_timeout is not None:
pyfs = fs.remote.CacheFS(
pyfs, cache_timeout=self._cache_timeout)
# NOTE: fs.path.split does not function in the same
# way os os.path.split... at least under windows
url2_path, url2_filename = os.path.split(url2)
if url2_path and not pyfs.exists(url2_path):
pyfs.makedir(url2_path, recursive=True)
else:
# assume local filesystem
full_url = fs.opener._expand_syspath(self.filename)
# NOTE: fs.path.split does not function in the same
# way os os.path.split... at least under windows
url2_path, url2 = os.path.split(full_url)
pyfs = fs.osfs.OSFS(url2_path)
try:
# reuse the pyfilesystem and path
self._pyfs = pyfs
self._path = url2
return pyfs.open(url2, mode)
except fs.errors.ResourceNotFoundError:
if writeable:
raise
else:
pass
# NOTE: ignore read errors as the underlying caller can fail safely
if writeable:
raise
else:
pass
return open_file
@property
def config(self):
"""load the passwords from the config file
"""
if not hasattr(self, '_config'):
raw_config = configparser.RawConfigParser()
f = self._open()
if f:
raw_config.readfp(f)
f.close()
self._config = raw_config
return self._config
def get_password(self, service, username):
"""Read the password from the file.
"""
service = escape_for_ini(service)
username = escape_for_ini(username)
# fetch the password
try:
password_base64 = self.config.get(service, username).encode()
# decode with base64
password_encrypted = base64.decodestring(password_base64)
# decrypted the password
password = self.decrypt(password_encrypted).decode('utf-8')
except (configparser.NoOptionError, configparser.NoSectionError):
password = None
return password
def set_password(self, service, username, password):
"""Write the password in the file.
"""
service = escape_for_ini(service)
username = escape_for_ini(username)
# encrypt the password
password = password or ''
password_encrypted = self.encrypt(password.encode('utf-8'))
# encode with base64
password_base64 = base64.encodestring(password_encrypted).decode()
# write the modification
if not self.config.has_section(service):
self.config.add_section(service)
self.config.set(service, username, password_base64)
config_file = UnicodeWriterAdapter(self._open('w'))
self.config.write(config_file)
config_file.close()
def delete_password(self, service, username):
service = escape_for_ini(service)
username = escape_for_ini(username)
try:
self.config.remove_option(service, username)
except configparser.NoSectionError:
raise errors.PasswordDeleteError('Password not found')
config_file = UnicodeWriterAdapter(self._open('w'))
self.config.write(config_file)
config_file.close()
@properties.ClassProperty
@classmethod
def priority(cls):
if not has_pyfs():
raise RuntimeError("pyfs required")
return 2
class UnicodeWriterAdapter(object):
"""
Wrap an object with a .write method to accept 'str' on Python 2
and make it a Unicode string.
"""
def __init__(self, orig):
self._orig = orig
def __getattr__(self, *args, **kwargs):
return getattr(self._orig, *args, **kwargs)
def write(self, value):
if isinstance(value, str):
value = value.decode('ascii')
return self._orig.write(value)
if sys.version_info > (3,):
def UnicodeWriterAdapter(x): # noqa
return x
class PlaintextKeyring(BasicKeyring):
"""Unencrypted Pyfilesystem Keyring
"""
def __init__(self, filename=None, can_create=True, cache_timeout=None):
super(PlaintextKeyring, self).__init__(
NullCrypter(), filename=filename, can_create=can_create,
cache_timeout=cache_timeout)
class EncryptedKeyring(BasicKeyring):
"""Encrypted Pyfilesystem Keyring
"""
_filename = 'crypted_pyf_pass.cfg'
def __init__(self, crypter, filename=None, can_create=True,
cache_timeout=None):
super(EncryptedKeyring, self).__init__(
crypter, filename=filename, can_create=can_create,
cache_timeout=cache_timeout)
class KeyczarKeyring(EncryptedKeyring):
"""Encrypted Pyfilesystem Keyring using Keyczar keysets specified in
environment vars
"""
def __init__(self):
super(KeyczarKeyring, self).__init__(
keyczar.EnvironCrypter())
|