Esempio n. 1
0
 def authenticate(self, username, password):
     username = username.strip()
     if not username:
         raise AuthenticationError('No username, please identify yourself!')
     # check for exact match (also matches empty password if username
     # matches)
     for (user, pw, level) in self.passwd:
         if user == username:
             if not pw or pw == self._hash(password):
                 if not password and level > USER:
                     level = USER  # limit passwordless entries to USER
                 return User(username, level)
             else:
                 raise AuthenticationError('Invalid username or password!')
     # check for unspecified user
     for (user, pw, level) in self.passwd:
         if user == '':  # pylint: disable=compare-to-empty-string
             if pw and pw == self._hash(password):
                 if level > USER:
                     level = USER  # limit passworded anonymous to USER
                 return User(username, level)
             elif not pw:  # fix passwordless anonymous to GUEST
                 return User(username, GUEST)
     # do not give a hint whether username or password is wrong...
     raise AuthenticationError('Invalid username or password!')
Esempio n. 2
0
    def authenticate(self, username, password):
        userdn = self._get_user_dn(username)

        # first of all: try a bind to check user existence and password
        try:
            connection = ldap3.Connection(
                self.uri,
                user=userdn,
                password=password,
                auto_bind=self.BIND_METHODS[self.bindmethod])
        except ldap3.core.exceptions.LDAPException as e:
            raise AuthenticationError('LDAP connection failed (%s)' % e)

        userlevel = -1

        # check if the user has explicit rights
        if username in self.userroles:
            userlevel = self._access_levels[self.userroles[username]]
            return User(username, userlevel)

        # if no explicit user right was given, check group rights
        groups = self._get_user_groups(connection, username)

        for group in groups:
            if group in self.grouproles:
                userlevel = max(userlevel,
                                self._access_levels[self.grouproles[group]])

        if userlevel >= 0:
            return User(username, userlevel)

        raise AuthenticationError('Login not permitted for the given user')
Esempio n. 3
0
def test_passwd_user(session, ListAuth):
    assert ListAuth.authenticate('user', 'user') == User('user', USER)
    assert ListAuth.authenticate('guest', '') == User('guest', GUEST)
    assert ListAuth.authenticate('guest', 'somepw') == User('guest', GUEST)
    assert raises(AuthenticationError, ListAuth.authenticate, 'user', 'nouser')
    assert raises(AuthenticationError, ListAuth.authenticate, 'joedoe', '')
    assert User('user', USER).data == {}
    assert User('guest', GUEST).data == {}
Esempio n. 4
0
def test_keystore_auth(session, KeystoreAuth):
    assert KeystoreAuth.userdomain == 'test_nicos_user'

    assert KeystoreAuth.authenticate('admin', 'admin') == User('admin', ADMIN)
    assert KeystoreAuth.authenticate('joedoe', 'userpass') == User('joedoe', USER)
    assert raises(AuthenticationError, KeystoreAuth.authenticate, 'user', 'user_')
    assert raises(AuthenticationError, KeystoreAuth.authenticate, 'admin', 'user_')
    assert User('admin', ADMIN).data == {}
    assert User('joedoe', USER).data == {}
Esempio n. 5
0
 def authenticate(self, username, password):
     try:
         pam.authenticate(username, password, resetcred=0)
         entry = pwd.getpwnam(username)
         idx = access_re.search(to_utf8(entry.pw_gecos))
         if idx:
             access = int(idx.group('level'))
             if access in (GUEST, USER, ADMIN):
                 return User(username, access)
         return User(username, self.defaultlevel)
     except pam.PAMError as err:
         raise AuthenticationError('PAM authentication failed: %s' % err)
     except Exception as err:
         raise AuthenticationError(
             'exception during PAM authentication: %s' % err)
Esempio n. 6
0
 def authenticate(self, username, password):
     if username in self.aliases:
         email, level = self.aliases[username]
     else:
         email, level = username, USER
     ghost = GhostWrapper('https://' + self.ghosthost, self.log)
     try:
         realname = ghost.login(self.instrument,
                                email,
                                password,
                                strict=self.checkexp)
     except ghostapi.errors.GhostAccessError:
         self.log.exception('during authentication')
         raise AuthenticationError('unknown user or wrong password') \
             from None
     except AuthenticationError:
         self.log.exception('during authentication')
         raise
     except Exception as err:
         self.log.exception('during authentication')
         raise AuthenticationError('exception during authenticate(): %s' %
                                   err) from None
     if email == username:
         # try to extract the user's real name from the user data
         username = realname
     return User(username, level, {
         'ghost': ghost,
         'keepalive': ghost.keepalive
     })
Esempio n. 7
0
    def authenticate(self, username, password):
        """Authenticate a user with given username and password hash.

        On success, must return a User object.  On failure, must raise
        `AuthenticationError`.

        The default implementation accepts any user and password and grants
        ADMIN user level.
        """
        return User(username, ADMIN)
Esempio n. 8
0
 def authenticate(self, username, password):
     try:
         credentials = queryUser(username)
         if credentials[1] != self._hash(password):
             raise AuthenticationError('wrong password')
         return User(username, USER)
     except AuthenticationError:
         raise
     except Exception as err:
         raise AuthenticationError('exception during authenticate(): %s' %
                                   err)
Esempio n. 9
0
def test_any_user(session, ListAuth):
    assert ListAuth.authenticate('user', 'user') == User('user', USER)
    assert ListAuth.authenticate('guest', '') == User('guest', GUEST)
    assert ListAuth.authenticate('joedoe', '') == User('joedoe', GUEST)
    assert ListAuth.authenticate('joedoe', '') != User('joedoe', USER)
    assert raises(AuthenticationError, ListAuth.authenticate, 'user', 'user_')
    assert User('user', USER).data == {}
    assert User('guest', GUEST).data == {}
Esempio n. 10
0
 def authenticate(self, username, password):
     username = username.strip()
     if not username:
         raise AuthenticationError('No username, please identify yourself!')
     # check for exact match (also matches empty password if username
     # matches)
     pw = nicoskeystore.getCredential(username, domain=self.userdomain)
     if pw is None:
         raise AuthenticationError('Invalid username or password!')
     for (user, level) in self.access:
         if user == username:
             if pw == password:
                 if password == '' and level > USER:  # pylint: disable=compare-to-empty-string
                     level = USER  # limit passwordless entries to USER
                 return User(username, level)
             else:
                 raise AuthenticationError('Invalid username or password!')
     # do not give a hint whether username or password is wrong...
     raise AuthenticationError('Invalid username or password!')
Esempio n. 11
0
 def authenticate(self, username, password):
     secret = nicoskeystore.getCredential(self.keystoretoken)
     error = None
     try:
         oauth = OAuth2Session(client=LegacyApplicationClient(
             client_id=self.clientid))
         token = oauth.fetch_token(token_url=self.tokenurl,
                                   username=username,
                                   password=password,
                                   client_id=self.clientid,
                                   client_secret=secret)
     except Exception as err:
         # this avoids leaking credential details via tracebacks
         error = str(err)
     if error:
         raise AuthenticationError('exception during authenticate(): %s' %
                                   error)
     if not oauth.authorized:
         raise AuthenticationError('wrong password')
     return User(username, USER, {
         'token': token,
         'clientid': self.clientid
     })
Esempio n. 12
0
def test_empty_user(session, ListAuth):
    assert ListAuth.authenticate('joedoe', 'passwd') == User('joedoe', USER)
    assert User('joedoe', USER).data == {}
Esempio n. 13
0
    def handle(self):
        """Handle a single connection."""
        self.log.info('connection from %s', self.clientnames)

        # check trusted hosts list, if nonempty
        if self.daemon.trustedhosts:
            self.check_host()

        authenticators = self.daemon.get_authenticators()
        pubkey, privkey = rsa.newkeys(512)
        pubkey_base64 = b64encode(pubkey.save_pkcs1())
        bannerhashing = 'rsa,plain'

        # announce version, authentication modality and serializer
        self.send_ok_reply(
            dict(
                daemon_version=nicos_version,
                custom_version=get_custom_version(),
                nicos_root=config.nicos_root,
                custom_path=config.setup_package_path,
                pw_hashing=bannerhashing,
                rsakey=pubkey_base64,
                protocol_version=self.get_version(),
                serializer=self.serializer.name,
            ))

        # read login credentials
        cmd, credentials = self.recv_command()
        if cmd != 'authenticate' or len(credentials) != 1 or \
           not isinstance(credentials[0], dict) or \
           not all(v in credentials[0] for v in ('login', 'passwd')):
            self.log.error('invalid login: %r, credentials=%r', cmd,
                           credentials)
            self.send_error_reply('invalid credentials')
            raise CloseConnection

        password = credentials[0]['passwd']
        if password[0:4] == 'RSA:':
            password = rsa.decrypt(b64decode(password[4:]), privkey).decode()

        # check login data according to configured authentication
        login = credentials[0]['login']
        self.log.info('auth request from login %r', login)
        if authenticators:
            auth_err = None
            for auth in authenticators:
                try:
                    self.user = auth.authenticate(login, password)
                    break
                except AuthenticationError as err:
                    auth_err = err  # "err" is cleared after the except block
                    continue
            else:  # no "break": all authenticators failed
                self.log.error('authentication failed: %s', auth_err)
                self.send_error_reply(str(auth_err))
                raise CloseConnection
        else:
            self.user = User(login, ADMIN)

        # acknowledge the login
        self.log.info('login succeeded, access level %d', self.user.level)
        self.send_ok_reply(dict(user_level=self.user.level, ))

        # make the user known to controller.current_user()
        self.controller.thread_data.user = self.user

        # start main command loop
        while 1:
            command, data = self.recv_command()
            command_wrappers[command](self, data)