def keyring_supported(): if keyring is None: logger.debug('No keyring due to import errror.') return False backends = [] try: backends.append(keyring.backends.SecretService.Keyring) except: pass try: backends.append(keyring.backends.Gnome.Keyring) except: pass try: backends.append(keyring.backends.kwallet.Keyring) except: pass try: backends.append(keyring.backend.SecretServiceKeyring) except: pass try: backends.append(keyring.backend.GnomeKeyring) except: pass try: backends.append(keyring.backend.KDEKWallet) except: pass try: displayName = keyring.get_keyring().__module__ except: displayName = str(keyring.get_keyring()) if backends: logger.debug("Found appropriate keyring '{}'".format(displayName)) return isinstance(keyring.get_keyring(), tuple(backends)) logger.debug("No appropriate keyring found. '{}' can't be used with BackInTime".format(displayName)) return False
def _init_keyring(): if keyring is None: return global _keyring_backend if _keyring_backend is not None: return _keyring_backend backends = [keyring.get_keyring()] try: backends = backends[0].backends except AttributeError: pass for i, backend in enumerate(backends): # Substitute our own KeePass compatible keyring if isinstance(backend, keyring.backends.SecretService.Keyring): backends[i] = KeePassKeyring() backend = backends if isinstance(backend, ( keyring.backends.kwallet.DBusKeyring, keyring.backends.SecretService.Keyring, )): backend.appid = 'Hopic' if isinstance(backend, keyring.backends.OS_X.Keyring): backends[i] = OSXKeyring() backend = backends if len(backends) == 1: _keyring_backend = backends[0] else: _keyring_backend = keyring.get_keyring() return _keyring_backend
def get_secret(self): """Fetches a secret from the user's keystore or keyboard. Caches the result to the keystore, if possible.""" import_keyring() if keyring is not None: secret = keyring.get_keyring().get_password( self.name, self.KEYRING_USERNAME) if secret is not None: return secret # Pop open Chrome for them if self.location is not None: try: webbrowser.open(self.location) except: # pylint: disable=bare-except # TODO this can't be a good idea pass # Fetch and cache secret = (getpass.getpass( prompt="Enter secret for '%s' from\n%s\nPassword: " % (self.name, self.location)) or None) if secret is not None and keyring is not None: keyring.get_keyring().set_password(self.name, self.KEYRING_USERNAME, secret) return secret
def check_keyring_support(): """ Check if the UserNamePassword class can be used, else raise ImportError with an explanatory error message. """ global keyring # if gnomekeyring exists, block kde libraries old_pykde4 = sys.modules.get('PyKDE4') try: import gnomekeyring except ImportError: pass else: sys.modules['PyKDE4'] = None try: import keyring except ImportError: global UserNamePassword class UserNamePassword (object): pass raise else: # Configure the fallback keyring's configuration file if used import keyring.backend kr = keyring.get_keyring() if hasattr(kr, "crypted_password"): keyring.set_keyring(keyring.backend.UncryptedFileKeyring()) kr = keyring.get_keyring() if hasattr(kr, "file_path"): kr.file_path = config.save_config_file("keyring.cfg") finally: # now unblock kde libraries again if old_pykde4: sys.modules['PyKDE4'] = old_pykde4
def __init__(self): self.builder = Gtk.Builder() self.builder.add_from_file("/opt/globalprotect-indicator/settings.xml") self.window = self.builder.get_object("MainWindow") self.window.set_icon_from_file( "/opt/globalprotect-indicator/gp_on.png") self.builder.connect_signals(self) self.host = self.builder.get_object("entry_host") self.username = self.builder.get_object("entry_username") self.password = self.builder.get_object("entry_password") keyring.get_keyring() host = keyring.get_password("gp", "host") username = keyring.get_password("gp", "username") password = keyring.get_password("gp", "password") if not password: password = '' if not username: username = '' if not host: host = '' self.host.set_text(host) self.username.set_text(username) self.password.set_text(password) self.window.show_all() self.window.show()
def KeyringAvailable(self): """ determine if keyring module and an implementation is available for secure password storage """ try: # Linux systems should use keyring only if it comes with the distro, otherwise chances are small # that keyring works at all if not platform.system() in NON_LINUX: # keyring and secretstorage have to be importable import keyring, secretstorage if ("SecretService") in dir(keyring.backends) and not (keyring.get_keyring() is None): return True else: # safety first - if not yet available disable it # if not self.__dict__.has_key("use_system_keyring"): if not 'use_system_keyring' in self.__dict__.keys(): self.use_system_keyring = False # only import keyring lib if configured to do so # necessary to avoid Windows crashes like https://github.com/HenriWahl/Nagstamon/issues/97 if self.use_system_keyring == True: # hint for packaging: nagstamon.spec always have to match module path # keyring has to be bound to object to be used later import keyring return not (keyring.get_keyring() is None) else: return False except: import traceback traceback.print_exc(file=sys.stdout) return False
def KeyringAvailable(self): """ determine if keyring module and an implementation is available for secure password storage """ try: # Linux systems should use keyring only if it comes with the distro, otherwise chances are small # that keyring works at all if platform.system() in NON_LINUX: # safety first - if not yet available disable it if 'use_system_keyring' not in self.__dict__.keys(): self.use_system_keyring = False # only import keyring lib if configured to do so # necessary to avoid Windows crashes like https://github.com/HenriWahl/Nagstamon/issues/97 if self.use_system_keyring is True: # hint for packaging: nagstamon.spec always have to match module path # keyring has to be bound to object to be used later import keyring return not (keyring.get_keyring() is None) else: return False else: # keyring and secretstorage have to be importable import Nagstamon.thirdparty.keyring as keyring # import secretstorage module as dependency of keyring - # if not available keyring won't work import secretstorage if ("SecretService") in dir(keyring.backends) and not (keyring.get_keyring() is None): return True except Exception: import traceback traceback.print_exc(file=sys.stdout) return False
def connect_thread(self, obj=None): keyring.get_keyring() host = keyring.get_password("gp", "host") username = keyring.get_password("gp", "username") password = keyring.get_password("gp", "password") if not password: password = '' if not username: username = '******' self.proc = subprocess.Popen([ 'pkexec', 'openconnect', '-u', username, '--protocol=gp', host, '--passwd-on-stdin' ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.proc.stdin.write(password.encode('utf-8')) self.proc.stdin.write(b'\n') self.proc.stdin.flush() for line in iter(self.proc.stdout.readline, ''): s = line.decode('utf-8') if 'connected' in s and 'mainloop' in s: self.connected = True self.indicator.set_menu(self.create_menu()) if 'error' in s: self.proc.kill() if line == b'': self.disconnect() break
def get_secret(self): """Fetches a secret from the user's keystore or keyboard. Caches the result to the keystore, if possible.""" keyring = import_keyring() if keyring is not None: secret = keyring.get_keyring().get_password( self.name, self.KEYRING_USERNAME) if secret is not None: return secret # Pop open Chrome for them if self.location is not None: import webbrowser try: webbrowser.open(self.location) except: pass # Fetch and cache import getpass secret = getpass.getpass( prompt="Enter secret for '%s' from\n%s\nPassword: " % (self.name, self.location)) or None if secret is not None and keyring is not None: keyring.get_keyring().set_password(self.name, self.KEYRING_USERNAME, secret) return secret
def user_password(self): """Wrap getpass to simplify testing.""" password = None if self.config.password_cache: self.log.debug("Password cache enabled") try: keyring.get_keyring() password = keyring.get_password( "aws_okta_keyman", self.config.username, ) except keyring.errors.InitError: msg = "Password cache enabled but no keyring available." self.log.warning(msg) password = getpass.getpass() if self.config.password_reset or password is None: self.log.debug("Password not in cache or reset requested") password = getpass.getpass() keyring.set_password( "aws_okta_keyman", self.config.username, password, ) else: password = getpass.getpass() return password
def keyring_backend(): """Temporary set in-memory keyring as current backend.""" prev_backend = keyring.get_keyring() keyring.set_keyring(_InmemoryKeyring()) yield keyring.get_keyring() keyring.set_keyring(prev_backend)
def _get_sudo_password(self): """ Ask and test a sudo password, and save it. Raise KeyboardInterrupt if the user cancel :return: The sudo password :rtype: str """ try: import keyring use_keyring = True except StandardError: use_keyring = False if self._sudo_password is not None: return self._sudo_password # Check for empty password if self._check_sudo_pwd(None, True): # No need for password self._sudo_password = "" return self._sudo_password tested = set([]) # Try using system keyring if available if use_keyring: keyring.get_keyring() sudo_pwd = keyring.get_password(self._params.domain, self._params.login) if sudo_pwd != None and self._check_sudo_pwd(sudo_pwd): self._sudo_password = sudo_pwd keyring.set_password(self._params.domain, self._params.login, sudo_pwd) return sudo_pwd tested.add(sudo_pwd) # Ask the user until it's good or the user cancel while True: full_login = self._params.login + "@" + self._params.domain try: full_login_str = full_login.encode("utf-8") sudo_pwd = getpass.getpass("[sudo] password for " + full_login_str + ": ").strip() except EOFError: raise KeyboardInterrupt() if not sudo_pwd or sudo_pwd in tested: sys.stderr.write( os.linesep + "This password has already been tested, please retry." + os.linesep) sys.stderr.flush() continue if self._check_sudo_pwd(sudo_pwd): self._sudo_password = sudo_pwd if use_keyring: keyring.set_password(self._params.domain, self._params.login, sudo_pwd) return sudo_pwd tested.add(sudo_pwd)
def _configure_keyring(cls): # Configure the fallback keyring's configuration file if used import keyring.backend kr = keyring.get_keyring() if hasattr(kr, "crypted_password"): keyring.set_keyring(keyring.backend.UncryptedFileKeyring()) kr = keyring.get_keyring() if hasattr(kr, "file_path"): kr.file_path = config.save_config_file("keyring.cfg")
def on_btn_save_clicked(self, data=None): self.host = self.builder.get_object("entry_host").get_text() self.username = self.builder.get_object("entry_username").get_text() self.password = self.builder.get_object("entry_password").get_text() keyring.get_keyring() keyring.set_password("gp", "host", self.host) keyring.set_password("gp", "username", self.username) keyring.set_password("gp", "password", self.password) self.window.hide()
def _keyring(): # If there's an existing keyring, let's use it! if (config.has_option('authorization', 'ldap_username') and config.get('authorization', 'ldap_username') != '' and config.has_option('authorization', 'keyring') and config.get('authorization', 'keyring') != '' and KEYRING_PRESENT): # use keyring auth = [ config.get('authorization', 'ldap_username'), keyring.get_password( config.get('authorization', 'keyring'), config.get('authorization', 'ldap_username') ) ] if auth[1] is None: keyring.get_keyring() print("Can't retrieve ldap password from keyring '{0}'" .format(config.get('authorization', 'keyring'))) auth[1] = getpass.getpass( 'ldap username: {0}\npassword: '******'authorization', 'ldap_username')) ) keyring.set_password( config.get('authorization', 'keyring'), config.get('authorization', 'ldap_username'), auth[1] ) print("Saved password to keyring") return tuple(auth) # If there's no existing keyring and we have keyring support # let's try to be nice and create a keyring. else: # configure credentials auth = ( raw_input('ldap username: '******'password: '******'authorization', 'ldap_username', auth[0]) if (not config.has_option('authorization', 'keyring') or config.get('authorization', 'keyring') == ''): config.set('authorization', 'keyring', 'invtool-ldap') try: config.write(open(HOME_CONFIG_FILE, 'w')) print("Wrote new configuration to {0}".format(HOME_CONFIG_FILE)) except OSError: print("could not write keyring configuration to {0}".format( HOME_CONFIG_FILE )) # store the password keyring.set_password(config.get('authorization', 'keyring'), *auth) print("Saved password to keyring") return auth
def connect(self, obj=None): keyring.get_keyring() host = keyring.get_password("gp", "host") username = keyring.get_password("gp", "username") password = keyring.get_password("gp", "password") if not host or not username or not password: self.show_settings() return t = threading.Thread(target=self.connect_thread) t.start()
def process_args(self): if self.args.user is None: raise ValueError('Please use --user') if self.args.key_file: with open(self.args.key_file) as fh: self.password = fh.read().strip() elif self.args.key_ring: import keyring keyring.get_keyring() self.password = keyring.get_password(URL, self.args.user) else: raise ValueError('Password not specified')
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 __init__(self, service): self._service = service self._keyring = keyring.get_keyring() self._save_policy = self._keyring.get_password(service, self._SAVE_POLICY_KEY) LOG.info("Viable keyring backends: {b}".format(b=" ".join([qualname(o) for o in keyring.backend.get_all_keyring()]))) LOG.info("Hint: You may set up '{r}/keyringrc.cfg' to force a backend.".format(r=keyring_data_root())) LOG.info("Hint: See 'keyringrc.cfg' in the package's docs 'examples' directory for a sample file.")
def keyring_get_password(username): if keyring is None: raise CMDLineExit("You requested to use the 'keyring' module " "as password provider, but do not have this " "installed.") keyring_impl = keyring.get_keyring() # For older 'keyring' module (<8.0) implementation where undesirable # implementations were still permissable. And, for newer ones (>=8.0), # where the 'fail' module is used to denote no available keyrings. undesirable = [ 'keyring.backends.file.PlaintextKeyring', # < 8.0 'keyring.backends.file.EncryptedKeyring', # < 8.0 'keyrings.alt.file.EncryptedKeyring', # >= 8.0 'keyring.backends.fail.Keyring', # >= 8.0 ] # TODO: there has got to be a better way description = '.'.join( (keyring_impl.__class__.__module__, keyring_impl.__class__.__name__)) debug("Description of the backend is: '{0}'".format(description)) if description in undesirable: msg = ("Aborting: Did not find a usable backend to access your " "keyring.\n\n" "Maybe 'pip install keyrings.alt' will fix your problem.") raise CMDLineExit(msg) debug("Note: will use the backend: '{0}'".format(keyring_impl)) password = keyring.get_password('afp', username) if not password: info("No password found in keychain, please enter it now to store it.") password = prompt_get_password(username) keyring.set_password('afp', username, password) return password
def test_keyring(): """Verify test keyring backend is selected and working""" assert isinstance(keyring.get_keyring(), KrTestBackEnd) system, user, pw = "krtest", "kruser", "krpw" keyring.set_password(system, user, pw) assert keyring.get_password(system, user) == pw keyring.delete_password(system, user)
def __init__(self, service_name, backend_name): self._service_name = service_name keyring_backend = keyring.get_keyring() if backend_name == StrongboxBackend.KEYRING: LOG.info("The keyring backend is used as the secret storage " "for {}".format(service_name)) elif backend_name == StrongboxBackend.VAULT: LOG.info("The vault backend is selected to access the " "secret storage for {}".format(service_name)) vault_url = keyring_backend.get_password(service_name, 'vault_url') if vault_url is None: self._raise_config_error(key='vault_url') vault_token = keyring_backend.get_password(service_name, 'vault_token') if vault_token is None: self._raise_config_error(key='vault_token') keyring_backend = VaultKeyring(vault_url=vault_url, vault_token=vault_token) else: raise ConfigError( "Invalid strongbox backend: '{}', e.g. only 'keyring' " "and 'vault' values are allowed".format(backend_name)) self._keyring_backend = keyring_backend
def keygen(get_keyring=get_keyring): """Generate a public/private key pair.""" warn_signatures() WheelKeys, keyring = get_keyring() ed25519ll = signatures.get_ed25519ll() wk = WheelKeys().load() keypair = ed25519ll.crypto_sign_keypair() vk = native(urlsafe_b64encode(keypair.vk)) sk = native(urlsafe_b64encode(keypair.sk)) kr = keyring.get_keyring() kr.set_password("wheel", vk, sk) print("Created Ed25519 keypair with vk={}".format(vk)) print("in {!r}".format(kr)) sk2 = kr.get_password('wheel', vk) if sk2 != sk: raise WheelError("Keyring is broken. Could not retrieve secret key.") print("Trusting {} to sign and verify all packages.".format(vk)) wk.add_signer('+', vk) wk.trust('+', vk) wk.save()
def sign(wheelfile, replace=False, get_keyring=get_keyring): """Sign a wheel""" WheelKeys, keyring = get_keyring() ed25519ll = signatures.get_ed25519ll() wf = WheelFile(wheelfile, append=True) wk = WheelKeys().load() name = wf.parsed_filename.group('name') sign_with = wk.signers(name)[0] sys.stdout.write("Signing {0} with {1}\n".format(name, sign_with[1])) vk = sign_with[1] kr = keyring.get_keyring() sk = kr.get_password('wheel', vk) keypair = ed25519ll.Keypair(urlsafe_b64decode(binary(vk)), urlsafe_b64decode(binary(sk))) record_name = wf.distinfo_name + '/RECORD' sig_name = wf.distinfo_name + '/RECORD.jws' if sig_name in wf.zipfile.namelist(): raise WheelError("Wheel is already signed.") record_data = wf.zipfile.read(record_name) payload = {"hash":"sha256=" + native(urlsafe_b64encode(hashlib.sha256(record_data).digest()))} sig = signatures.sign(payload, keypair) wf.zipfile.writestr(sig_name, json.dumps(sig, sort_keys=True)) wf.zipfile.close()
def keygen(get_keyring=get_keyring): """Generate a public/private key pair.""" WheelKeys, keyring = get_keyring() ed25519ll = signatures.get_ed25519ll() wk = WheelKeys().load() keypair = ed25519ll.crypto_sign_keypair() vk = native(urlsafe_b64encode(keypair.vk)) sk = native(urlsafe_b64encode(keypair.sk)) kr = keyring.get_keyring() kr.set_password("wheel", vk, sk) sys.stdout.write("Created Ed25519 keypair with vk={0}\n".format(vk)) if isinstance(kr, keyring.backends.file.BaseKeyring): sys.stdout.write("in {0}\n".format(kr.file_path)) else: sys.stdout.write("in %r\n" % kr.__class__) sk2 = kr.get_password('wheel', vk) if sk2 != sk: raise WheelError("Keyring is broken. Could not retrieve secret key.") sys.stdout.write("Trusting {0} to sign and verify all packages.\n".format(vk)) wk.add_signer('+', vk) wk.trust('+', vk) wk.save()
def keyring_backend(): saved_backend = keyring.get_keyring() try: keyring.set_keyring(MockKeyringBackend()) yield finally: keyring.set_keyring(saved_backend)
def init(force, delete, clientsecrets): app_name = 'xoauth2relay' from keyring import get_keyring keyring = get_keyring() from .oauth2 import ClientSecretsStore clientsecrets_store = ClientSecretsStore(keyring) try: client_type, client_info = clientsecrets_store.load( app_name, ) except KeyError: pass else: if not force: logger.warning('clientsecrets already exists; ignoring') return try: with io.open(clientsecrets, 'rb') as fp: clientsecrets = fp.read() json.loads(clientsecrets) except IOError as e: logger.error(e) raise SystemExit(1) clientsecrets_store.save(app_name, clientsecrets) logger.info('clientsecrets saved.') if delete: os.unlink(clientsecrets) logger.info('deleted: %s', clientsecrets)
def test_keyring_unit(): """Small unit test for keyring""" import keyring print(keyring.get_keyring()) base_url = "https://data.exchange.se.com/" keyring.set_password(base_url, 'apikey', 'blah') assert keyring.get_password(base_url, 'apikey') == 'blah'
def interactive_login(): token = interactive_get_token() kr = get_keyring() kr.set_password('binstar-token', getpass.getuser(), token) print 'login successful'
def __init__(self): self.aws_profiles = self.load_aws_profiles( os.path.expanduser("~/.aws/credentials")) self.aws_session = None self.keyring = keyring.get_keyring() self.session_name = None
def main(): if '--debug' in sys.argv: print("using keyring", str(keyring.get_keyring())) print("github_token", keyring.get_password("vaultauth", "GITHUB_TOKEN")) if '--reset' in sys.argv: github_token = getpass.getpass('Github Token: ') keyring.set_password("vaultauth", "GITHUB_TOKEN", github_token) xargs = { 'verify': os.getenv('VAULT_CACERT', None), 'url': os.getenv('VAULT_ADDR', 'http://127.0.0.1:8200'), 'token': os.getenv('VAULT_TOKEN', None) } github_token = keyring.get_password("vaultauth", "GITHUB_TOKEN") if not github_token: print('Found no github token in your keyring.') github_token = getpass.getpass('Github Token: ') keyring.set_password("vaultauth", "GITHUB_TOKEN", github_token) client = hvac.Client(**xargs) try: res = client.auth_github(github_token) token = res['auth']['client_token'] print(token) except Exception as ex: print('Authentication failed.', file=sys.stderr) print(ex, file=sys.stderr) sys.exit(1)
def unlocked(self): """ Is the store unlocked so that I can decrypt the content? """ if self.password is not None: return bool(self.password) else: password_storage = self.config["password_storage"] KEYRING_AVAILABLE = False if password_storage == "keyring": try: import keyring if not isinstance(keyring.get_keyring(), keyring.backends.fail.Keyring): KEYRING_AVAILABLE = True else: KEYRING_AVAILABLE = False except ImportError: KEYRING_AVAILABLE = False if ("UNLOCK" in os.environ and os.environ["UNLOCK"] and self.config_key in self.config and self.config[self.config_key] and password_storage == "environment"): log.debug("Trying to use environmental " "variable to unlock wallet") self.unlock(os.environ.get("UNLOCK")) return bool(self.password) elif (password_storage == "keyring" and KEYRING_AVAILABLE and self.config_key in self.config and self.config[self.config_key]): log.debug("Trying to use keyring to unlock wallet") pwd = keyring.get_password("beem", "wallet") self.unlock(pwd) return bool(self.password) return False
def keyring_get_password(username): if keyring is None: raise CMDLineExit("You requested to use the 'keyring' module " "as password provider, but do not have this " "installed.") keyring_impl = keyring.get_keyring() # For older 'keyring' module (<8.0) implementation where undesirable # implementations were still permissable. And, for newer ones (>=8.0), # where the 'fail' module is used to denote no available keyrings. undesirable = ['keyring.backends.file.PlaintextKeyring', # < 8.0 'keyring.backends.file.EncryptedKeyring', # < 8.0 'keyrings.alt.file.EncryptedKeyring', # >= 8.0 'keyring.backends.fail.Keyring', # >= 8.0 ] # TODO: there has got to be a better way description = '.'.join((keyring_impl.__class__.__module__, keyring_impl.__class__.__name__)) debug("Description of the backend is: '{0}'".format(description)) if description in undesirable: raise CMDLineExit( "Aborting: the 'keyring' module has selected the " "undesirable backed: '%s'." % description) debug("Note: will use the backend: '{0}'".format(keyring_impl)) password = keyring.get_password('afp', username) if not password: info("No password found in keychain, please enter it now to store it.") password = prompt_get_password(username) keyring.set_password('afp', username, password) return password
def main(): parser = argparse.ArgumentParser(description='Format todos from todoist.') parser.add_argument('--output', help='Specify the was region.', default='~/.org/todoist.org') args = parser.parse_args() api_key = keyring.get_keyring().get_password('system', 'todoist') api = todoist.TodoistAPI(api_key) api.sync() projects = {p['id']: p['name'] for p in api.projects.all()} tasks = defaultdict(list) for item in api.items.all(): tasks[projects[item['project_id']]].append(item) with open(path.expanduser(args.output), 'w') as fp: fp.write("#+TITLE: Todoist\n#+SETUPFILE: common.org\n") for project_name in tasks: fp.write(f"* {project_name}\n") for task in tasks[project_name]: state = 'TODO' if task['checked']: state = 'DONE' entry = f"""** {state} {task['content']} :PROPERTIES: :URL: https://todoist.com/showTask?id={task['id']}&sync_id={task['id']} :ID: {task['id']} :ADDED: {task['date_added']} :END: """ fp.write(entry)
def main(): print('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') print(keyring.get_keyring()) print('ssssssssassssssssssssssssssssssss') keyring.set_password("https://upload.pypi.org/legacy", "username", getpass.getpass()) print(keyring.get_password("https://upload.pypi.org/legacy", "username"))
def _check(self) -> None: try: import keyring except Exception as e: logger.debug( "An error occurred while importing keyring: {}".format(str(e))) self._is_available = False return backend = keyring.get_keyring() name = backend.name.split(" ")[0] if name == "fail": logger.debug("No suitable keyring backend found") self._is_available = False elif "plaintext" in backend.name.lower(): logger.debug( "Only a plaintext keyring backend is available. Not using it.") self._is_available = False elif name == "chainer": try: import keyring.backend backends = keyring.backend.get_all_keyring() self._is_available = any( b.name.split(" ")[0] not in ["chainer", "fail"] and "plaintext" not in b.name.lower() for b in backends) except Exception: self._is_available = False if not self._is_available: logger.warning("No suitable keyring backends were found")
def main(args=None): args = sys.argv[1:] docopt_kwargs = dict( version=str(__version__), options_first=False, argv=args, ) arguments = docopt.docopt(USAGE, **docopt_kwargs) the_keyring = keyring.get_keyring() collection = the_keyring.get_preferred_collection() collection = list(collection.search_items("")) collection = sorted(collection, key=lambda c: c.get_label()) if arguments['--skiplog']: skiplog = open(arguments['--skiplog'], "a+") labels = skiplog.read().split("\n") skiplog.close() collection = filter(lambda c: c.get_label() not in labels, collection) collection = list(collection) if arguments['import']: prefix = arguments['--prefix'] convert( collection, prefix=prefix, overwrite=arguments['--overwrite'], ask=not arguments['--do-not-ask'], log=arguments['--log'], ) elif arguments['list']: print("Passwords to convert: {}".format(len(collection))) print("") print("\n".join([c.get_label() for c in collection]))
def get_keyring(): try: from ..signatures import keys import keyring assert keyring.get_keyring().priority except (ImportError, AssertionError): raise WheelError("Install wheel[signatures] (requires keyring, keyrings.alt, pyxdg) for signatures.") return keys.WheelKeys, keyring
def has_keyring(): """ Returns whether we have an useful keyring to use. :rtype: bool """ kr = keyring.get_keyring() return kr is not None and kr.__class__ not in OBSOLETE_KEYRINGS
def main(args): bs = get_binstar() auth = bs.authentication() bs.remove_authentication(auth['id']) kr = get_keyring() kr.delete_password('binstar-token', getpass.getuser()) log.info("logout successful")
def get_binstar(): from binstar_client import Binstar kr = get_keyring() token = kr.get_password('binstar-token', getpass.getuser()) url = get_config().get('url', 'https://api.binstar.org') return Binstar(token, domain=url,)
def get_auth_url(self, level): logger.info('using %s', keyring.get_keyring().__module__) client_id = key_store.get('picasa', 'client_id') self.session = OAuth2Session( client_id, scope=self.scope[level], redirect_uri='urn:ietf:wg:oauth:2.0:oob') return self.session.authorization_url( 'https://accounts.google.com/o/oauth2/v2/auth')[0]
def main(args): config = get_config() kr = get_keyring() token = kr.get_password('binstar-token', getpass.getuser()) url = config.get('url', 'https://api.binstar.org') bs = Binstar(token, domain=url) bs.remove_authentication(token) kr.delete_password('binstar-token', getpass.getuser())
def keyring_get_password(username): keyring_impl = keyring.get_keyring() verbose("Note: will use the backend: '{0}'".format(keyring_impl)) password = keyring.get_password('cbas', username) if not password: info("No password found in keychain, please enter it now to store it.") password = prompt_get_password(username) keyring.set_password('cbas', username, password) return password
def get_auth_url(self, level): logger.info('using %s', keyring.get_keyring().__module__) api_key = key_store.get('flickr', 'api_key') api_secret = key_store.get('flickr', 'api_secret') token = flickrapi.auth.FlickrAccessToken('', '', self.perms[level]) self.api = flickrapi.FlickrAPI( api_key, api_secret, token=token, store_token=False) self.api.get_request_token(oauth_callback='oob') return self.api.auth_url(perms=self.perms[level])
def login(ctx): """Set or change Vault login credentials in your keyring.""" if not keyring: raise UsageError("'keyring' support is not available, please read" " 'https://config-sesame.readthedocs.io/en/latest/deploy.html'!", ctx=ctx) url, user, token, _ = vault.default_credentials() if not url: raise UsageError("You MUST provide a VAULT_ADDR!", ctx=ctx) if token: click.secho("WARN: You have a VAULT_TOKEN variable in your environment," " which will override any keyring credentials!", fg='yellow', bg='black', bold=True, reverse=True) click.echo("Please enter credentials for storing in {}.{}..." .format(keyring.get_keyring().__class__.__module__, keyring.get_keyring().__class__.__name__)) access = security.Credentials(url) user, token = access.auth_pair(force_console=True) # Prompt for new password keyring.set_password(url, user, token) click.echo("Updated {}'s password (token) for {}".format(user, url))
def __init__(self, prefs, encrypt, decrypt, mac, macsize): self.prefs = prefs self.__encrypt = encrypt self.__decrypt = decrypt self.__mac = mac self.macsize = macsize self.used_keyring = False self.using_kwallet = 'kwallet' in str(keyring.get_keyring()).lower() self.ignore_keyring = False self.init()
def setUp(self): self.test_dir = tempfile.mkdtemp() self.path = os.path.join(self.test_dir, "conf1.json") self.config = ConfigFile(self.path) self.site = DummySite(self.config) self.engine = DummyEngine(self.site) self._initial_keyring = keyring.get_keyring() self.keyring = TestKeyring() keyring.set_keyring(self.keyring) self.credentials_manager = AWSCredentialsManager(self.engine)
def main(args): config = get_config() kr = get_keyring() token = kr.get_password('binstar-token', getpass.getuser()) url = config.get('url', 'https://api.binstar.org') bs = Binstar(token, domain=url,) username = raw_input('Username: '******'Binstar-Cli', url, ['packages']) kr.set_password('binstar-token', getpass.getuser(), token) print 'login successful'
def login(s): keys = keyring.get_keyring() password = keys.get_password("pythonanywhere", teacher_username) url = "https://www.pythonanywhere.com/login/" header = {"Referer": url} s.get(url) csrftoken = s.cookies['csrftoken'] payload = {"username": teacher_username, "password": password, "csrfmiddlewaretoken": csrftoken } r = s.post(url, data=payload, headers=header)
def has_keyring(): """ Returns whether we have an useful keyring to use. :rtype: bool """ kr = keyring.get_keyring() klass = kr.__class__ logger.debug("Selected keyring: %s" % (klass,)) canuse = kr is not None and klass not in OBSOLETE_KEYRINGS if not canuse: logger.debug("Not using this keyring since it is obsolete") return canuse
def run(self, terms, **kwargs): if not HAS_KEYRING: raise AnsibleError(u"Can't LOOKUP(keyring): missing required python library 'keyring'") display.vvvv(u"keyring: %s" % keyring.get_keyring()) ret = [] for term in terms: (servicename, username) = (term.split()[0], term.split()[1]) display.vvvv(u"username: %s, servicename: %s " % (username, servicename)) password = keyring.get_password(servicename, username) if password is None: raise AnsibleError(u"servicename: %s for user %s not found" % (servicename, username)) ret.append(password.rstrip()) return ret
def __import_old_keyring(): import keyring import keyring.backend # don't use keyring backends that require console input or just do # more or less the same thing we're already doing keyring.backend._all_keyring = [keyring.backend.OSXKeychain(), keyring.backend.GnomeKeyring(), keyring.backend.KDEKWallet(), keyring.backend.Win32CryptoKeyring(), keyring.backend.Win32CryptoRegistry(), keyring.backend.WinVaultKeyring()] keyring.core.init_backend() if keyring.get_keyring().supported() < 0: keyring = None return keyring
def __init__(self, database, cache_dir='cache'): # Fix the keyring # TODO this is unsafe but makes the tests pass if keyring.get_keyring().__class__.__name__ == "EncryptedKeyring": for new_keyring in keyring.backend.get_all_keyring(): if new_keyring.__class__.__name__ == "PlaintextKeyring": keyring.set_keyring(new_keyring) self.database = database self.input_handler = None self.entered_inputs = {} # Keeps track of all entered inputs self.cookie_jar = LWPCookieJar() self.cache_dir = cache_dir self.persistent_storage = {} self._logger = logging.getLogger(self.__class__.__name__) self.load_storage()
def get_password(environment, username): default_keyring = keyring.get_keyring() password = default_keyring.get_password("pycontrolshed.%s" % environment, username) if not(password): print "No password found for %s@%s" % (username, environment) pass1 = getpass.getpass("Please enter the password for %s@%s: " % (username, environment)) pass2 = getpass.getpass("Please confirm the password for %s@%s: " % (username, environment)) if pass1 == pass2: default_keyring.set_password('pycontrolshed.%s' % environment, username, pass1) password = pass1 else: raise Exception("passwords don't match") return password
def run(args): """Handle keyring script.""" parser = argparse.ArgumentParser( description=("Modify Home Assistant secrets in the default keyring. " "Use the secrets in configuration files with: " "!secret <name>")) parser.add_argument( '--script', choices=['keyring']) parser.add_argument( 'action', choices=['get', 'set', 'del', 'info'], help="Get, set or delete a secret") parser.add_argument( 'name', help="Name of the secret", nargs='?', default=None) import keyring from keyring.util import platform_ as platform args = parser.parse_args(args) if args.action == 'info': keyr = keyring.get_keyring() print('Keyring version {}\n'.format(keyring.__version__)) print('Active keyring : {}'.format(keyr.__module__)) config_name = os.path.join(platform.config_root(), 'keyringrc.cfg') print('Config location : {}'.format(config_name)) print('Data location : {}\n'.format(platform.data_root())) elif args.name is None: parser.print_help() return 1 if args.action == 'set': the_secret = getpass.getpass( 'Please enter the secret for {}: '.format(args.name)) keyring.set_password(_SECRET_NAMESPACE, args.name, the_secret) print('Secret {} set successfully'.format(args.name)) elif args.action == 'get': the_secret = keyring.get_password(_SECRET_NAMESPACE, args.name) if the_secret is None: print('Secret {} not found'.format(args.name)) else: print('Secret {}={}'.format(args.name, the_secret)) elif args.action == 'del': try: keyring.delete_password(_SECRET_NAMESPACE, args.name) print('Deleted secret {}'.format(args.name)) except keyring.errors.PasswordDeleteError: print('Secret {} not found'.format(args.name))