Ejemplo n.º 1
0
    def onChallenge(self, challenge):
        self.logger.info("Authenticate connection %s@%s (challenge) ...",
                         self.authid, self.config.realm)

        self.logger.debug("Challenge:")
        self.logger.debug(" + method: %s", challenge.method)
        self.logger.debug(" + extra:  %s", challenge.extra)

        if challenge.method == u"wampcra":
            salt = challenge.extra['salt']
            secret = self.secret

            secret = auth.derive_key(
                secret.encode('utf8'),
                salt.encode('utf8'),
                iterations=challenge.extra['iterations'],
                keylen=challenge.extra['keylen']).decode('ascii')

            signature = auth.compute_wcs(
                secret.encode('utf8'),
                challenge.extra['challenge'].encode('utf8'))

            signature = signature.decode('ascii')

            self.logger.debug("Signature '%s'", signature)
            return signature

        else:
            self.logger.error("Unknown challenge method '%s'",
                              challenge.method)
Ejemplo n.º 2
0
 def add(self, authid, authrole, secret, salt = None):
    if salt:
       key = auth.derive_key(secret, salt)
    else:
       key = secret
    self._creds[authid] = (salt, key, authrole)
    return self._creds[authid]
Ejemplo n.º 3
0
 def add(self, authid, authrole, secret, salt=None):
     if salt:
         key = auth.derive_key(secret, salt)
     else:
         key = secret
     self._creds[authid] = (salt, key, authrole)
     return self._creds[authid]
Ejemplo n.º 4
0
 def register_user(user_details):
     if user_exists(user_details['username']):
         return {"error": "User already exists. Please try again"}
     try:
         username = user_details['username']
         pw = generate_password()
         salted_pw = ath.derive_key(pw, auth_config['salt'],
                                    auth_config['iterations'],
                                    auth_config['keylen'])
         db_rec = {
             'username': username,
             'user_details': user_details,
             'auth_details': copy.deepcopy(auth_config)
         }
         db_rec['auth_details']['secret'] = salted_pw
         db_rec['auth_details']['role'] = u'user'
         del db_rec['user_details']['username']
         #print "Registered user ",  db_rec
         db.insert(db_rec)
     except Exception as e:
         print e
         return {"error": "Unexpected error occured. Please try again"}
     print "User added to database"
     send_email(user_details, pw, username)
     return {
         "success":
         "Successfuly registered. Please check your email for your password."
     }
Ejemplo n.º 5
0
        def on_challenge(challenge):
            if challenge.method == u"wampcra":
                print("WAMP-CRA challenge received: {}".format(challenge))
                if u'salt' in challenge.extra:
                    # salted secret
                    salted_key = auth.derive_key(secret,
                                                 challenge.extra['salt'],
                                                 challenge.extra['iterations'],
                                                 challenge.extra['keylen'])
                    salted_key = (salted_key).decode('utf-8')
                    print(salted_key)
                #if user==u'ffbo':
                # plain, unsalted secret
                #    salted_key = u"kMU73GH4GS1WGUpEaSdDYwN57bdLdB58PK1Brb25UCE="
                #print(salted_key)
                # compute signature for challenge, using the key
                signature = auth.compute_wcs(salted_key,
                                             challenge.extra['challenge'])

                # return the signature to the router for verification
                return signature

            else:
                raise Exception("Invalid authmethod {}".format(
                    challenge.method))
Ejemplo n.º 6
0
 def add(self, authid, authrole, secret, salt = None):
    if salt:
       key = auth.derive_key(secret.encode('utf8'), salt.encode('utf8')).decode('ascii')
    else:
       key = secret
    self._creds[authid] = (salt, key, authrole)
    return self._creds[authid]
Ejemplo n.º 7
0
    def onChallenge(self, challenge):
        self.logger.info(
            "Authenticate connection %s@%s (challenge) ...",
            self.authid, self.config.realm
        )

        self.logger.debug("Challenge:")
        self.logger.debug(" + method: %s", challenge.method)
        self.logger.debug(" + extra:  %s", challenge.extra)

        if challenge.method == u"wampcra":
            salt = challenge.extra['salt']
            secret = self.secret

            secret = auth.derive_key(
                secret.encode('utf8'),
                salt.encode('utf8'),
                iterations=challenge.extra['iterations'],
                keylen=challenge.extra['keylen']
            ).decode('ascii')

            signature = auth.compute_wcs(
                secret.encode('utf8'),
                challenge.extra['challenge'].encode('utf8')
            )

            signature = signature.decode('ascii')

            self.logger.debug("Signature '%s'", signature)
            return signature

        else:
            self.logger.error("Unknown challenge method '%s'", challenge.method)
Ejemplo n.º 8
0
 def verify(self, password, encoded):
     algorithm, salt, iterations, keylen, derived = encoded.split('$')
     new_password = '******'.join([
         self.algorithm, salt, iterations, keylen,
         derive_key(password, salt, int(iterations),
                    int(keylen)).decode('ascii')
     ])
     return encoded == new_password
Ejemplo n.º 9
0
 def encode(self, password, salt):
     password = '******'.join([
         self.algorithm, salt,
         str(settings.ITERATIONS),
         str(settings.KEYLEN),
         derive_key(password, salt, settings.ITERATIONS,
                    settings.KEYLEN).decode('ascii')
     ])
     return password
Ejemplo n.º 10
0
    def on_challenge(self, session, challenge):
        key = self._secret.encode('utf8')
        if u'salt' in challenge.extra:
            key = auth.derive_key(key, challenge.extra['salt'],
                                  challenge.extra['iterations'],
                                  challenge.extra['keylen'])

        signature = auth.compute_wcs(
            key, challenge.extra['challenge'].encode('utf8'))
        return signature.decode('ascii')
Ejemplo n.º 11
0
 def onChallenge(self, challenge):
    print challenge
    if challenge.method == u"wampcra":
       if u'salt' in challenge.extra:
          key = auth.derive_key(PASSWORDS[USER], challenge.extra['salt'],
             challenge.extra.get('iterations', None), challenge.extra.get('keylen', None))
       else:
          key = PASSWORDS[USER]
       signature = auth.compute_wcs(key, challenge.extra['challenge'])
       return signature
    else:
       raise Exception("don't know how to compute challenge for authmethod {}".format(challenge.method))
Ejemplo n.º 12
0
 def onChallenge(self, challenge):
     #print challenge
     if challenge.method == u"wampcra":
         if u'salt' in challenge.extra:
             key = auth.derive_key(self.config.extra['topic'], challenge.extra['salt'],
             challenge.extra.get('iterations', None), challenge.extra.get('keylen', None))
         else:
             key = self.config.extra['topic']
         signature = auth.compute_wcs(key, challenge.extra['challenge'])
         return signature
     else:
         raise Exception("don't know how to compute challenge for authmethod {}".format(challenge.method))
Ejemplo n.º 13
0
 def onChallenge(self, challenge):
     if challenge.method == u"wampcra":
         self.log.debug("WAMP-CRA challenge received: {}".format(challenge))
         if u'salt' in challenge.extra:
             # salted secret
             key = derive_key(USER_SECRET,
                              challenge.extra['salt'],
                              challenge.extra['iterations'],
                              challenge.extra['keylen'])
             # return the signature to the router for verification
             return compute_wcs(key, challenge.extra['challenge'])
     else:
         raise Exception("Invalid authmethod {}".format(challenge.method))
Ejemplo n.º 14
0
 def makeAccount(self, username, password, email, nickname):
     alphabet = string.digits + string.lowercase
     num = Crypto.Random.random.getrandbits(64)
     salt = ""
     while num != 0:
         num, i = divmod(num, len(alphabet))
         salt = alphabet[i] + salt
     extra = {"salt":salt, "keylen":32, "iterations":1000}
     password_hash = auth.derive_key(password.encode('utf-8'),
                                     extra['salt'].encode('utf-8'),
                                     extra['iterations'],
                                     extra['keylen'])
     d = self.call(u"rpc.registrar.make_account", username, "%s:%s" % (salt, password_hash), email, nickname)
     return d.addCallback(self.onMakeAccount).addErrback(self.onError, "makeAccount")
Ejemplo n.º 15
0
 def onChallenge(self, challenge):
     logger.info('Challenge received.')
     if challenge.method == 'wampcra':
         if 'salt' in challenge.extra:
             key = auth.derive_key(password.encode(),
                                   challenge.extra['salt'].encode(),
                                   challenge.extra.get('iterations', None),
                                   challenge.extra.get('keylen', None))
         else:
             key = password.encode()
         signature = auth.compute_wcs(key, challenge.extra['challenge'])
         return signature.decode('ascii')
     else:
         raise Exception('Unknown challenge method: %s' % challenge.method)
Ejemplo n.º 16
0
 def onChallenge(self, challenge):
    print("authentication challenge received: {}".format(challenge))
    if challenge.method == u"wampcra":
       if u'salt' in challenge.extra:
          key = auth.derive_key(PASSWORDS[USER].encode('utf8'),
             challenge.extra['salt'].encode('utf8'),
             challenge.extra.get('iterations', None),
             challenge.extra.get('keylen', None))
       else:
          key = PASSWORDS[USER].encode('utf8')
       signature = auth.compute_wcs(key, challenge.extra['challenge'].encode('utf8'))
       return signature.decode('ascii')
    else:
       raise Exception("don't know how to compute challenge for authmethod {}".format(challenge.method))
Ejemplo n.º 17
0
 def makeAccount(self, username, password, email, nickname):
     alphabet = string.digits + string.lowercase
     num = Crypto.Random.random.getrandbits(64)
     salt = ""
     while num != 0:
         num, i = divmod(num, len(alphabet))
         salt = alphabet[i] + salt
     extra = {"salt":salt, "keylen":32, "iterations":1000}
     password_hash = auth.derive_key(password.encode('utf-8'),
                                     extra['salt'].encode('utf-8'),
                                     extra['iterations'],
                                     extra['keylen'])
     d = self.call(u"rpc.registrar.make_account", username, "%s:%s" % (salt, password_hash), email, nickname)
     return d.addCallback(self.onMakeAccount).addErrback(self.onError, "makeAccount")
Ejemplo n.º 18
0
 def onChallenge(self, challenge):
     self.log.info('authentication challenge received')
     if challenge.method == u"wampcra":
         if u'salt' in challenge.extra:
             key = auth.derive_key(CRA_SECRET, challenge.extra['salt'],
                                   challenge.extra['iterations'],
                                   challenge.extra['keylen'])
             signature = auth.compute_wcs(key, challenge.extra['challenge'])
             return signature
         else:
             signature = auth.compute_wcs(CRA_SECRET,
                                          challenge.extra['challenge'])
             return signature
     else:
         raise Exception("Invalid authmethod {}".format(challenge.method))
Ejemplo n.º 19
0
    def on_challenge(self, session, challenge):
        key = self._secret.encode('utf8')
        if u'salt' in challenge.extra:
            key = auth.derive_key(
                key,
                challenge.extra['salt'],
                challenge.extra['iterations'],
                challenge.extra['keylen']
            )

        signature = auth.compute_wcs(
            key,
            challenge.extra['challenge'].encode('utf8')
        )
        return signature.decode('ascii')
Ejemplo n.º 20
0
 def onChallenge(self, challenge):
     if challenge.method == u"wampcra":
         if u'salt' in challenge.extra:
             key = auth.derive_key(u"marketmaker".encode('utf8'),
                 challenge.extra['salt'].encode('utf8'),
                 challenge.extra.get('iterations', None),
                 challenge.extra.get('keylen', None))
         else:
             key = u"a".encode('utf8')
         signature = auth.compute_wcs(key, challenge.extra['challenge'].encode('utf8'))
         return signature.decode('ascii')
     elif challenge.method == u"cookie":
         return self.cookie
     else:
         raise Exception("don't know how to compute challenge for authmethod {}".format(challenge.method))
Ejemplo n.º 21
0
    def onChallenge(self, challenge):
        log.msg("got challenge: %s" % challenge)
        if challenge.method == u"wampcra":
            if u'salt' in challenge.extra:
                key = auth.derive_key(self.factory.password.encode('utf-8'),
                    challenge.extra['salt'].encode('utf-8'),
                    challenge.extra.get('iterations', None),
                    challenge.extra.get('keylen', None))
            else:
                key = self.factory.password.encode('utf-8')

            signature = auth.compute_wcs(key, challenge.extra['challenge'].encode('utf-8'))
            return signature.decode('ascii')
        else:
            raise Exception("don't know how to compute challenge for authmethod {}".format(challenge.method))
Ejemplo n.º 22
0
    def onChallenge(self, challenge):
        log.msg("got challenge: %s" % challenge)
        if challenge.method == u"wampcra":
            if u'salt' in challenge.extra:
                key = auth.derive_key(self.factory.password.encode('utf-8'),
                    challenge.extra['salt'].encode('utf-8'),
                    challenge.extra.get('iterations', None),
                    challenge.extra.get('keylen', None))
            else:
                key = self.factory.password.encode('utf-8')

            signature = auth.compute_wcs(key, challenge.extra['challenge'].encode('utf-8'))
            return signature.decode('ascii')
        else:
            raise Exception("don't know how to compute challenge for authmethod {}".format(challenge.method))
Ejemplo n.º 23
0
    def onChallenge(self, challenge: Challenge):
        if challenge.method != self.__auth_method:
            raise ConnectionError(
                'expected authentication method "{}" but received a "{}" challenge instead'.
                format(self.__auth_method, challenge.method))

        if challenge.method == 'wampcra':
            key = self.__auth_secret
            if 'salt' in challenge.extra:
                # salted secret
                key = auth.derive_key(self.__auth_secret.encode('utf-8'),
                                      challenge.extra['salt'], challenge.extra['iterations'],
                                      challenge.extra['keylen'])

            return auth.compute_wcs(key, challenge.extra['challenge'])
        elif challenge.method == 'ticket':  # ticket
            return self.__auth_secret
Ejemplo n.º 24
0
 def onChallenge(self, challenge):
     log.msg("onChallenge - maynard")
     password = '******'
     if 'authinfo' in self.svar:
         password = self.svar['authinfo']['auth_password']
     log.msg("onChallenge with password {}".format(password))
     if challenge.method == u'wampcra':
         if u'salt' in challenge.extra:
             key = auth.derive_key(password.encode('utf8'),
                 challenge.extra['salt'].encode('utf8'),
                 challenge.extra.get('iterations', None),
                 challenge.extra.get('keylen', None))
         else:
             key = password.encode('utf8')
         signature = auth.compute_wcs(key, challenge.extra['challenge'].encode('utf8'))
         return signature.decode('ascii')
     else:
         raise Exception("don't know how to compute challenge for authmethod {}".format(challenge.method))
Ejemplo n.º 25
0
        def onChallenge(self, challenge):
            print("authentication challenge received")

            if challenge.method == u"wampcra":
                print("WAMP-CRA challenge received: {}".format(challenge))

                if u'salt' in challenge.extra:
                    # salted secret
                    key = auth.derive_key(u"uSrnbKa2cjxkYu9Flom1ZMIkNYMriSZ5tKzlhVKJT6o", challenge.extra['salt'], challenge.extra['iterations'], challenge.extra['keylen'])
                else:
                    # plain, unsalted secret
                    key = u"uSrnbKa2cjxkYu9Flom1ZMIkNYMriSZ5tKzlhVKJT6o"

                # compute signature for challenge, using the key
                signature = auth.compute_wcs(key, challenge.extra['challenge'])

                # return the signature to the router for verification
                return signature
Ejemplo n.º 26
0
    def onChallenge(self, challenge: Challenge):
        if challenge.method != self.__auth_method:
            raise WAMPError(
                'expected authentication method "{}" but received a "{}" challenge '
                'instead'.format(self.__auth_method, challenge.method))

        if challenge.method == 'wampcra':
            key = self.__auth_secret
            if 'salt' in challenge.extra:
                # salted secret
                key = auth.derive_key(self.__auth_secret.encode('utf-8'),
                                      challenge.extra['salt'],
                                      challenge.extra['iterations'],
                                      challenge.extra['keylen'])

            return auth.compute_wcs(key, challenge.extra['challenge'])
        elif challenge.method == 'ticket':
            return self.__auth_secret
Ejemplo n.º 27
0
def on_challenge(self, challenge):

    """
    A function that is called when we got onChallenge event aka authentication to a WAMP router.
    This function is attached to our WampDefaultComponent only if protocol is WSS

    :param self:
    :param challenge:

    :return: digital signature decode in ascii
    """

    log = Logger()
    log.info('On Challenge...')

    if challenge.method == u"wampcra":

        cfg = Config().get_wamp()

        password = {
            u'%s' % cfg.user: u'%s' % cfg.password
        }

        if u'salt' in challenge.extra:

            key = auth.derive_key(
                password[cfg.user].encode('utf8'),
                challenge.extra['salt'].encode('utf8'),
                challenge.extra.get('iterations', None),
                challenge.extra.get('keylen', None)
            )

        else:

            key = password[cfg.user].encode('utf8')
        
        signature = auth.compute_wcs(key, challenge.extra['challenge'].encode('utf8'))

        return signature.decode('ascii')

    else:

        raise Exception("don't know how to compute challenge for authmethod {}".format(challenge.method))
Ejemplo n.º 28
0
    def onChallenge(self, challenge):
        if challenge.method == u"wampcra":
            print("WAMP-CRA challenge received: {}".format(challenge))

            if u'salt' in challenge.extra:
                key = auth.derive_key(secret, challenge.extra['salt'],
                                      challenge.extra['iterations'],
                                      challenge.extra['keylen'])
            else:
                # plain, unsalted secret
                key = secret

            # compute signature for challenge, using the key
            signature = auth.compute_wcs(key, challenge.extra['challenge'])

            # return the signature to the router for verification
            return signature

        else:
            raise Exception("Invalid authmethod {}".format(challenge.method))
Ejemplo n.º 29
0
    def onChallenge(self, challenge):
        if challenge.method == "wampcra":
            if 'salt' in challenge.extra:
                # salted secret
                key = auth.derive_key(
                    conf.WAMP_CONNECTION['AUTHSECRET'],
                    challenge.extra['salt'],
                    challenge.extra['iterations'],
                    challenge.extra['keylen'],
                )
            else:
                # plain, unsalted secret
                key = conf.WAMP_CONNECTION['AUTHSECRET']

            signature = auth.compute_wcs(key, challenge.extra['challenge'])
            self.log.info(key)

            return signature
        else:
            raise Exception("don't know how to handle authmethod {}".format(challenge.method))
Ejemplo n.º 30
0
    def handle_wampcra_challenge(self, challenge):
        """
        Default handler for WAMP-CRA authentication

        Uses the `secret` keyword-argument value supplied to the constructor
        of the opendna.autobahn.repl.abc.AbstractSession instance that is the
        parent of this opendna.autobahn.repl.wamp.REPLApplicationSession instance
        in order to generate an authentication signature

        :param challenge:
        :return:
        """
        secret = self._session.session_kwargs['secret']
        if 'salt' in challenge.extra:
            secret = auth.derive_key(self._session.session_kwargs['secret'],
                                     challenge.extra['salt'],
                                     challenge.extra['iterations'],
                                     challenge.extra['keylen'])
        signature = auth.compute_wcs(secret, challenge.extra['challenge'])
        return signature
Ejemplo n.º 31
0
def on_challenge(self, challenge):
    """
    A function that is called when we got onChallenge event aka authentication to a WAMP router.
    This function is attached to our WampDefaultComponent only if protocol is WSS

    :param self:
    :param challenge:

    :return: digital signature decode in ascii
    """

    log = Logger()
    log.info('On Challenge...')

    if challenge.method == u"wampcra":

        cfg = Config().get_wamp()

        password = {u'%s' % cfg.user: u'%s' % cfg.password}

        if u'salt' in challenge.extra:

            key = auth.derive_key(password[cfg.user].encode('utf8'),
                                  challenge.extra['salt'].encode('utf8'),
                                  challenge.extra.get('iterations', None),
                                  challenge.extra.get('keylen', None))

        else:

            key = password[cfg.user].encode('utf8')

        signature = auth.compute_wcs(
            key, challenge.extra['challenge'].encode('utf8'))

        return signature.decode('ascii')

    else:

        raise Exception(
            "don't know how to compute challenge for authmethod {}".format(
                challenge.method))
Ejemplo n.º 32
0
    def onChallenge(self, challenge):
        if challenge.method == "wampcra":
            if 'salt' in challenge.extra:
                # salted secret
                key = auth.derive_key(
                    conf.WAMP_CONNECTION['AUTHSECRET'],
                    challenge.extra['salt'],
                    challenge.extra['iterations'],
                    challenge.extra['keylen'],
                )
            else:
                # plain, unsalted secret
                key = conf.WAMP_CONNECTION['AUTHSECRET']

            signature = auth.compute_wcs(key, challenge.extra['challenge'])
            self.log.info(key)

            return signature
        else:
            raise Exception("don't know how to handle authmethod {}".format(
                challenge.method))
Ejemplo n.º 33
0
   def onChallenge(self, challenge):
      if challenge.method == u"wampcra":
         print("WAMP-CRA challenge received: {}".format(challenge))

         if u'salt' in challenge.extra:
            # salted secret
            key = auth.derive_key(USER_SECRET,
                                  challenge.extra['salt'],
                                  challenge.extra['iterations'],
                                  challenge.extra['keylen'])
         else:
            # plain, unsalted secret
            key = USER_SECRET

         # compute signature for challenge, using the key
         signature = auth.compute_wcs(key, challenge.extra['challenge'])

         # return the signature to the router for verification
         return signature

      else:
         raise Exception("Invalid authmethod {}".format(challenge.method))
Ejemplo n.º 34
0
 def create_user(data, details=None):
     try:
         # Add user
         salt = generate_wcs(12).decode('utf8')
         user = User(username=data['username'],
                     role=data['role'],
                     password='******'.join([
                         'salted_autobahn_auth', salt,
                         str(settings.ITERATIONS),
                         str(settings.KEYLEN),
                         derive_key(data['password'], salt,
                                    settings.ITERATIONS,
                                    settings.KEYLEN).decode('ascii')
                     ]),
                     settings={},
                     created_by=details.caller_authid)
         user.save()
         return True
     except IntegrityError as e:
         return str(e)
     except Exception as e:
         return str(e)
Ejemplo n.º 35
0
    def onChallenge(self, challenge):
        if challenge.method == u"wampcra":
            out.verbose("WAMP-CRA challenge received: {}".format(challenge))

            wampPassword = nexus.core.getKey('apitoken')
            if u'salt' in challenge.extra:
                # salted secret
                key = auth.derive_key(wampPassword, challenge.extra['salt'],
                                      challenge.extra['iterations'],
                                      challenge.extra['keylen'])
            else:
                # plain, unsalted secret
                key = wampPassword

            # compute signature for challenge, using the key
            signature = auth.compute_wcs(key, challenge.extra['challenge'])

            # return the signature to the router for verification
            return signature

        else:
            raise Exception("Invalid authmethod {}".format(challenge.method))
Ejemplo n.º 36
0
        def on_challenge(challenge):
            """The On Challenge function that computes the user signature for verification.
            
            Args:
                challenge (obj): The challenge object received.

            Returns:
                str: The signature sent to the router for verification.
            """
            print(printHeader('FFBOLab Client') + 'Initiating authentication.')
            if challenge.method == u"wampcra":
                print(
                    printHeader('FFBOLab Client') +
                    "WAMP-CRA challenge received: {}".format(challenge))
                print(challenge.extra['salt'])
                if u'salt' in challenge.extra:
                    # Salted secret
                    print(printHeader('FFBOLab Client') + 'Deriving key...')
                    salted_key = auth.derive_key(secret,
                                                 challenge.extra['salt'],
                                                 challenge.extra['iterations'],
                                                 challenge.extra['keylen'])
                    print(salted_key.decode('utf-8'))

                if user == 'guest':
                    # A plain, unsalted secret for the guest account
                    salted_key = u"C5/c598Gme4oALjmdhVC2H25OQPK0M2/tu8yrHpyghA="

                # compute signature for challenge, using the key
                signature = auth.compute_wcs(salted_key,
                                             challenge.extra['challenge'])

                # return the signature to the router for verification
                return signature

            else:
                raise Exception("Invalid authmethod {}".format(
                    challenge.method))
Ejemplo n.º 37
0
    def onChallenge(self, challenge):
        if challenge.method == u"wampcra":
            out.verbose("WAMP-CRA challenge received: {}".format(challenge))

            wampPassword = nexus.core.getKey('apitoken')
            if u'salt' in challenge.extra:
                # salted secret
                key = auth.derive_key(wampPassword,
                                      challenge.extra['salt'],
                                      challenge.extra['iterations'],
                                      challenge.extra['keylen'])
            else:
                # plain, unsalted secret
                key = wampPassword

            # compute signature for challenge, using the key
            signature = auth.compute_wcs(key, challenge.extra['challenge'])

            # return the signature to the router for verification
            return signature

        else:
            raise Exception("Invalid authmethod {}".format(challenge.method))
#
###############################################################################

from os import environ
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks

from autobahn.twisted.wamp import Session, ApplicationRunner
from autobahn.wamp import auth

if False:
    # this is (one way) to get the encoded/salted secret to put in
    # config.json (see examples/router/.crossbar/config.json)
    print("encoded secret:", auth.derive_key(
        secret=u's33kr1t',
        salt=u'salt123',
        iterations=100,
        keylen=32,
    ).decode('ascii'))


class Component(Session):
    """
    An application component calling the different backend procedures.
    """

    def onJoin(self, details):
        print("session attached {}".format(details))
        return self.leave()


if __name__ == '__main__':
 def test_derive_key(self):
     secret = u'L3L1YUE8Txlw'
     salt = u'salt123'
     key = auth.derive_key(secret.encode('utf8'), salt.encode('utf8'))
     self.assertEqual(type(key), bytes)
     self.assertEqual(key, b"qzcdsr9uu/L5hnss3kjNTRe490ETgA70ZBaB5rvnJ5Y=")
Ejemplo n.º 40
0
 def test_derive_key(self):
     secret = 'L3L1YUE8Txlw'
     salt = 'salt123'
     key = auth.derive_key(secret.encode('utf8'), salt.encode('utf8'))
     self.assertEqual(type(key), bytes)
     self.assertEqual(key, b"qzcdsr9uu/L5hnss3kjNTRe490ETgA70ZBaB5rvnJ5Y=")
Ejemplo n.º 41
0
Archivo: wamp.py Proyecto: gchoi/VTK
 def updateKey(self, id, newKey):
     self._creds[id] = auth.derive_key(newKey, self.AUTHEXTRA['salt'])
Ejemplo n.º 42
0
from os import environ
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks

from autobahn.twisted.wamp import Session, ApplicationRunner
from autobahn.wamp import auth

if False:
    # this is (one way) to get the encoded/salted secret to put in
    # config.json (see examples/router/.crossbar/config.json)
    print(
        "encoded secret:",
        auth.derive_key(
            secret=u's33kr1t',
            salt=u'salt123',
            iterations=100,
            keylen=32,
        ).decode('ascii'))


class Component(Session):
    """
    An application component calling the different backend procedures.
    """
    def onJoin(self, details):
        print("session attached {}".format(details))
        return self.leave()


if __name__ == '__main__':
    runner = ApplicationRunner(
Ejemplo n.º 43
0
   def onHello(self, realm, details):

      try:

         ## check if the realm the session wants to join actually exists
         ##
         if realm not in self._router_factory:
            return types.Deny(ApplicationError.NO_SUCH_REALM, message = "no realm '{}' exists on this router".format(realm))

         ## perform authentication
         ##
         if self._transport._authid is not None:

            ## already authenticated .. e.g. via cookie

            ## check if role still exists on realm
            ##
            allow = self._router_factory[realm].has_role(self._transport._authrole)

            if allow:
               return types.Accept(authid = self._transport._authid,
                                   authrole = self._transport._authrole,
                                   authmethod = self._transport._authmethod,
                                   authprovider = 'transport')
            else:
               return types.Deny(ApplicationError.NO_SUCH_ROLE, message = "session was previously authenticated (via transport), but role '{}' no longer exists on realm '{}'".format(self._transport._authrole, realm))

         else:
            ## if authentication is enabled on the transport ..
            ##
            if "auth" in self._transport_config:

               ## iterate over authentication methods announced by client ..
               ##
               for authmethod in details.authmethods or ["anonymous"]:

                  ## .. and if the configuration has an entry for the authmethod
                  ## announced, process ..
                  if authmethod in self._transport_config["auth"]:

                     ## "WAMP-Challenge-Response" authentication
                     ##
                     if authmethod == u"wampcra":
                        cfg = self._transport_config['auth']['wampcra']

                        if cfg['type'] == 'static':
                           if details.authid in cfg.get('users', {}):
                              user = cfg['users'][details.authid]

                              ## when using salted passwords, computes a derived cryptographic key from a password according to PBKDF2.
                              if 'salt' in user:
                                 secret = auth.derive_key(
                                    user['secret'].encode('utf8'),
                                    user['salt'].encode('utf-8'),
                                    user.get('iterations', 1000),
                                    user.get('keylen', 32)).encode('utf-8')
                              else:
                                 secret = user['secret'].encode('utf-8')
                              self._pending_auth = PendingAuthWampCra(details.pending_session, details.authid, user['role'], u'static', secret)

                              ## send challenge to client
                              ##
                              extra = {
                                 u'challenge': self._pending_auth.challenge
                              }

                              ## when using salted passwords, provide the client with
                              ## the salt and then PBKDF2 parameters used
                              if 'salt' in user:
                                 extra[u'salt'] = user['salt']
                                 extra[u'iterations'] = user.get('iterations', 1000)
                                 extra[u'keylen'] = user.get('keylen', 32)

                              return types.Challenge(u'wampcra', extra)

                           else:
                              return types.Deny(message = "no user with authid '{}' in user database".format(details.authid))

                        elif cfg['type'] == 'dynamic':

                           ## Get the Crossbar.io service session on the router/realm
                           ## to issue the WAMP call to the custom authorizer
                           ##
                           router = self._router_factory.get(realm)
                           service_session = router._realm.session

                           d = service_session.call(cfg['authenticator'], realm, details.authid)

                           def on_authenticate_ok(user):

                              ## construct a pending WAMP-CRA authentication
                              ##
                              self._pending_auth = PendingAuthWampCra(details.pending_session, details.authid, user['role'], u'dynamic', user['secret'].encode('utf8'))

                              ## send challenge to client
                              ##
                              extra = {
                                 u'challenge': self._pending_auth.challenge
                              }

                              ## when using salted passwords, provide the client with
                              ## the salt and the PBKDF2 parameters used
                              ##
                              if 'salt' in user:
                                 extra[u'salt'] = user['salt']
                                 extra[u'iterations'] = user.get('iterations', 1000)
                                 extra[u'keylen'] = user.get('keylen', 32)

                              return types.Challenge(u'wampcra', extra)

                           def on_authenticate_error(err):
                              error = None
                              message = "dynamic WAMP-CRA credential getter failed: {}".format(err)

                              if isinstance(err.value, ApplicationError):
                                 error = err.value.error
                                 if err.value.args and len(err.value.args):
                                    message = err.value.args[0]

                              return types.Deny(error, message)


                           d.addCallbacks(on_authenticate_ok, on_authenticate_error)

                           return d

                        else:

                           return types.Deny(message = "illegal WAMP-CRA config (type '{0}' is unknown)".format(cfg['type']))

                     ## "Mozilla Persona" authentication
                     ##
                     elif authmethod == u"mozilla_persona":
                        cfg = self._transport_config['auth']['mozilla_persona']

                        audience = cfg.get('audience', self._transport._origin)
                        provider = cfg.get('provider', "https://verifier.login.persona.org/verify")

                        ## authrole mapping
                        ##
                        authrole = cfg.get('role', 'anonymous')

                        ## check if role exists on realm anyway
                        ##
                        if not self._router_factory[realm].has_role(authrole):
                           return types.Deny(ApplicationError.NO_SUCH_ROLE, message = "authentication failed - realm '{}' has no role '{}'".format(realm, authrole))

                        ## ok, now challenge the client for doing Mozilla Persona auth.
                        ##
                        self._pending_auth = PendingAuthPersona(provider, audience, authrole)
                        return types.Challenge("mozilla-persona")


                     ## "Anonymous" authentication
                     ##
                     elif authmethod == u"anonymous":
                        cfg = self._transport_config['auth']['anonymous']

                        ## authrole mapping
                        ##
                        authrole = cfg.get('role', 'anonymous')

                        ## check if role exists on realm anyway
                        ##
                        if not self._router_factory[realm].has_role(authrole):
                           return types.Deny(ApplicationError.NO_SUCH_ROLE, message = "authentication failed - realm '{}' has no role '{}'".format(realm, authrole))

                        ## authid generation
                        ##
                        if self._transport._cbtid:
                           ## if cookie tracking is enabled, set authid to cookie value
                           ##
                           authid = self._transport._cbtid
                        else:
                           ## if no cookie tracking, generate a random value for authid
                           ##
                           authid = util.newid(24)

                        self._transport._authid = authid
                        self._transport._authrole = authrole
                        self._transport._authmethod = authmethod

                        return types.Accept(authid = authid, authrole = authrole, authmethod = self._transport._authmethod)


                     ## "Cookie" authentication
                     ##
                     elif authmethod == u"cookie":
                        pass
                        # if self._transport._cbtid:
                        #    cookie = self._transport.factory._cookies[self._transport._cbtid]
                        #    authid = cookie['authid']
                        #    authrole = cookie['authrole']
                        #    authmethod = "cookie.{}".format(cookie['authmethod'])
                        #    return types.Accept(authid = authid, authrole = authrole, authmethod = authmethod)
                        # else:
                        #    return types.Deny()

                     else:
                        log.msg("unknown authmethod '{}'".format(authmethod))
                        return types.Deny(message = "unknown authentication method {}".format(authmethod))


               ## if authentication is configured, by default, deny.
               ##
               return types.Deny(message = "authentication using method '{}' denied by configuration".format(authmethod))


            else:
               ## if authentication is _not_ configured, by default, allow anyone.
               ##

               ## authid generation
               ##
               if self._transport._cbtid:
                  ## if cookie tracking is enabled, set authid to cookie value
                  ##
                  authid = self._transport._cbtid
               else:
                  ## if no cookie tracking, generate a random value for authid
                  ##
                  authid = util.newid(24)


               return types.Accept(authid = authid, authrole = "anonymous", authmethod = "anonymous")

      except Exception as e:
         traceback.print_exc()
         return types.Deny(message = "internal error: {}".format(e))
Ejemplo n.º 44
0
 def updateKey(self, id, newKey):
     self._creds[id] = auth.derive_key(newKey, self.AUTHEXTRA['salt'])
Ejemplo n.º 45
0
 def __init__(self):
     self._creds = {'vtkweb': auth.derive_key("vtkweb-secret", self.AUTHEXTRA['salt'])}
Ejemplo n.º 46
0
nlp_config["connection"]["secret"] = guest_secret

with open(jsfilename, "w") as f:
    json.dump(nlp_config, f, indent=2 * ' ', separators=(',', ':'))

# Replace user_data.json
with open(
        os.path.join(filepath,
                     "components/processor_component/data/user_data.json"),
        "r") as f:
    userdata = json.load(f)
username = config["USER"]["user"]
salt = config["USER"]["salt"]
secret = derive_key(
    secret=config["USER"]["secret"],
    salt=config["USER"]["salt"],
    iterations=userdata["_default"]["1"]["auth_details"]["iterations"],
    keylen=userdata["_default"]["1"]["auth_details"]["keylen"])

userdata["_default"]["1"]["auth_details"]["secret"] = secret
userdata["_default"]["1"]["auth_details"]["salt"] = salt
userdata["_default"]["1"]["username"] = username

secret = derive_key(
    secret=guest_secret,
    salt=guest_salt,
    iterations=userdata["_default"]["2"]["auth_details"]["iterations"],
    keylen=userdata["_default"]["2"]["auth_details"]["keylen"])
userdata["_default"]["2"]["auth_details"]["secret"] = secret
userdata["_default"]["2"]["auth_details"]["salt"] = guest_salt
userdata["_default"]["2"]["username"] = guest_user
Ejemplo n.º 47
0
Archivo: wamp.py Proyecto: gchoi/VTK
 def __init__(self):
     self._creds = {
         'vtkweb': auth.derive_key("vtkweb-secret", self.AUTHEXTRA['salt'])
     }