def __init__(self): try: self.bus = secretstorage.dbus_init() except: self.bus = None self.collection = {'application': 'pupy'}
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 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 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 __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 __init__(self): try: self.bus = secretstorage.dbus_init() except: self.bus = None self.collection = {'application':'pupy'}
def get_linux_pass(self, cookie_file: str) -> bytes: """ Adapted from https://github.com/n8henrie/pycookiecheat/issues/27 Get the settings for Chrome/Chromium cookies on Linux. Parameter: cookie_file: Path of cookie file Return: pass for decryption """ bus = secretstorage.dbus_init() collection = secretstorage.get_any_collection(bus) ## login keyring # Set the default linux password my_pass = "******".encode('utf-8') browser = '' if 'chrome' in cookie_file: browser = 'Chrome' elif 'chromium' in cookie_file: browser = 'Chromium' else: raise BrowserCookieError( 'Browser cookie type is not supported.' 'See and change the setting in config.ini.') if not collection.is_locked(): label_to_check = f"{browser} Safe Storage" items1 = collection.get_all_items() for item in items1: if item.get_label() == label_to_check: my_pass = item.get_secret() else: raise BrowserCookieError("keyring is locked") return my_pass
def test_closing_context_manager(self) -> None: with closing(dbus_init()) as connection: self.assertTrue(check_service_availability(connection)) collection = get_any_collection(connection) self.assertIsNotNone(collection) label = collection.get_label() self.assertIsNotNone(label)
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 setKeyring(): try: #HACK set keyring backend explicitly if platform.system().startswith("Windows"): import keyring # @Reimport keyring.set_keyring(keyring.backends.Windows.WinVaultKeyring() ) # @UndefinedVariable elif platform.system() == 'Darwin': import keyring # @Reimport keyring.set_keyring(keyring.backends.OS_X.Keyring()) else: # Linux try: import keyring # @Reimport config.logger.debug("controller: keyring.get_keyring() %s", keyring.get_keyring()) # test if secretstorage dbus is working import secretstorage # @Reimport @UnresolvedImport bus = secretstorage.dbus_init() _ = list(secretstorage.get_all_collections(bus)) # if yes, import it import keyring.backends.SecretService # @Reimport ss_keyring = keyring.backends.SecretService.Keyring() if ss_keyring.priority: import keyring # @Reimport # if priority is not 0, we set it as keyring system keyring.set_keyring(ss_keyring) except Exception as e: pass #config.logger.error("controller: Linux keyring Exception %s",e) #config.logger.debug("keyring: %s",str(keyring.get_keyring())) except Exception as e: config.logger.error("controller: keyring Exception %s", e)
def get_linux_config(browser: str) -> dict: """Get the settings for Chrome/Chromium cookies on Linux. Args: browser: Either "Chrome" or "Chromium" Returns: Config dictionary for Chrome/Chromium cookie decryption """ bus = secretstorage.dbus_init() collection = secretstorage.get_any_collection(bus) ## login keyring # Verify supported browser, fail early otherwise if browser.lower() == "chrome": cookie_file = "~/.config/google-chrome/Default/Cookies" elif browser.lower() == "chromium": cookie_file = "~/.config/chromium/Default/Cookies" else: raise ValueError("Browser must be either Chrome or Chromium.") # Set the default linux password config = { "my_pass": "******", "iterations": 1, "cookie_file": cookie_file } if not collection.is_locked(): label_to_check = f"{browser.capitalize()} Safe Storage" items1 = collection.get_all_items() for item in items1: if item.get_label() == label_to_check: config["my_pass"] = item.get_secret() else: print("keyring is locked") exit(1) return config
def setUp(self) -> None: self.connection = dbus_init() self.collection = get_any_collection(self.connection) self.created_timestamp = time.time() self.item = self.collection.create_item('My item', ATTRIBUTES, b'pa$$word') self.other_item = self.collection.create_item('My item', ATTRIBUTES, b'', content_type='data/null')
def setUpClass(cls): cls.bus = dbus_init(main_loop=False) cls.collection = get_any_collection(cls.bus) cls.created_timestamp = time.time() cls.item = cls.collection.create_item('My item', ATTRIBUTES, b'pa$$word') cls.other_item = cls.collection.create_item('My item', ATTRIBUTES, '', content_type='data/null')
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 ready(self): try: # this will throw an exception of all the dependencies didn't get setup correctly import secretstorage bus = secretstorage.dbus_init() list(secretstorage.get_all_collections(bus)) return True except Exception: return False
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 get_gnome_keyrings(): connection = secretstorage.dbus_init() keyrings = {} for collection in secretstorage.get_all_collections(connection): keyring_name = collection.collection_path keyrings[keyring_name] = [ get_item_info(i) for i in list(collection.get_all_items()) ] return keyrings
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 get_secret(item_path: str) -> Optional[str]: "fetch secret from dbus item path" log_secret.debug('Get secret for %s', item_path) try: with closing(dbus_init()) as connection: time.sleep(0.2) # sometimes needed for items to be populated after unlock item = Item(connection, item_path) return item.get_secret() except SecretServiceNotAvailableException: log_secret.error('The dbus secretservice provider is not running any more') return None
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_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_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_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 get_collection(name): connection = secretstorage.dbus_init() collections = secretstorage.get_all_collections(connection) collection = next((collection for collection in collections if collection.get_label() == name), None) if collection == None: print('keyring "%s" not found, creating...' % name) collection = secretstorage.create_collection(connection, name) collection.unlock() return collection
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 priority(cls): with ExceptionRaisedContext() as exc: secretstorage.__name__ if exc: raise RuntimeError("SecretStorage required") if not hasattr(secretstorage, 'get_default_collection'): raise RuntimeError("SecretStorage 1.0 or newer required") try: bus = secretstorage.dbus_init() list(secretstorage.get_all_collections(bus)) except exceptions.SecretStorageException as e: raise RuntimeError("Unable to initialize SecretService: %s" % e) return 5
def priority(cls): with ExceptionRaisedContext() as exc: secretstorage.__name__ if exc: raise RuntimeError("SecretStorage required") if secretstorage.__version_tuple__[0] < 3: raise RuntimeError("SecretStorage 3.0 or newer required") try: with closing(secretstorage.dbus_init()) as connection: list(secretstorage.get_all_collections(connection)) except exceptions.SecretStorageException as e: raise RuntimeError("Unable to initialize SecretService: %s" % e) return 5
def hackng(): bus = secretstorage.dbus_init() for keyring in secretstorage.get_all_collections(bus): for item in keyring.get_all_items(): attr = item.get_attributes() if attr and 'username_value' in attr: print('[%s] %s: %s = %s' % (keyring.get_label(), item.get_label(), attr['username_value'], item.get_secret())) else: print( '[%s] %s = %s' % (keyring.get_label(), item.get_label(), item.get_secret()))
def supported(self): try: import secretstorage except ImportError: return -1 from secretstorage.exceptions import SecretServiceNotAvailableException try: bus = secretstorage.dbus_init() secretstorage.Collection(bus) except (ImportError, SecretServiceNotAvailableException): return -1 else: return 1
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_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 priority(cls): with ExceptionRaisedContext() as exc: secretstorage.__name__ if exc: raise RuntimeError("SecretStorage required") if not hasattr(secretstorage, 'get_default_collection'): raise RuntimeError("SecretStorage 1.0 or newer required") try: bus = secretstorage.dbus_init() list(secretstorage.get_all_collections(bus)) except exceptions.SecretServiceNotAvailableException as e: raise RuntimeError( "Unable to initialize SecretService: %s" % e) return 5
def hackng(): bus = secretstorage.dbus_init() for keyring in secretstorage.get_all_collections(bus): for item in keyring.get_all_items(): attr = item.get_attributes() if attr and 'username_value' in attr: print('[%s] %s: %s = %s' % ( keyring.get_label(), item.get_label(), attr['username_value'], item.get_secret() )) else: print('[%s] %s = %s' % ( keyring.get_label(), item.get_label(), item.get_secret() ))
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 setUpClass(cls): cls.bus = dbus_init(main_loop=False) cls.collection = get_any_collection(cls.bus)
def setUp(self) -> None: self.connection = dbus_init()
def setUp(self) -> None: self.connection = dbus_init() self.collection = get_any_collection(self.connection)
def setUpClass(cls): cls.bus = secretstorage.dbus_init(main_loop=False) cls.collection = secretstorage.get_any_collection(cls.bus)
def setUp(self) -> None: self.connection = dbus_init() collection_path = "/org/freedesktop/secrets/collection/english" self.collection = Collection(self.connection, collection_path)
def setUp(self) -> None: self.connection = secretstorage.dbus_init() self.collection = secretstorage.get_any_collection(self.connection)
def get_secret_storage(): bus = secretstorage.dbus_init() return secretstorage.get_default_collection(bus)
#!/usr/bin/env python3 import secretstorage bus = secretstorage.dbus_init() items = secretstorage.search_items(bus, {'application': 'secretstorage-test'}) for item in items: print('Deleting item with label %r.' % item.get_label()) item.delete()