def present(dest, username, password, crypt_scheme, create, check_mode): """ Ensures user is present Returns (msg, changed) """ if crypt_scheme in apache_hashes: context = htpasswd_context else: context = CryptContext(schemes=[crypt_scheme] + apache_hashes) if not os.path.exists(dest): if not create: raise ValueError('Destination %s does not exist' % dest) if check_mode: return ("Create %s" % dest, True) create_missing_directories(dest) if LooseVersion(passlib.__version__) >= LooseVersion('1.6'): ht = HtpasswdFile(dest, new=True, default_scheme=crypt_scheme, context=context) else: ht = HtpasswdFile(dest, autoload=False, default=crypt_scheme, context=context) if getattr(ht, 'set_password', None): ht.set_password(username, password) else: ht.update(username, password) ht.save() return ("Created %s and added %s" % (dest, username), True) else: if LooseVersion(passlib.__version__) >= LooseVersion('1.6'): ht = HtpasswdFile(dest, new=False, default_scheme=crypt_scheme, context=context) else: ht = HtpasswdFile(dest, default=crypt_scheme, context=context) found = None if getattr(ht, 'check_password', None): found = ht.check_password(username, password) else: found = ht.verify(username, password) if found: return ("%s already present" % username, False) else: if not check_mode: if getattr(ht, 'set_password', None): ht.set_password(username, password) else: ht.update(username, password) ht.save() return ("Add/update %s" % username, True)
def add_user(email, password): cwd = os.path.abspath(__file__)[:-7] if not os.path.exists(cwd + ".htpasswd"): ht = HtpasswdFile(cwd + ".htpasswd", new=True) else: ht = HtpasswdFile(cwd + ".htpasswd") result = ht.set_password(email, password) ht.save() return result
def add_user(username, password): cwd = os.path.abspath(__file__)[:-8] if os.path.exists(cwd + "login/.htpasswd") == False: ht = HtpasswdFile(cwd + "login/.htpasswd", new=True) result = ht.set_password(username, password) ht.save() return result else: ht = HtpasswdFile(cwd + "login/.htpasswd") result = ht.set_password(username, password) ht.save() if result == False: return True
def passwd(username): """Set the password for a user.""" if username is None: username = input('Username: '******'htpasswd') os.makedirs(app.instance_path, exist_ok=True) try: htpasswd = HtpasswdFile(path) except FileNotFoundError: htpasswd = HtpasswdFile() htpasswd.set_password(username, password) htpasswd.save(path)
def verify_pw(username, password): """ return password or None if there isn't one""" credentials = HtpasswdFile(app.config["CREDENTIAL_FILE"]) if not credentials.check_password(username, password): logging.warning("%s tried to login with wrong password", username) return False return True
def __init__(self, file_path): """ :param file_path: Path to the file with authentication information. :type file_path: ``str`` """ self._file_path = file_path self._htpasswd_file = HtpasswdFile(path=self._file_path)
def __init__(self, htpasswd_file=".htpasswd", perms_file=".repoperms", keys_file=".rsakeys"): self.htpasswd = HtpasswdFile(htpasswd_file) self.perms_file = perms_file self.keys_file = keys_file
def validate_user(username, password, htpassfile=None, session={}, request=None): ''' Validate the User with htpassfile or Trac ''' from brain import bconfig result = {} # validate the user with htpassfile or trac username is_valid = False user = None # try from request if not htpassfile and request: htpassfile = request.environ.get('HTPASSFILE', None) # try from brain config if not htpassfile and hasattr(bconfig, '_htpass_path'): htpassfile = bconfig._htpass_path # validate user if username == 'sdss': if htpassfile: htpass = HtpasswdFile(htpassfile) is_valid = htpass.check_password(username, password) user = username else: result['error'] = 'No valid htpasswd file found!' else: result = inspection_authenticate(session, username=username, password=password) is_valid = result['is_valid'] user = result.get('membername', None) return is_valid, user, result
def htpasswd_file(): """Create a new htpasswd file and return the path and instance.""" tmpdir = mkdtemp() passpath = path.join(tmpdir, 'htpasswd.pass') HtpasswdFile(passpath, new=True).save() yield passpath rmtree(tmpdir)
def absent(dest, username, check_mode): """ Ensures user is absent Returns (msg, changed) """ if LooseVersion(passlib.__version__) >= LooseVersion('1.6'): ht = HtpasswdFile(dest, new=False) else: ht = HtpasswdFile(dest) if username not in ht.users(): return ("%s not present" % username, False) else: if not check_mode: ht.delete(username) ht.save() return ("Remove %s" % username, True)
def create_tls_secret(tls_config: TlsConfig, tls_secret_name: str, namespace: str, basic_auth_cred: BasicAuthCred = None): """ Creates a secret with the configured TLS certificates in the K8s cluster. Optionally adds credentials for Basic Authentication""" not_none(tls_config) not_empty(tls_secret_name) not_empty(namespace) ctx = kube_ctx namespace_helper = ctx.namespace_helper() namespace_helper.create_if_absent(namespace) secret_helper = ctx.secret_helper() if not secret_helper.get_secret(tls_secret_name, namespace): data = { 'tls.key': tls_config.private_key(), 'tls.crt': tls_config.certificate(), } if basic_auth_cred: ht = HtpasswdFile() ht.set_password(basic_auth_cred.user, basic_auth_cred.password) data['auth'] = ht.to_string().decode('utf-8') secret_helper.put_secret( name=tls_secret_name, data=data, namespace=namespace, )
def run(self): try: import gevent.monkey gevent.monkey.patch_all() server_address = (CONFIG.get('network', 'listen-host'), CONFIG.getint('network', 'listen-port')) self.server = SecureXMLRPCServer(server_address, SecureXMLRPCRequestHandler) # Set process name setproctitle('storage_serviced') # Register functions self.server.register_function(self.create, 'create') self.server.register_function(self.delete, 'delete') # Read users file from passlib.apache import HtpasswdFile passwd_file = CONFIG.get('runtime', 'passwd-file') try: self.server.users = HtpasswdFile(passwd_file) except: self.logger.error("Could not open authentication file %s" % passwd_file) self.logger.info("Storage service running as PID %d" % os.getpid()) self.logger.info("Listening on %s:%d" % server_address) signal.signal(signal.SIGTERM, self.stop_handler) self.server.serve_forever() except Exception as e: self.logger.info('Exception was of type: %s' % (str(type(e)))) self.logger.info("Exception= : %s" % (str(e)))
def setFtpPasswd(user, passwd, test=False): conf = siteConf() testPfx = '_test' if test else '' ht = HtpasswdFile(conf.get('ftp', 'passwd' + testPfx), default_scheme="md5_crypt") ht.set_password(user, passwd) ht.save()
def configure(root=None, redirect_to_fallback=True, fallback_url=None, password_file=None, overwrite=False): global packages if root is None: root = os.path.expanduser("~/packages") if fallback_url is None: fallback_url = "http://pypi.python.org/simple" if not isinstance(root, (list, tuple)): roots = [root] else: roots = root roots = [os.path.abspath(r) for r in roots] for r in roots: try: os.listdir(r) except Exception: err = sys.exc_info()[1] sys.exit("Error: while trying to list %r: %s" % (r, err)) packages = lambda: itertools.chain(*[listdir(r) for r in roots]) packages.root = roots[0] config.redirect_to_fallback = redirect_to_fallback config.fallback_url = fallback_url if password_file: from passlib.apache import HtpasswdFile config.htpasswdfile = HtpasswdFile(password_file) config.overwrite = overwrite
def create_basic_auth_secret( secret_name: str, namespace: str, basic_auth_cred: BasicAuthCred = None, ): """ Creates a secret with the configured TLS certificates in the K8s cluster. Optionally adds credentials for Basic Authentication""" not_empty(secret_name) not_empty(namespace) ctx = kube_ctx namespace_helper = ctx.namespace_helper() namespace_helper.create_if_absent(namespace) secret_helper = ctx.secret_helper() if not secret_helper.get_secret(secret_name, namespace): ht = HtpasswdFile() ht.set_password(basic_auth_cred.user, basic_auth_cred.password) data = { 'auth': ht.to_string().decode('utf-8'), } secret_helper.put_secret( name=secret_name, data=data, namespace=namespace, )
def compute_basic_auth(username, password): """Generate hashed HTTP basic auth from traefik_api username+password""" ht = HtpasswdFile() # generate htpassword ht.set_password(username, password) hashed_password = str(ht.to_string()).split(":")[1][:-3] return username + ":" + hashed_password
def _generate_htpassword(self): from passlib.apache import HtpasswdFile ht = HtpasswdFile() ht.set_password(self.traefik_api_username, self.traefik_api_password) self.traefik_api_hashed_password = str( ht.to_string()).split(":")[1][:-3]
def __init__(self): config = self.get_component_config() if 'file' not in config: raise InsufficientConfiguration(missing='file', component=self.get_component_name()) self.htpasswd = HtpasswdFile(config['file'])
def configure(**kwds): """ :return: a 2-tuple (Configure, package-list) """ c = Configuration(**kwds) log.info(f"+++Pypiserver invoked with: {c}") if c.root is None: c.root = os.path.expanduser("~/packages") roots = c.root if isinstance(c.root, (list, tuple)) else [c.root] roots = [os.path.abspath(r) for r in roots] for r in roots: try: os.listdir(r) except OSError: err = sys.exc_info()[1] sys.exit(f"Error: while trying to list root({r}): {err}") packages = lambda: itertools.chain(*[listdir(r) for r in roots]) packages.root = roots[0] if not c.authenticated: c.authenticated = [] if not callable(c.auther): if c.password_file and c.password_file != ".": from passlib.apache import HtpasswdFile htPsswdFile = HtpasswdFile(c.password_file) else: c.password_file = htPsswdFile = None c.auther = functools.partial(auth_by_htpasswd_file, htPsswdFile) # Read welcome-msg from external file or failback to the embedded-msg try: if not c.welcome_file: c.welcome_file = "welcome.html" c.welcome_msg = pkg_resources.resource_string( # @UndefinedVariable __name__, "welcome.html").decode("utf-8") # @UndefinedVariable else: with io.open(c.welcome_file, "r", encoding="utf-8") as fd: c.welcome_msg = fd.read() except Exception: log.warning(f"Could not load welcome-file({c.welcome_file})!", exc_info=True) if c.fallback_url is None: c.fallback_url = "https://pypi.org/simple" if c.hash_algo: try: halgos = hashlib.algorithms_available except AttributeError: halgos = ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"] if c.hash_algo not in halgos: sys.exit(f"Hash-algorithm {c.hash_algo} not one of: {halgos}") log.info(f"+++Pypiserver started with: {c}") return c, packages
def initPasswordFile(path: Path) -> HtpasswdFile: passwordFile = HtpasswdFile(str(path), default_scheme='portable', new=True) # Marking schemes as deprecated tells passlib to re-hash when a password # is successfully verified. Instead of marking only known insecure schemes # as deprecated, we mark everything except the default scheme. # A good password cannot be brute forced in a reasonable amount of time, # but few people actually use good passwords, so slowing down an attacker # by using the best hash algorithm we have available is useful. orgContext = passwordFile.context defaultScheme = orgContext.default_scheme() deprecated = [ scheme for scheme in orgContext.schemes() if scheme != defaultScheme ] passwordFile.context = orgContext.copy(deprecated=deprecated) try: passwordFile.load() except FileNotFoundError: path.parent.mkdir(parents=True, exist_ok=True) # Create empty file. with path.open('a'): pass return passwordFile
def init_app(s, app): fname = app.config.get('HTPASSWD_FILE') if fname: if not hasattr(app, 'extensions'): app.extensions = {} app.extensions[ext_name] = HtpasswdFile(fname) app.before_request(require_auth)
def authenticate(self, request): """Authenticate the provided request.""" if (self.config.password_file is None or self.config.password_file == '.'): return True pwd_file = HtpasswdFile(self.config.password_file) pwd_file.load_if_changed() return pwd_file.check_password(*request.auth)
def groupfinder(username, password, request): ht = HtpasswdFile() ht.load_string(os.environ.get("HTPASSWORDS", "")) if ht.check_password(username, password): return ["admin"] else: return None
def is_user_authenticated(self, username, password): passfile = HtpasswdFile(config['passfile']) # is the user in the password file? if not username in passfile.users(): return False return passfile.check_password(username, password)
def update_passwd(): global passwd global passwd_mtime passwd_exists = os.path.exists(passwd_path) if passwd_exists: # Use the modified time to update the passwd file if necessary try: new_passwd_mtime = os.stat(passwd_path).st_mtime except Exception as e: print(str(e)) new_passwd_mtime = 0 # If the file has changed if new_passwd_mtime != passwd_mtime: app.logger.debug('Update passwd file') passwd = HtpasswdFile(passwd_path, new=False) passwd_mtime = new_passwd_mtime else: if passwd_mtime > 0 or passwd is None: passwd = HtpasswdFile(passwd_path, new=True)
def absent(dest, username, check_mode): """ Ensures user is absent Returns (msg, changed) """ if not os.path.exists(dest): raise ValueError("%s does not exists" % dest) if StrictVersion(passlib.__version__) >= StrictVersion('1.6'): ht = HtpasswdFile(dest, new=False) else: ht = HtpasswdFile(dest) if username not in ht.users(): return ("%s not present" % username, False) else: if not check_mode: ht.delete(username) ht.save() return ("Remove %s" % username, True)
def logins(passfile_path, *logins): """Add (username, password) pairs to htpasswd file.""" passbak_path = '{}.bak'.format(passfile_path) copy2(passfile_path, passbak_path) passfile = HtpasswdFile(passfile_path) for uname, password in logins: passfile.set_password(uname, password) passfile.save() yield remove(passfile_path) copy2(passbak_path, passfile_path)
def create_ht(key, folder, htaccess, csv_dict): user_htaccess = htaccess.replace( 'auth_name', '"' + csv_dict[key]['matricola'] + '"').replace( 'psw_path', ABSOLUTE_PATH_TO_HTPASSWD_ON_WEB_SERVER + '/' + folder + '/.htpasswd') ht = HtpasswdFile(SHUTTLE_FOLDER + '/' + folder + '/.htpasswd', new=True) ht.set_password(csv_dict[key]['matricola'], csv_dict[key]['psw']) ht.set_password("admin", pwd_admin) ht.save() with open(SHUTTLE_FOLDER + '/' + folder + '/.htaccess', 'w') as f: f.write(user_htaccess)
def verify_passwd_hash(username, password): htContent = HtpasswdFile(app.config['HTPASSWD_FILE'], default_scheme='sha256_crypt') passwdHash = htContent.get_hash(username) try: hashMatch = sha256_crypt.verify(password, passwdHash) if hashMatch: return True except ValueError: return False except TypeError: return False
def check_credentials(self, username, password): """ Need to make this file based. """ if os.path.isfile(self.htpasswd): ht = HtpasswdFile(self.htpasswd) if ht.check_password(username, password): return (True) else: return (u"Incorrect username or password.") return (u"Htpasswd file was not found ")