File manager - Edit - /var/www/payraty/helpdesk/public/storage/branding_media/images/keyring.tar
Back
usr/bin/keyring 0000755 00000001701 00000000000 0007463 0 ustar 00 #!/usr/bin/python3 # EASY-INSTALL-ENTRY-SCRIPT: 'keyring==23.5.0','console_scripts','keyring' import re import sys # for compatibility with easy_install; see #2198 __requires__ = 'keyring==23.5.0' try: from importlib.metadata import distribution except ImportError: try: from importlib_metadata import distribution except ImportError: from pkg_resources import load_entry_point def importlib_load_entry_point(spec, group, name): dist_name, _, _ = spec.partition('==') matches = ( entry_point for entry_point in distribution(dist_name).entry_points if entry_point.group == group and entry_point.name == name ) return next(matches).load() globals().setdefault('load_entry_point', importlib_load_entry_point) if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(load_entry_point('keyring==23.5.0', 'console_scripts', 'keyring')()) backend.py 0000644 00000014350 00000000000 0006451 0 ustar 00 """ Keyring implementation support """ import os import abc import logging import operator from typing import Optional import importlib_metadata as metadata from . import credentials, errors, util from .util import properties log = logging.getLogger(__name__) by_priority = operator.attrgetter('priority') _limit = None class KeyringBackendMeta(abc.ABCMeta): """ A metaclass that's both an ABCMeta and a type that keeps a registry of all (non-abstract) types. """ def __init__(cls, name, bases, dict): super().__init__(name, bases, dict) if not hasattr(cls, '_classes'): cls._classes = set() classes = cls._classes if not cls.__abstractmethods__: classes.add(cls) class KeyringBackend(metaclass=KeyringBackendMeta): """The abstract base class of the keyring, every backend must implement this interface. """ def __init__(self): self.set_properties_from_env() # @abc.abstractproperty def priority(cls): """ Each backend class must supply a priority, a number (float or integer) indicating the priority of the backend relative to all other backends. The priority need not be static -- it may (and should) vary based attributes of the environment in which is runs (platform, available packages, etc.). A higher number indicates a higher priority. The priority should raise a RuntimeError with a message indicating the underlying cause if the backend is not suitable for the current environment. As a rule of thumb, a priority between zero but less than one is suitable, but a priority of one or greater is recommended. """ @properties.ClassProperty @classmethod def viable(cls): with errors.ExceptionRaisedContext() as exc: cls.priority return not exc @classmethod def get_viable_backends(cls): """ Return all subclasses deemed viable. """ return filter(operator.attrgetter('viable'), cls._classes) @properties.ClassProperty @classmethod def name(cls): """ The keyring name, suitable for display. The name is derived from module and class name. """ parent, sep, mod_name = cls.__module__.rpartition('.') mod_name = mod_name.replace('_', ' ') return ' '.join([mod_name, cls.__name__]) def __str__(self): keyring_class = type(self) return "{}.{} (priority: {:g})".format( keyring_class.__module__, keyring_class.__name__, keyring_class.priority ) @abc.abstractmethod def get_password(self, service: str, username: str) -> Optional[str]: """Get password of the username for the service""" return None @abc.abstractmethod def set_password(self, service: str, username: str, password: str) -> None: """Set password for the username of the service. If the backend cannot store passwords, raise PasswordSetError. """ raise errors.PasswordSetError("reason") # for backward-compatibility, don't require a backend to implement # delete_password # @abc.abstractmethod def delete_password(self, service: str, username: str) -> None: """Delete the password for the username of the service. If the backend cannot delete passwords, raise PasswordDeleteError. """ raise errors.PasswordDeleteError("reason") # for backward-compatibility, don't require a backend to implement # get_credential # @abc.abstractmethod def get_credential( self, service: str, username: Optional[str], ) -> Optional[credentials.Credential]: """Gets the username and password for the service. Returns a Credential instance. The *username* argument is optional and may be omitted by the caller or ignored by the backend. Callers must use the returned username. """ # The default implementation requires a username here. if username is not None: password = self.get_password(service, username) if password is not None: return credentials.SimpleCredential(username, password) return None def set_properties_from_env(self): """For all KEYRING_PROPERTY_* env var, set that property.""" def parse(item): key, value = item pre, sep, name = key.partition('KEYRING_PROPERTY_') return sep and (name.lower(), value) props = filter(None, map(parse, os.environ.items())) for name, value in props: setattr(self, name, value) class Crypter: """Base class providing encryption and decryption""" @abc.abstractmethod def encrypt(self, value): """Encrypt the value.""" pass @abc.abstractmethod def decrypt(self, value): """Decrypt the value.""" pass class NullCrypter(Crypter): """A crypter that does nothing""" def encrypt(self, value): return value def decrypt(self, value): return value def _load_plugins(): """ Locate all setuptools entry points by the name 'keyring backends' and initialize them. Any third-party library may register an entry point by adding the following to their setup.cfg:: [options.entry_points] keyring.backends = plugin_name = mylib.mymodule:initialize_func `plugin_name` can be anything, and is only used to display the name of the plugin at initialization time. `initialize_func` is optional, but will be invoked if callable. """ for ep in metadata.entry_points(group='keyring.backends'): try: log.debug('Loading %s', ep.name) init_func = ep.load() if callable(init_func): init_func() except Exception: log.exception(f"Error initializing plugin {ep}.") @util.once def get_all_keyring(): """ Return a list of all implemented keyrings that can be constructed without parameters. """ _load_plugins() viable_classes = KeyringBackend.get_viable_backends() rings = util.suppress_exceptions(viable_classes, exceptions=TypeError) return list(rings) devpi_client.py 0000644 00000000307 00000000000 0007524 0 ustar 00 from pluggy import HookimplMarker import keyring hookimpl = HookimplMarker("devpiclient") @hookimpl() def devpiclient_get_password(url, username): return keyring.get_password(url, username) backends/fail.py 0000644 00000001504 00000000000 0007544 0 ustar 00 from ..backend import KeyringBackend from ..errors import NoKeyringError class Keyring(KeyringBackend): """ Keyring that raises error on every operation. >>> kr = Keyring() >>> kr.get_password('svc', 'user') Traceback (most recent call last): ... keyring.errors.NoKeyringError: ...No recommended backend... """ priority = 0 def get_password(self, service, username, password=None): msg = ( "No recommended backend was available. Install a recommended 3rd " "party backend package; or, install the keyrings.alt package if " "you want to use the non-recommended backends. See " "https://pypi.org/project/keyring for details." ) raise NoKeyringError(msg) set_password = delete_password = get_password # type: ignore backends/SecretService.py 0000644 00000011203 00000000000 0011374 0 ustar 00 from contextlib import closing import logging from ..util import properties from ..backend import KeyringBackend from ..credentials import SimpleCredential from ..errors import ( InitError, PasswordDeleteError, ExceptionRaisedContext, KeyringLocked, ) try: import secretstorage import secretstorage.exceptions as exceptions except ImportError: pass except AttributeError: # See https://github.com/jaraco/keyring/issues/296 pass log = logging.getLogger(__name__) class Keyring(KeyringBackend): """Secret Service Keyring""" appid = 'Python keyring library' @properties.ClassProperty @classmethod def priority(cls): with ExceptionRaisedContext() as exc: secretstorage.__name__ if exc: raise RuntimeError("SecretStorage required") if secretstorage.__version_tuple__ < (3, 2): raise RuntimeError("SecretStorage 3.2 or newer required") try: with closing(secretstorage.dbus_init()) as connection: if not secretstorage.check_service_availability(connection): raise RuntimeError( "The Secret Service daemon is neither running nor " "activatable through D-Bus" ) except exceptions.SecretStorageException as e: raise RuntimeError("Unable to initialize SecretService: %s" % e) return 5 def get_preferred_collection(self): """If self.preferred_collection contains a D-Bus path, the collection at that address is returned. Otherwise, the default collection is returned. """ bus = secretstorage.dbus_init() try: if hasattr(self, 'preferred_collection'): collection = secretstorage.Collection(bus, self.preferred_collection) else: collection = secretstorage.get_default_collection(bus) except exceptions.SecretStorageException as e: raise InitError("Failed to create the collection: %s." % e) if collection.is_locked(): collection.unlock() if collection.is_locked(): # User dismissed the prompt raise KeyringLocked("Failed to unlock the collection!") return collection def unlock(self, item): if hasattr(item, 'unlock'): item.unlock() if item.is_locked(): # User dismissed the prompt raise KeyringLocked('Failed to unlock the item!') def get_password(self, service, username): """Get password of the username for the service""" collection = self.get_preferred_collection() with closing(collection.connection): items = collection.search_items({"username": username, "service": service}) for item in items: self.unlock(item) return item.get_secret().decode('utf-8') def set_password(self, service, username, password): """Set password for the username of the service""" collection = self.get_preferred_collection() attributes = { "application": self.appid, "service": service, "username": username, } label = "Password for '{}' on '{}'".format(username, service) with closing(collection.connection): collection.create_item(label, attributes, password, replace=True) def delete_password(self, service, username): """Delete the stored password (only the first one)""" collection = self.get_preferred_collection() with closing(collection.connection): items = collection.search_items({"username": username, "service": service}) for item in items: return item.delete() raise PasswordDeleteError("No such password!") def get_credential(self, service, username): """Gets the first username and password for a service. Returns a Credential instance The username can be omitted, but if there is one, it will use get_password and return a SimpleCredential containing the username and password Otherwise, it will return the first username and password combo that it finds. """ query = {"service": service} if username: query["username"] = username collection = self.get_preferred_collection() with closing(collection.connection): items = collection.search_items(query) for item in items: self.unlock(item) username = item.get_attributes().get("username") return SimpleCredential(username, item.get_secret().decode('utf-8')) backends/Windows.py 0000644 00000013275 00000000000 0010273 0 ustar 00 import logging from ..util import properties from ..backend import KeyringBackend from ..credentials import SimpleCredential from ..errors import PasswordDeleteError, ExceptionRaisedContext with ExceptionRaisedContext() as missing_deps: try: # prefer pywin32-ctypes from win32ctypes.pywin32 import pywintypes from win32ctypes.pywin32 import win32cred # force demand import to raise ImportError win32cred.__name__ except ImportError: # fallback to pywin32 import pywintypes import win32cred # force demand import to raise ImportError win32cred.__name__ log = logging.getLogger(__name__) class Persistence: def __get__(self, keyring, type=None): return getattr(keyring, '_persist', win32cred.CRED_PERSIST_ENTERPRISE) def __set__(self, keyring, value): """ Set the persistence value on the Keyring. Value may be one of the win32cred.CRED_PERSIST_* constants or a string representing one of those constants. For example, 'local machine' or 'session'. """ if isinstance(value, str): attr = 'CRED_PERSIST_' + value.replace(' ', '_').upper() value = getattr(win32cred, attr) setattr(keyring, '_persist', value) class DecodingCredential(dict): @property def value(self): """ Attempt to decode the credential blob as UTF-16 then UTF-8. """ cred = self['CredentialBlob'] try: return cred.decode('utf-16') except UnicodeDecodeError: decoded_cred_utf8 = cred.decode('utf-8') log.warning( "Retrieved an UTF-8 encoded credential. Please be aware that " "this library only writes credentials in UTF-16." ) return decoded_cred_utf8 class WinVaultKeyring(KeyringBackend): """ WinVaultKeyring stores encrypted passwords using the Windows Credential Manager. Requires pywin32 This backend does some gymnastics to simulate multi-user support, which WinVault doesn't support natively. See https://github.com/jaraco/keyring/issues/47#issuecomment-75763152 for details on the implementation, but here's the gist: Passwords are stored under the service name unless there is a collision (another password with the same service name but different user name), in which case the previous password is moved into a compound name: {username}@{service} """ persist = Persistence() @properties.ClassProperty @classmethod def priority(cls): """ If available, the preferred backend on Windows. """ if missing_deps: raise RuntimeError("Requires Windows and pywin32") return 5 @staticmethod def _compound_name(username, service): return f'{username}@{service}' def get_password(self, service, username): # first attempt to get the password under the service name res = self._get_password(service) if not res or res['UserName'] != username: # It wasn't found so attempt to get it with the compound name res = self._get_password(self._compound_name(username, service)) if not res: return None return res.value def _get_password(self, target): try: res = win32cred.CredRead( Type=win32cred.CRED_TYPE_GENERIC, TargetName=target ) except pywintypes.error as e: if e.winerror == 1168 and e.funcname == 'CredRead': # not found return None raise return DecodingCredential(res) def set_password(self, service, username, password): existing_pw = self._get_password(service) if existing_pw: # resave the existing password using a compound target existing_username = existing_pw['UserName'] target = self._compound_name(existing_username, service) self._set_password( target, existing_username, existing_pw.value, ) self._set_password(service, username, str(password)) def _set_password(self, target, username, password): credential = dict( Type=win32cred.CRED_TYPE_GENERIC, TargetName=target, UserName=username, CredentialBlob=password, Comment="Stored using python-keyring", Persist=self.persist, ) win32cred.CredWrite(credential, 0) def delete_password(self, service, username): compound = self._compound_name(username, service) deleted = False for target in service, compound: existing_pw = self._get_password(target) if existing_pw and existing_pw['UserName'] == username: deleted = True self._delete_password(target) if not deleted: raise PasswordDeleteError(service) def _delete_password(self, target): try: win32cred.CredDelete(Type=win32cred.CRED_TYPE_GENERIC, TargetName=target) except pywintypes.error as e: if e.winerror == 1168 and e.funcname == 'CredDelete': # not found return raise def get_credential(self, service, username): res = None # get the credentials associated with the provided username if username: res = self._get_password(self._compound_name(username, service)) # get any first password under the service name if not res: res = self._get_password(service) if not res: return None return SimpleCredential(res['UserName'], res.value) backends/chainer.py 0000644 00000004226 00000000000 0010246 0 ustar 00 """ Keyring Chainer - iterates over other viable backends to discover passwords in each. """ from .. import backend from ..util import properties from . import fail class ChainerBackend(backend.KeyringBackend): """ >>> ChainerBackend() <keyring.backends.chainer.ChainerBackend object at ...> """ # override viability as 'priority' cannot be determined # until other backends have been constructed viable = True @properties.ClassProperty @classmethod def priority(cls): """ If there are backends to chain, high priority Otherwise very low priority since our operation when empty is the same as null. """ return 10 if len(cls.backends) > 1 else (fail.Keyring.priority - 1) @properties.ClassProperty @classmethod def backends(cls): """ Discover all keyrings for chaining. """ def allow(keyring): limit = backend._limit or bool return ( not isinstance(keyring, ChainerBackend) and limit(keyring) and keyring.priority > 0 ) allowed = filter(allow, backend.get_all_keyring()) return sorted(allowed, key=backend.by_priority, reverse=True) def get_password(self, service, username): for keyring in self.backends: password = keyring.get_password(service, username) if password is not None: return password def set_password(self, service, username, password): for keyring in self.backends: try: return keyring.set_password(service, username, password) except NotImplementedError: pass def delete_password(self, service, username): for keyring in self.backends: try: return keyring.delete_password(service, username) except NotImplementedError: pass def get_credential(self, service, username): for keyring in self.backends: credential = keyring.get_credential(service, username) if credential is not None: return credential backends/libsecret.py 0000644 00000013457 00000000000 0010617 0 ustar 00 import logging from ..util import properties from ..backend import KeyringBackend from ..credentials import SimpleCredential from ..errors import ( PasswordDeleteError, PasswordSetError, ExceptionRaisedContext, KeyringLocked, ) available = False try: import gi from gi.repository import Gio from gi.repository import GLib gi.require_version('Secret', '1') from gi.repository import Secret available = True except (AttributeError, ImportError, ValueError): pass log = logging.getLogger(__name__) class Keyring(KeyringBackend): """libsecret Keyring""" appid = 'Python keyring library' if available: schema = Secret.Schema.new( "org.freedesktop.Secret.Generic", Secret.SchemaFlags.NONE, { "application": Secret.SchemaAttributeType.STRING, "service": Secret.SchemaAttributeType.STRING, "username": Secret.SchemaAttributeType.STRING, }, ) collection = Secret.COLLECTION_DEFAULT @properties.ClassProperty @classmethod def priority(cls): with ExceptionRaisedContext() as exc: Secret.__name__ if exc: raise RuntimeError("libsecret required") return 4.8 def get_password(self, service, username): """Get password of the username for the service""" attributes = { "application": self.appid, "service": service, "username": username, } try: items = Secret.password_search_sync( self.schema, attributes, Secret.SearchFlags.UNLOCK, None ) except GLib.Error as error: quark = GLib.quark_try_string('g-io-error-quark') if error.matches(quark, Gio.IOErrorEnum.FAILED): raise KeyringLocked('Failed to unlock the item!') from error raise for item in items: try: return item.retrieve_secret_sync().get_text() except GLib.Error as error: quark = GLib.quark_try_string('secret-error') if error.matches(quark, Secret.Error.IS_LOCKED): raise KeyringLocked('Failed to unlock the item!') from error raise def set_password(self, service, username, password): """Set password for the username of the service""" attributes = { "application": self.appid, "service": service, "username": username, } label = "Password for '{}' on '{}'".format(username, service) try: stored = Secret.password_store_sync( self.schema, attributes, self.collection, label, password, None ) except GLib.Error as error: quark = GLib.quark_try_string('secret-error') if error.matches(quark, Secret.Error.IS_LOCKED): raise KeyringLocked("Failed to unlock the collection!") from error quark = GLib.quark_try_string('g-io-error-quark') if error.matches(quark, Gio.IOErrorEnum.FAILED): raise KeyringLocked("Failed to unlock the collection!") from error raise if not stored: raise PasswordSetError("Failed to store password!") def delete_password(self, service, username): """Delete the stored password (only the first one)""" attributes = { "application": self.appid, "service": service, "username": username, } try: items = Secret.password_search_sync( self.schema, attributes, Secret.SearchFlags.UNLOCK, None ) except GLib.Error as error: quark = GLib.quark_try_string('g-io-error-quark') if error.matches(quark, Gio.IOErrorEnum.FAILED): raise KeyringLocked('Failed to unlock the item!') from error raise for item in items: try: removed = Secret.password_clear_sync( self.schema, item.get_attributes(), None ) except GLib.Error as error: quark = GLib.quark_try_string('secret-error') if error.matches(quark, Secret.Error.IS_LOCKED): raise KeyringLocked('Failed to unlock the item!') from error raise return removed raise PasswordDeleteError("No such password!") def get_credential(self, service, username): """Get the first username and password for a service. Return a Credential instance The username can be omitted, but if there is one, it will use get_password and return a SimpleCredential containing the username and password Otherwise, it will return the first username and password combo that it finds. """ query = {"service": service} if username: query["username"] = username try: items = Secret.password_search_sync( self.schema, query, Secret.SearchFlags.UNLOCK, None ) except GLib.Error as error: quark = GLib.quark_try_string('g-io-error-quark') if error.matches(quark, Gio.IOErrorEnum.FAILED): raise KeyringLocked('Failed to unlock the item!') from error raise for item in items: username = item.get_attributes().get("username") try: return SimpleCredential( username, item.retrieve_secret_sync().get_text() ) except GLib.Error as error: quark = GLib.quark_try_string('secret-error') if error.matches(quark, Secret.Error.IS_LOCKED): raise KeyringLocked('Failed to unlock the item!') from error raise backends/null.py 0000644 00000000550 00000000000 0007603 0 ustar 00 from ..backend import KeyringBackend class Keyring(KeyringBackend): """ Keyring that return None on every operation. >>> kr = Keyring() >>> kr.get_password('svc', 'user') """ priority = -1 def get_password(self, service, username, password=None): pass set_password = delete_password = get_password # type: ignore backends/__init__.py 0000644 00000000000 00000000000 0010356 0 ustar 00 backends/kwallet.py 0000644 00000013334 00000000000 0010300 0 ustar 00 import sys import os import contextlib from ..backend import KeyringBackend from ..credentials import SimpleCredential from ..errors import PasswordDeleteError from ..errors import PasswordSetError, InitError, KeyringLocked from ..util import properties try: import dbus from dbus.mainloop.glib import DBusGMainLoop except ImportError: pass except AttributeError: # See https://github.com/jaraco/keyring/issues/296 pass def _id_from_argv(): """ Safely infer an app id from sys.argv. """ allowed = AttributeError, IndexError, TypeError with contextlib.suppress(allowed): return sys.argv[0] class DBusKeyring(KeyringBackend): """ KDE KWallet 5 via D-Bus """ appid = _id_from_argv() or 'Python keyring library' wallet = None bus_name = 'org.kde.kwalletd5' object_path = '/modules/kwalletd5' @properties.ClassProperty @classmethod def priority(cls): if 'dbus' not in globals(): raise RuntimeError('python-dbus not installed') try: bus = dbus.SessionBus(mainloop=DBusGMainLoop()) except dbus.DBusException as exc: raise RuntimeError(exc.get_dbus_message()) if not ( bus.name_has_owner(cls.bus_name) or cls.bus_name in bus.list_activatable_names() ): raise RuntimeError( "The KWallet daemon is neither running nor activatable through D-Bus" ) if "KDE" in os.getenv("XDG_CURRENT_DESKTOP", "").split(":"): return 5.1 return 4.9 def __init__(self, *arg, **kw): super().__init__(*arg, **kw) self.handle = -1 def _migrate(self, service): old_folder = 'Python' entry_list = [] if self.iface.hasFolder(self.handle, old_folder, self.appid): entry_list = self.iface.readPasswordList( self.handle, old_folder, '*@*', self.appid ) for entry in entry_list.items(): key = entry[0] password = entry[1] username, service = key.rsplit('@', 1) ret = self.iface.writePassword( self.handle, service, username, password, self.appid ) if ret == 0: self.iface.removeEntry(self.handle, old_folder, key, self.appid) entry_list = self.iface.readPasswordList( self.handle, old_folder, '*', self.appid ) if not entry_list: self.iface.removeFolder(self.handle, old_folder, self.appid) def connected(self, service): if self.handle >= 0: if self.iface.isOpen(self.handle): return True bus = dbus.SessionBus(mainloop=DBusGMainLoop()) wId = 0 try: remote_obj = bus.get_object(self.bus_name, self.object_path) self.iface = dbus.Interface(remote_obj, 'org.kde.KWallet') self.handle = self.iface.open(self.iface.networkWallet(), wId, self.appid) except dbus.DBusException as e: raise InitError('Failed to open keyring: %s.' % e) if self.handle < 0: return False self._migrate(service) return True def get_password(self, service, username): """Get password of the username for the service""" if not self.connected(service): # the user pressed "cancel" when prompted to unlock their keyring. raise KeyringLocked("Failed to unlock the keyring!") if not self.iface.hasEntry(self.handle, service, username, self.appid): return None password = self.iface.readPassword(self.handle, service, username, self.appid) return str(password) def get_credential(self, service, username): """Gets the first username and password for a service. Returns a Credential instance The username can be omitted, but if there is one, it will forward to get_password. Otherwise, it will return the first username and password combo that it finds. """ if username is not None: return super().get_credential(service, username) if not self.connected(service): # the user pressed "cancel" when prompted to unlock their keyring. raise KeyringLocked("Failed to unlock the keyring!") for username in self.iface.entryList(self.handle, service, self.appid): password = self.iface.readPassword( self.handle, service, username, self.appid ) return SimpleCredential(str(username), str(password)) def set_password(self, service, username, password): """Set password for the username of the service""" if not self.connected(service): # the user pressed "cancel" when prompted to unlock their keyring. raise PasswordSetError("Cancelled by user") self.iface.writePassword(self.handle, service, username, password, self.appid) def delete_password(self, service, username): """Delete the password for the username of the service.""" if not self.connected(service): # the user pressed "cancel" when prompted to unlock their keyring. raise PasswordDeleteError("Cancelled by user") if not self.iface.hasEntry(self.handle, service, username, self.appid): raise PasswordDeleteError("Password not found") self.iface.removeEntry(self.handle, service, username, self.appid) class DBusKeyringKWallet4(DBusKeyring): """ KDE KWallet 4 via D-Bus """ bus_name = 'org.kde.kwalletd' object_path = '/modules/kwalletd' @properties.ClassProperty @classmethod def priority(cls): return super().priority - 1 backends/__pycache__/chainer.cpython-310.pyc 0000644 00000004617 00000000000 0014611 0 ustar 00 o ���a� � @ s>