def __init__(self): """ Test whether DBus and Gnome-Keyring are available. """ self.connection = secretstorage.dbus_init() asyncio.set_event_loop(asyncio.new_event_loop()) secretstorage.get_default_collection(self.connection)
def set_access_token(token: bytes): conn = secretstorage.dbus_init() coll = secretstorage.get_default_collection(conn) if coll.is_locked(): coll.unlock() coll.create_item(SS_TOKEN_LABEL, SS_TOKEN_ATTRIBUTE, token, replace=True)
def is_unlocked(self): try: collection = secretstorage.get_default_collection(self.connection) return not collection.is_locked() except secretstorage.exceptions.SecretServiceNotAvailableException: logger.debug('SecretStorage is closed.') return False
def _try_dbus_auth(self, restaurant_identifier: str) -> Optional[bytes]: eprint("Trying D-Bus Secret Service") try: with secretstorage.dbus_init() as connection: collection = secretstorage.get_default_collection(connection) attributes = { "application": "Scone", "restaurant": restaurant_identifier, } items = list(collection.search_items(attributes)) if items: eprint("Found secret sauce for this Restaurant, unlocking…") items[0].unlock() return URLSafeBase64Encoder.decode(items[0].get_secret()) else: eprint("Did not find secret sauce for this Restaurant.") eprint("Enter it and I will try and store it...") secret = self._try_manual_entry() if secret is not None: collection.create_item( f"scone({restaurant_identifier}): secret sauce", attributes, URLSafeBase64Encoder.encode(secret), ) return secret return None except EOFError: # XXX what happens with no D-Bus return None
def get_credentials(): bus = secretstorage.dbus_init() collection = secretstorage.get_default_collection(bus) collection.unlock() secret = next(collection.search_items({'application': 'barclays'})).get_secret() return json.loads(secret)
def generate_new(self): eprint("Generating a new freezer key...") self.key = nacl.utils.random(SecretBox.KEY_SIZE) key_b64 = URLSafeBase64Encoder.encode(self.key) eprint("Your new key is: " + key_b64.decode()) eprint("Pretty please store it in a safe place!") if not self.restaurant_identifier: eprint("No RI; not saving to SS") return eprint("Attempting to save it to the secret service...") eprint("(save it yourself anyway!)") with secretstorage.dbus_init() as connection: collection = secretstorage.get_default_collection(connection) attributes = { "application": "Scone", "restaurant": self.restaurant_identifier, } items = list(collection.search_items(attributes)) if items: eprint( "Found secret sauce for this Restaurant already!" " Will not overwrite." ) else: eprint("Storing secret sauce for this Restaurant...") collection.create_item( f"scone({self.restaurant_identifier}): secret sauce", attributes, key_b64, ) eprint("OK!")
def __init__(self): # init base class super().__init__() self.login_db_path = f"/home/{getuser()}/.config/google-chrome/Default/Login Data" self.tmp_login_db_path = f"/home/{getuser()}/.config/google-chrome/Default/Login_tmp" if os.path.exists(self.login_db_path): shutil.copy2( self.login_db_path, self.tmp_login_db_path ) # making a temp copy since login data db is locked while chrome is running else: print("It seems that no chrome browser is installed! Exiting...") exit(1) self.iv = b' ' * 16 self.password = '******'.encode('utf8') bus = secretstorage.dbus_init() collection = secretstorage.get_default_collection(bus) for item in collection.get_all_items(): if item.get_label() == 'Chrome Safe Storage': self.password = item.get_secret() break self.key = PBKDF2(password=self.password, salt=b'saltysalt', dkLen=16, count=1) self.cipher = AES.new(self.key, AES.MODE_CBC, IV=self.iv) self.bytechars = [ b'\x01', b'\x02', b'\x03', b'\x04', b'\x05', b'\x06', b'\x07', b'\x08', b'\x09' ]
def getsecret(label: str) -> str: import secretstorage con = secretstorage.dbus_init() col = secretstorage.get_default_collection(con) secret = None for item in col.get_all_items(): if item.get_label() == label: return item.get_secret().decode()
def is_unlocked(self): try: collection = secretstorage.get_default_collection(self.connection) if collection.is_locked(): # Prompt for unlock collection.unlock() return not collection.is_locked() # In case of denial except secretstorage.exceptions.SecretServiceNotAvailableException: logger.debug('SecretStorage is closed.') return False
def del_pass(self): if not self.bus: return collection = secretstorage.get_default_collection(self.bus) if collection.is_locked(): collection.unlock() x=collection.search_items(self.collection).next() x.delete()
def linux_safe_storage(self): bus = secretstorage.dbus_init() collection = secretstorage.get_default_collection(bus) for item in collection.get_all_items(): if item.get_label() == 'Chromium Safe Storage': self.MY_PASS = item.get_secret() break else: raise Exception('Chromium password not found!')
def del_pass(self): if not self.bus: return collection = secretstorage.get_default_collection(self.bus) if collection.is_locked(): collection.unlock() x = collection.search_items(self.collection).next() x.delete()
def set_password(self, service, repo_url, password): asyncio.set_event_loop(asyncio.new_event_loop()) collection = secretstorage.get_default_collection(self.connection) attributes = { 'application': 'Vorta', 'service': service, 'repo_url': repo_url, 'xdg:schema': 'org.freedesktop.Secret.Generic' } collection.create_item(repo_url, attributes, password, replace=True)
def set_client_secret(token: bytes): conn = secretstorage.dbus_init() coll = secretstorage.get_default_collection(conn) if coll.is_locked(): coll.unlock() coll.create_item(SS_CLIENT_SECRET_LABEL, SS_CLIENT_SECRET_ATTRIBUTE, token, replace=True)
def store_pass(self, password): if not self.bus: return try: collection = secretstorage.get_default_collection(self.bus) if collection.is_locked(): collection.unlock() collection.create_item('pupy_credentials', self.collection, password) except Exception as e: logging.warning("Error with GnomeKeyring store_pass : %s"%e)
def get_default_collection(self): bus = secretstorage.dbus_init() try: 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 InitError("Failed to unlock the collection!") return collection
def _get_accounts(self): conn = secretstorage.dbus_init() sec_coll = secretstorage.get_default_collection(conn) for filepath in self._get_sources_files_list(): account = EvolutionAccount(filepath) if account.has_authentication: account.get_password(sec_coll) self._accounts.append(account) conn.close()
def get_default_collection(self): import secretstorage bus = secretstorage.dbus_init() if hasattr(secretstorage, "get_default_collection"): collection = secretstorage.get_default_collection(bus) else: collection = secretstorage.Collection(bus) if collection.is_locked(): if collection.unlock(): raise InitError("Failed to unlock the collection!") return collection
def get_linux_pass(os_crypt_name): """Retrive password used to encrypt cookies from libsecret. """ # https://github.com/n8henrie/pycookiecheat/issues/12 my_pass = None import secretstorage connection = secretstorage.dbus_init() collection = secretstorage.get_default_collection(connection) secret = None # we should not look for secret with label. Sometimes label can be different. For example, # if Steam is installed before Chromium, Opera or Edge, it will show Steam Secret Storage as label. # insted we should look with schema and application secret = next( collection.search_items({ 'xdg:schema': 'chrome_libsecret_os_crypt_password_v2', 'application': os_crypt_name }), None) if not secret: # trying os_crypt_v1 secret = next( collection.search_items({ 'xdg:schema': 'chrome_libsecret_os_crypt_password_v1', 'application': os_crypt_name }), None) if secret: my_pass = secret.get_secret() connection.close() # Try to get pass from keyring, which should support KDE / KWallet if not my_pass: try: import keyring.backends.kwallet keyring.set_keyring(keyring.backends.kwallet.DBusKeyring()) my_pass = keyring.get_password( "{} Keys".format(os_crypt_name.capitalize()), "{} Safe Storage".format( os_crypt_name.capitalize())).encode('utf-8') # it may raise `dbus.exceptions.DBusException` `eyring.errors.InitError` # on Gnome environment, all of them extended from `Exception` except Exception: pass # try default peanuts password, probably won't work if not my_pass: my_pass = '******'.encode('utf-8') return my_pass
def delete_access_token(): conn = secretstorage.dbus_init() coll = secretstorage.get_default_collection(conn) searched = coll.search_items(SS_TOKEN_ATTRIBUTE) try: item = next(searched) except StopIteration: return None else: item.delete() return True
def delete_client_id(): conn = secretstorage.dbus_init() coll = secretstorage.get_default_collection(conn) searched = coll.search_items(SS_CLIENT_ID_ATTRIBUTE) try: item = next(searched) except StopIteration: return None else: item.delete() return True
def get_client_secret(): conn = secretstorage.dbus_init() coll = secretstorage.get_default_collection(conn) searched = coll.search_items(SS_CLIENT_SECRET_ATTRIBUTE) try: item = next(searched) except StopIteration: return None else: if item.is_locked(): item.unlock() return item.get_secret()
def get_cookies(self): salt = b'saltysalt' length = 16 if sys.platform == 'darwin': # running Chrome on OSX my_pass = keyring.get_password('Chrome Safe Storage', 'Chrome') my_pass = my_pass.encode('utf8') iterations = 1003 key = PBKDF2(my_pass, salt, length, iterations) elif sys.platform.startswith('linux'): # running Chrome on Linux bus = secretstorage.dbus_init() collection = secretstorage.get_default_collection(bus) for item in collection.get_all_items(): if item.get_label() == 'Chrome Safe Storage': my_pass = item.get_secret() break else: raise Exception('Chrome password not found!') print('pass: '******'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) con.row_factory = sqlite3.Row cur = con.cursor() cur.execute('SELECT value FROM meta WHERE key = "version";') version = int(cur.fetchone()[0]) query = 'SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value FROM cookies;' if version < 10: query = query.replace('is_', '') cur.execute(query) for item in cur.fetchall(): host, path, secure, expires, name = item[:5] value = self._decrypt(item[5], item[6], key=key) # if item[0] == '.instagram.com': # print ('domain: ' + item[0] + ' name: ' + name + ' value: ' + value) yield create_cookie(host, path, secure, expires, name, value) con.close()
def get_password(self, service, repo_url): if self.is_unlocked: asyncio.set_event_loop(asyncio.new_event_loop()) collection = secretstorage.get_default_collection(self.connection) attributes = { 'application': 'Vorta', 'service': service, 'repo_url': repo_url } items = list(collection.search_items(attributes)) logger.debug('Found %i passwords matching repo URL.', len(items)) if len(items) > 0: return items[0].get_secret().decode("utf-8") return None
def _read_credentials() -> Credentials: """Read credentials from Freedesktop.org SecretService standard.""" with closing(secretstorage.dbus_init()) as conn: collection = secretstorage.get_default_collection(conn) items = collection.search_items({'uri': 'https://secure.lemonde.fr'}) try: item = next(items) except StopIteration: LOGGER.debug('Credentials not found!') raise CredentialsNotFound attributes = item.get_attributes() mail = attributes['username'] LOGGER.debug(f'Will use credentials for {mail}') return Credentials(mail, item.get_secret().decode('utf-8'))
def getChromeSecret(): """Get Chrome Secret This function returns secret from Gnome Keyring used to encrypt/decrypt cookies stored in Google-Chrome """ bus = secretstorage.dbus_init() collection = secretstorage.get_default_collection(bus) MY_PASS = "" for item in collection.get_all_items(): if item.get_label() == 'Chrome Safe Storage': MY_PASS = item.get_secret() break else: raise Exception('Chrome password not found!') return MY_PASS
def __init__(self): my_pass = '******'.encode('utf8') bus = secretstorage.dbus_init() collection = secretstorage.get_default_collection(bus) for item in collection.get_all_items(): if item.get_label() == 'Chrome Safe Storage': my_pass = item.get_secret() break iterations = 1 salt = b'saltysalt' length = 16 kdf = import_module('Crypto.Protocol.KDF') self.key = kdf.PBKDF2(my_pass, salt, length, iterations) self.dbpath = f"/home/{getuser()}/.config/google-chrome/Default/"
def get_pass(self): if not self.bus: return try: collection = secretstorage.get_default_collection(self.bus) if collection.is_locked(): collection.unlock() # will open a gnome-keyring popup x=collection.search_items(self.collection).next() return x.get_secret() except StopIteration: pass except Exception as e: logging.warning("Error with GnomeKeyring get_pass : %s"%e)
def __setitem__(self, key: str, secret: str): import secretstorage connection = secretstorage.dbus_init() collection = secretstorage.get_default_collection(connection) self._ensure_unlocked(collection, self.interactive) item = collection.create_item( f"envrun-{key}", { "application": "envrun", "key": key }, secret.encode("utf-8"), )
def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error('secretstorage not available {}'.format(SECRETSTORAGE_UNAVAILABLE_REASON)) return b'' # the Gnome keyring does not seem to organise keys in the same way as KWallet, # using `dbus-monitor` during startup, it can be observed that chromium lists all keys # and presumably searches for its key in the list. It appears that we must do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label() == '{} Safe Storage'.format(browser_keyring_name): return item.get_secret() else: logger.error('failed to read from keyring') return b''
def get_pass(self): if not self.bus: return try: collection = secretstorage.get_default_collection(self.bus) if collection.is_locked(): collection.unlock() # will open a gnome-keyring popup x = collection.search_items(self.collection).next() return x.get_secret() except StopIteration: pass except Exception as e: logger.warning("Error with GnomeKeyring get_pass : %s" % e)
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 InitError("Failed to unlock the collection!") return collection
def set_password(self, service, repo_url, password): try: asyncio.set_event_loop(asyncio.new_event_loop()) collection = secretstorage.get_default_collection(self.connection) attributes = { 'application': 'Vorta', 'service': service, 'repo_url': repo_url, 'xdg:schema': 'org.freedesktop.Secret.Generic' } collection.create_item(repo_url, attributes, password, replace=True) except secretstorage.exceptions.ItemNotFoundException: logger.error("SecretStorage writing failed", exc_info=sys.exc_info())
def main(): ap = argparse.ArgumentParser() ap.add_argument('-u', '--user', action='store', help='The username') ap.add_argument('-s', '--server', action='store', help='The server') ap.add_argument('-p', '--port', action='store', type=int, help='The port number') ap.add_argument('-P', '--proto', '--protocol', action='store', dest='protocol', help='The port number') args = ap.parse_args() params = ('user', 'server', 'port', 'protocol') attributes = {} for p in params: value = getattr(args, p) if value is not None: attributes[p] = str(value) dbus = secretstorage.dbus_init() collection = secretstorage.get_default_collection(dbus) items = list(collection.search_items(attributes)) if not items: print("error: no matching password found", file=sys.stderr) return os.EX_UNAVAILABLE if len(items) > 1: print(f"error: more than one matching entry found: " f"{len(items)} matches", file=sys.stderr) return os.EX_UNAVAILABLE password = items[0].get_secret() sys.stdout.buffer.write(password) sys.stdout.buffer.write(b"\n") return os.EX_OK
def get_password(user=None, server=None, port=None, protocol=None): attributes = {} if user is not None: attributes['user'] = user if server is not None: attributes['server'] = server if port is not None: attributes['port'] = str(port) if protocol is not None: attributes['protocol'] = protocol dbus = secretstorage.dbus_init() collection = secretstorage.get_default_collection(dbus) items = list(collection.search_items(attributes)) if not items: raise NoPasswordError() if len(items) > 1: raise PasswordError( "found multiple password entries matching the criteria" ) secret = items[0].get_secret() return secret.decode('utf-8')
def get_secret_storage(): bus = secretstorage.dbus_init() return secretstorage.get_default_collection(bus)
def test_default_collection(self) -> None: collection = get_default_collection(self.connection) self.assertEqual(collection.get_label(), "Collection One")