Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
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
Ejemplo n.º 6
0
 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)
Ejemplo n.º 7
0
 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
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
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)
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
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,
        )
Ejemplo n.º 12
0
    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)))
Ejemplo n.º 13
0
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()
Ejemplo n.º 14
0
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
Ejemplo n.º 15
0
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,
        )
Ejemplo n.º 16
0
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
Ejemplo n.º 17
0
    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]
Ejemplo n.º 18
0
    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'])
Ejemplo n.º 19
0
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
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
 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)
Ejemplo n.º 22
0
 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)
Ejemplo n.º 23
0
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
Ejemplo n.º 24
0
 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)
Ejemplo n.º 25
0
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)
Ejemplo n.º 26
0
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)
Ejemplo n.º 27
0
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)
Ejemplo n.º 28
0
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)
Ejemplo n.º 29
0
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
Ejemplo n.º 30
0
    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 ")