Exemple #1
0
    def authenticatePassword(self, app, credentials):
        assert isinstance(app, Factory)
        assert IUsernamePassword.providedBy(credentials)

        service = Service(
            self.protocol(app.getConfig(),
                          'drupalorg-vcs-auth-fetch-user-hash'))
        service.request_json({"username": credentials.username})

        def _authCallback(result):
            if result:
                service = Service(
                    self.protocol(app.getConfig(),
                                  'drupalorg-vcs-auth-check-user-pass'))

                data = {
                    "username": credentials.username,
                    "password": DrupalHash(result,
                                           credentials.password).get_hash()
                }

                service.request_bool(data)

                service.addCallback(self._handleProtocolCallback, app, data)

                return service.deferred
            else:
                return None

        service.addCallback(_authCallback)

        return service.deferred
Exemple #2
0
def login(client, credentials):
    """
    Authenticate using the given L{AMP} instance.  The protocol must be
    connected to a server with responders for L{PasswordLogin} and
    L{PasswordChallengeResponse}.

    @param client: A connected L{AMP} instance which will be used to issue
        authentication commands.

    @param credentials: An object providing L{IUsernamePassword} which will
        be used to authenticate this connection to the server.

    @return: A L{Deferred} which fires when authentication has succeeded or
        which fails with L{UnauthorizedLogin} if the server rejects the
        authentication attempt.
    """
    if not IUsernamePassword.providedBy(credentials):
        raise UnhandledCredentials()
    d = client.callRemote(
        PasswordLogin, username=credentials.username)
    def cbChallenge(response):
        args = PasswordChallengeResponse.determineFrom(
            response['challenge'], credentials.password)
        d = client.callRemote(PasswordChallengeResponse, **args)
        return d.addCallback(lambda ignored: client)
    d.addCallback(cbChallenge)
    return d
Exemple #3
0
  def authenticatePassword(self, app, credentials):
    assert IUsernamePassword.providedBy(credentials)

    if credentials.username == "pass" and credentials.password == "test_pass":
      return defer.succeed(UserStub())
    else:
      return None
Exemple #4
0
def login(client, credentials):
    """
    Authenticate using the given L{AMP} instance.  The protocol must be
    connected to a server with responders for L{PasswordLogin} and
    L{PasswordChallengeResponse}.

    @param client: A connected L{AMP} instance which will be used to issue
        authentication commands.

    @param credentials: An object providing L{IUsernamePassword} which will
        be used to authenticate this connection to the server.

    @return: A L{Deferred} which fires when authentication has succeeded or
        which fails with L{UnauthorizedLogin} if the server rejects the
        authentication attempt.
    """
    if not IUsernamePassword.providedBy(credentials):
        raise UnhandledCredentials()
    d = client.callRemote(PasswordLogin, username=credentials.username)

    def cbChallenge(response):
        args = PasswordChallengeResponse.determineFrom(response['challenge'],
                                                       credentials.password)
        d = client.callRemote(PasswordChallengeResponse, **args)
        return d.addCallback(lambda ignored: client)

    d.addCallback(cbChallenge)
    return d
Exemple #5
0
    def _auth(self, result, credentials):
        if not result:
            # Username not found in db
            return defer.fail(
                error.UnauthorizedLogin('Username or Password mismatch'))
        else:
            id = result.id
            password = result.password

        if IUsernameHashedPassword.providedBy(credentials):
            if credentials.checkPassword(password):
                return defer.succeed(id)
            else:
                return defer.fail(
                    error.UnauthorizedLogin('Username or Password mismatch'))
        elif IUsernamePassword.providedBy(credentials):
            m = hashlib.md5()
            m.update(credentials.password)
            #if password==m.hexdigest():
            if password == credentials.password:
                from goliat.session.usermanager import UserManager
                if not UserManager().exists(id):
                    return defer.succeed(id)
                else:
                    return defer.succeed(id)
                    #return defer.fail(
                    #    error.LoginFailed('Already Logged'))
            else:
                return defer.fail(
                    error.UnauthorizedLogin('Username or Password mismatch'))
        else:
            # Wooops!
            return defer.fail(
                error.UnhandledCredentials(
                    'Revise the protocol configuration'))
Exemple #6
0
    def requestAvatarId(self, credentials):
        for interface in self.credentialInterfaces:
            if interface.providedBy(credentials):
                break
        else:
            raise error.UnhandledCredentials()

        try:
            result = yield getUser(credentials.username)
        except:
            msg = "Database Error"
            raise error.UnhandledCredentials(msg)

        result = list(result)
        if not len(result):
            raise error.UnauthorizedLogin("Username not found.")
        else:
            password = result[0].password
            if IUsernameHashedPassword.providedBy(credentials):
                if credentials.checkPassword(password):
                    defer.returnValue(result[0])
                else:
                    raise error.UnauthorizedLogin("Password mismatch.")

            elif IUsernamePassword.providedBy(credentials):
                if password == credentials.password:
                    defer.returnValue(result[0])
                else:
                    raise error.UnauthorizedLogin("Password mismatch.")

            else:
                raise error.UnhandledCredentials()
Exemple #7
0
    def _auth(self, result, credentials):
        if not result:
            # Username not found in db            
            return defer.fail(
                error.UnauthorizedLogin('Username or Password mismatch'))
        else:
            id=result.id
            password=result.password

        if IUsernameHashedPassword.providedBy(credentials):
            if credentials.checkPassword(password):
                return defer.succeed(id)
            else:
                return defer.fail(
                    error.UnauthorizedLogin('Username or Password mismatch'))
        elif IUsernamePassword.providedBy(credentials):
            m=hashlib.md5()
            m.update(credentials.password)
            #if password==m.hexdigest():
            if password==credentials.password:
                from goliat.session.usermanager import UserManager
                if not UserManager().exists(id):
                    return defer.succeed(id)
                else:
                    return defer.succeed(id)
                    #return defer.fail(
                    #    error.LoginFailed('Already Logged'))
            else:
                return defer.fail(
                    error.UnauthorizedLogin('Username or Password mismatch'))
        else:
            # Wooops!            
            return defer.fail(
                error.UnhandledCredentials('Revise the protocol configuration'))
Exemple #8
0
    def authenticatePassword(self, app, credentials):
        assert isinstance(app, Factory)
        assert IUsernamePassword.providedBy(credentials)

        service = Service(self.protocol(app.getConfig(), "drupalorg-vcs-auth-fetch-user-hash"))
        service.request_json({"username": credentials.username})

        def _authCallback(result):
            if result:
                service = Service(self.protocol(app.getConfig(), "drupalorg-vcs-auth-check-user-pass"))

                data = {
                    "username": credentials.username,
                    "password": DrupalHash(result, credentials.password).get_hash(),
                }

                service.request_bool(data)

                service.addCallback(self._handleProtocolCallback, app, data)

                return service.deferred
            else:
                return None

        service.addCallback(_authCallback)

        return service.deferred
Exemple #9
0
 def requestAvatarId(self, credentials):
     """
     Check the given credentials and return a suitable user identifier if
     they are valid.
     """
     if IUsernamePassword.providedBy(credentials):
         return self._checkPassword(credentials)
     if ISSHPrivateKey.providedBy(credentials):
         return self._checkKey(credentials)
     raise NotImplementedError()
Exemple #10
0
 def _requestAvatarId(self, err, queue, credentials):
     # disallow empty password to be authenticated
     if IUsernamePassword.providedBy(credentials) and \
         ((not credentials.password) or (credentials.username=='root')):
         raise UnauthorizedLogin()
     try:
         ch = queue.popleft()
     except IndexError:
         raise UnauthorizedLogin()
     d = ch.requestAvatarId(credentials)
     return d.addErrback(self._requestAvatarId, queue, credentials)
Exemple #11
0
    def test_usernamePassword(self):
        """
        L{basic.BasicCredentialFactory.decode} turns a base64-encoded response
        into a L{UsernamePassword} object with a password which reflects the
        one which was encoded in the response.
        """
        response = b64encode(b''.join([self.username, b':', self.password]))

        creds = self.credentialFactory.decode(response, self.request)
        self.assertTrue(IUsernamePassword.providedBy(creds))
        self.assertTrue(creds.checkPassword(self.password))
        self.assertFalse(creds.checkPassword(self.password + b'wrong'))
Exemple #12
0
    def test_usernamePassword(self):
        """
        L{basic.BasicCredentialFactory.decode} turns a base64-encoded response
        into a L{UsernamePassword} object with a password which reflects the
        one which was encoded in the response.
        """
        response = b64encode('%s:%s' % (self.username, self.password))

        creds = self.credentialFactory.decode(response, self.request)
        self.assertTrue(IUsernamePassword.providedBy(creds))
        self.assertTrue(creds.checkPassword(self.password))
        self.assertFalse(creds.checkPassword(self.password + 'wrong'))
Exemple #13
0
  def requestAvatarId(self, credentials):
    self._invariant()
    assert IUsernamePassword.providedBy(credentials)

    d = defer.maybeDeferred(self.app.getAuth().authenticatePassword, self.app, credentials)
    d.addCallback(self.authCallback, credentials)

    d.addErrback(authenticationErrorHandler)

    assert isinstance(d, defer.Deferred)

    return d
Exemple #14
0
    def _connect(self):
        """
        Connect to the directory server.
        This will always be called in a thread to prevent blocking.

        @returns: The connection object.
        @rtype: L{ldap.ldapobject.LDAPObject}

        @raises: L{LDAPConnectionError} if unable to connect.
        """

        # FIXME: ldap connection objects are not thread safe, so let's set up
        # a connection pool

        self.log.debug("Connecting to LDAP at {log_source.url}")
        connection = self._newConnection()

        if self._credentials is not None:
            if IUsernamePassword.providedBy(self._credentials):
                try:
                    connection.simple_bind_s(
                        self._credentials.username,
                        self._credentials.password,
                    )
                    self.log.debug(
                        "Bound to LDAP as {credentials.username}",
                        credentials=self._credentials
                    )
                except (
                    ldap.INVALID_CREDENTIALS, ldap.INVALID_DN_SYNTAX
                ) as e:
                    self.log.error(
                        "Unable to bind to LDAP as {credentials.username}",
                        credentials=self._credentials
                    )
                    raise LDAPBindAuthError(
                        self._credentials.username, e
                    )

            else:
                raise LDAPConnectionError(
                    "Unknown credentials type: {0}"
                    .format(self._credentials)
                )

        return connection
Exemple #15
0
 def _cbAuthenticate(self, result, credentials, deferred):
     """
     Checks to see if authentication was good. Called once the info has
     been retrieved from the DB.
     """
     if len(result) == 0:
         # Username not found in db
         deferred.errback(error.UnauthorizedLogin('Username unknown'))
     else:
         username, password = result[0]
         if self.customCheckFunc:
             # Let the owner do the checking
             if self.customCheckFunc(username, credentials.password,
                                     password):
                 deferred.callback(credentials.username)
             else:
                 deferred.errback(
                     error.UnauthorizedLogin('Password mismatch'))
         else:
             # It's up to us or the credentials object to do the checking
             # now
             if IUsernameHashedPassword.providedBy(credentials):
                 # Let the hashed password checker do the checking
                 if credentials.checkPassword(password):
                     deferred.callback(credentials.username)
                 else:
                     deferred.errback(
                         error.UnauthorizedLogin('Password mismatch'))
             elif IUsernamePassword.providedBy(credentials):
                 # Compare the passwords, deciging whether or not to use
                 # case sensitivity
                 if self.caseSensitivePasswords:
                     passOk = (
                         password.lower() == credentials.password.lower())
                 else:
                     passOk = password == credentials.password
                 # See if they match
                 if passOk:
                     deferred.callback(credentials.username)
                 else:
                     deferred.errback(
                         error.UnauthorizedLogin('Password mismatch'))
             else:
                 # OK, we don't know how to check this
                 deferred.errback(error.UnhandledCredentials())
Exemple #16
0
 def _cbAuthenticate(self, result, credentials, deferred):
     """
     Checks to see if authentication was good. Called once the info has
     been retrieved from the DB.
     """
     if len(result) == 0:
         # Username not found in db
         deferred.errback(error.UnauthorizedLogin('Username unknown'))
     else:
         username, password = result[0]
         if self.customCheckFunc:
             # Let the owner do the checking
             if self.customCheckFunc(
                     username, credentials.password, password):
                 deferred.callback(credentials.username)
             else:
                 deferred.errback(
                     error.UnauthorizedLogin('Password mismatch'))
         else:
             # It's up to us or the credentials object to do the checking
             # now
             if IUsernameHashedPassword.providedBy(credentials):
                 # Let the hashed password checker do the checking
                 if credentials.checkPassword(password):
                     deferred.callback(credentials.username)
                 else:
                     deferred.errback(
                         error.UnauthorizedLogin('Password mismatch'))
             elif IUsernamePassword.providedBy(credentials):
                 # Compare the passwords, deciging whether or not to use
                 # case sensitivity
                 if self.caseSensitivePasswords:
                     passOk = (
                         password.lower() == credentials.password.lower())
                 else:
                     passOk = password == credentials.password
                 # See if they match
                 if passOk:
                     deferred.callback(credentials.username)
                 else:
                     deferred.errback(
                         error.UnauthorizedLogin('Password mismatch'))
             else:
                 # OK, we don't know how to check this
                 deferred.errback(error.UnhandledCredentials())
Exemple #17
0
 def __init__(self, credentials, api, provider_cert):
     # TODO move provider_cert to api object.
     # On creation, it should be able to retrieve all the info it needs
     # (calling bootstrap).
     # TODO could get a "provider" object instead.
     # this provider can have an api attribute,
     # and a "autoconfig" attribute passed on initialization.
     # TODO get a file-descriptor for password if not in credentials
     # TODO merge self._request with config.Provider._http_request ?
     if IAnonymous.providedBy(credentials):
         self.username = None
         self.password = None
     elif IUsernamePassword.providedBy(credentials):
         self.username = credentials.username
         self.password = credentials.password
     self._provider_cert = provider_cert
     self._api = api
     self._initialize_session()
Exemple #18
0
    def requestAvatarId(self, credentials):
        if not IUsernamePassword.providedBy(credentials):
            raise TypeError(
                "Not an IUsernamePassword: {0!r}".format(credentials))

        record = yield self.service.recordWithShortName(
            RecordType.user, credentials.username.decode("utf-8"))

        if record is None:
            raise UnauthorizedLogin("No such user")

        if not IPlaintextPasswordVerifier.providedBy(record):
            raise UnauthorizedLogin(
                "Not an IPlaintextPasswordVerifier: {0!r}".format(record))

        auth = yield record.verifyPlaintextPassword(credentials.password)
        if auth:
            returnValue(record)

        raise UnauthorizedLogin("Incorrect password")
 def test_interface(self):
     """
     L{UsernamePassword} implements L{IUsernamePassword}.
     """
     self.assertTrue(IUsernamePassword.implementedBy(UsernamePassword))
Exemple #20
0
  def authenticatePassword(self, app, credentials):
    assert IUsernamePassword.providedBy(credentials)

    return False
Exemple #21
0
  def authenticatePassword(self, app, credentials):
    assert IUsernamePassword.providedBy(credentials)

    return defer.succeed(True)
Exemple #22
0
 def test_interface(self):
     """
     L{UsernamePassword} implements L{IUsernamePassword}.
     """
     self.assertTrue(IUsernamePassword.implementedBy(UsernamePassword))