Exemplo n.º 1
0
def SessionPlugin_validateTicket(self, ticket, now=None):
    if now is None:
        now = time()
    if self._shared_secret is not None:
        ticket_data = tktauth.validateTicket(self._shared_secret,
                                             ticket,
                                             timeout=self.timeout,
                                             now=now,
                                             mod_auth_tkt=self.mod_auth_tkt)
    else:
        ticket_data = None
        parent = aq_parent(aq_parent(self))

        is_root = ICastleApplication.providedBy(parent)
        if is_root:
            manager = getGlobalSiteManager().queryUtility(IKeyManager)
        else:
            manager = queryUtility(IKeyManager)

        if manager is None:
            return None

        for secret in manager[u"_system"]:
            if secret is None:
                continue
            ticket_data = tktauth.validateTicket(
                secret,
                ticket,
                timeout=self.timeout,
                now=now,
                mod_auth_tkt=self.mod_auth_tkt)
            if ticket_data is not None:
                break
    return ticket_data
Exemplo n.º 2
0
 def _validateTicket(self, ticket, now=None):
     if now is None:
         now = time.time()
     if self._shared_secret is not None:
         ticket_data = tktauth.validateTicket(
             self._shared_secret,
             ticket,
             timeout=self.timeout,
             now=now,
             mod_auth_tkt=self.mod_auth_tkt)
     else:
         ticket_data = None
         manager = queryUtility(IKeyManager)
         if manager is None:
             return None
         for secret in manager[u"_system"]:
             if secret is None:
                 continue
             ticket_data = tktauth.validateTicket(
                 secret,
                 ticket,
                 timeout=self.timeout,
                 now=now,
                 mod_auth_tkt=self.mod_auth_tkt)
             if ticket_data is not None:
                 break
     return ticket_data
Exemplo n.º 3
0
 def _validateTicket(self, ticket, now=None):
     if now is None:
         now = time.time()
     if self._shared_secret is not None:
         ticket_data = tktauth.validateTicket(
             self._shared_secret,
             ticket,
             timeout=self.timeout,
             now=now,
             mod_auth_tkt=self.mod_auth_tkt
         )
     else:
         ticket_data = None
         manager = queryUtility(IKeyManager)
         if manager is None:
             return None
         for secret in manager[u"_system"]:
             if secret is None:
                 continue
             ticket_data = tktauth.validateTicket(
                 secret,
                 ticket,
                 timeout=self.timeout,
                 now=now,
                 mod_auth_tkt=self.mod_auth_tkt
             )
             if ticket_data is not None:
                 break
     return ticket_data
    def remember(self, environ, identity):
        if self.include_ip:
            remote_addr = environ['REMOTE_ADDR']
        else:
            remote_addr = '0.0.0.0'

        cookies = get_cookies(environ)
        old_cookie = cookies.get(self.cookie_name)
        existing = cookies.get(self.cookie_name)
        old_cookie_value = getattr(existing, 'value', None)

        timestamp, userid, tokens, userdata = None, '', (), ''

        if old_cookie_value:
            validation = validateTicket(self.secret, old_cookie_value,
                                        remote_addr, timeout=self.timeout,
                                        mod_auth_tkt=not self.enhanced_hashing)
            if validation:
                ignore, userid, tokens, user_data, timestamp = validation
            else:
                return
        tokens = tuple(tokens)

        who_userid = identity['repoze.who.userid']
        who_tokens = tuple(identity.get('tokens', ()))
        who_userdata = identity.get('userdata', '')

        who_userid = utf_8_encode(who_userid)[0]

        old_data = (userid, tokens, userdata)
        new_data = (who_userid, who_tokens, who_userdata)
    def identify(self, environ):
        cookies = get_cookies(environ)
        cookie = cookies.get(self.cookie_name)

        if cookie is None or not cookie.value:
            return None

        try:
            tkt = binascii.a2b_base64(urllib.unquote(cookie.value))
        except binascii.Error:
            return None

        if self.include_ip:
            remote_addr = environ['REMOTE_ADDR']
        else:
            remote_addr = '0.0.0.0'

        validation = validateTicket(self.secret, tkt, remote_addr,
                                    timeout=self.timeout,
                                    mod_auth_tkt=not self.enhanced_hashing)
        if validation:
            ignore, userid, tokens, user_data, timestamp = validation
        else:
            return None

        if cookie is None or not cookie.value:
            return None

        identity = {}
        identity['timestamp'] = timestamp
        identity['repoze.who.plugins.plone_session_tkt.userid'] = userid
        identity['tokens'] = tokens
        identity['userdata'] = user_data
        return identity
    def remember(self, environ, identity):
        if self.include_ip:
            remote_addr = environ['REMOTE_ADDR']
        else:
            remote_addr = '0.0.0.0'

        cookies = get_cookies(environ)
        old_cookie = cookies.get(self.cookie_name)
        existing = cookies.get(self.cookie_name)
        old_cookie_value = getattr(existing, 'value', None)

        timestamp, userid, tokens, userdata = None, '', (), ''

        if old_cookie_value:
            validation = validateTicket(self.secret,
                                        old_cookie_value,
                                        remote_addr,
                                        timeout=self.timeout,
                                        mod_auth_tkt=not self.enhanced_hashing)
            if validation:
                ignore, userid, tokens, user_data, timestamp = validation
            else:
                return
        tokens = tuple(tokens)

        who_userid = identity['repoze.who.userid']
        who_tokens = tuple(identity.get('tokens', ()))
        who_userdata = identity.get('userdata', '')

        who_userid = utf_8_encode(who_userid)[0]

        old_data = (userid, tokens, userdata)
        new_data = (who_userid, who_tokens, who_userdata)
Exemplo n.º 7
0
def SessionPlugin_validateTicket(self, ticket, now=None):
    if now is None:
        now = time()
    if self._shared_secret is not None:
        ticket_data = tktauth.validateTicket(
            self._shared_secret,
            ticket,
            timeout=self.timeout,
            now=now,
            mod_auth_tkt=self.mod_auth_tkt
        )
    else:
        ticket_data = None
        parent = aq_parent(aq_parent(self))

        is_root = ICastleApplication.providedBy(parent)
        if is_root:
            manager = getGlobalSiteManager().queryUtility(IKeyManager)
        else:
            manager = queryUtility(IKeyManager)

        if manager is None:
            return None

        try:
            for secret in manager[u"_system"]:
                if secret is None:
                    continue
                ticket_data = tktauth.validateTicket(
                    secret,
                    ticket,
                    timeout=self.timeout,
                    now=now,
                    mod_auth_tkt=self.mod_auth_tkt
                )
                if ticket_data is not None:
                    break
        except ConnectionStateError:
            logger.warning(
                'Connection state error, swallowing', exc_info=True)
    return ticket_data
Exemplo n.º 8
0
def decode(secret_key, urlsafe_string, timeout):
    """
    Decode the url safe string and validate with secret key and timeout
    Return tuple of email address and true if it is validate
    """
    now = time.time()
    if not hasattr(urlsafe_string, 'translate'):
        # IE8 passes the key twice in the request
        if hasattr(urlsafe_string[0], 'translate'):
            urlsafe_string = urlsafe_string[0]
    try:
        # What is the minimum we should try?
        ticket = base64.urlsafe_b64decode(urlsafe_string)
        (digest, email, tokens, user_data, timestamp) = tktauth.splitTicket(
            ticket)
        is_validate = tktauth.validateTicket(secret_key, ticket,
                                             timeout=timeout, now=now)
    except (ValueError, TypeError) as e:
        # Log what went wrong.
        email = None
        is_validate = None
    return email, is_validate is not None
    def identify(self, environ):
        cookies = get_cookies(environ)
        cookie = cookies.get(self.cookie_name)

        if cookie is None or not cookie.value:
            return None

        try:
            tkt = binascii.a2b_base64(urllib.unquote(cookie.value))
        except binascii.Error:
            return None

        if self.include_ip:
            remote_addr = environ['REMOTE_ADDR']
        else:
            remote_addr = '0.0.0.0'

        validation = validateTicket(self.secret,
                                    tkt,
                                    remote_addr,
                                    timeout=self.timeout,
                                    mod_auth_tkt=not self.enhanced_hashing)
        if validation:
            ignore, userid, tokens, user_data, timestamp = validation
        else:
            return None

        if cookie is None or not cookie.value:
            return None

        identity = {}
        identity['timestamp'] = timestamp
        identity['repoze.who.plugins.plone_session_tkt.userid'] = userid
        identity['tokens'] = tokens
        identity['userdata'] = user_data
        return identity
    def authenticateCredentials(self, credentials):
        """See IAuthenticationPlugin.

        This plugin will actually never authenticate.

        o We expect the credentials to be those returned by
          ILoginPasswordExtractionPlugin.
        """
        request = self.REQUEST
        alsoProvides(request, IDisableCSRFProtection)

        response = request['RESPONSE']
        pas_instance = self._getPAS()

        login = credentials.get('login')
        password = credentials.get('password')

        if None in (login, password, pas_instance) and (
                credentials.get('source') != 'plone.session'):
            return None
        else:
            session_source = self.session

            ticket = credentials.get('cookie')

            if session_source._shared_secret is not None:
                ticket_data = tktauth.validateTicket(
                    session_source._shared_secret,
                    ticket,
                    timeout=session_source.timeout,
                    mod_auth_tkt=session_source.mod_auth_tkt)
            else:
                ticket_data = None
                manager = queryUtility(IKeyManager)
                if manager is None:
                    return None
                for secret in manager[u"_system"]:
                    if secret is None:
                        continue

                    ticket_data = tktauth.validateTicket(
                        secret,
                        ticket,
                        timeout=session_source.timeout,
                        mod_auth_tkt=session_source.mod_auth_tkt)

                    if ticket_data is not None:
                        break

            if ticket_data is None:
                return None

            (digest, userid, tokens, user_data, timestamp) = ticket_data
            pas = self._getPAS()
            info = pas._verifyUser(pas.plugins, user_id=userid)

            if info is None:
                return None

            login = info['login']

        cookie_val = self.getCookie()

        # get max seats from member data property or cache and default to 1 if not set
        try:
            max_seats = self.getMaxSeatsForLogin(login)
        except:
            traceback.print_exc()

        # When debugging, print the maxSeats value that was resolved
        if self.DEBUG:
            print "authenticateCredentials():: Max Seats is " + str(max_seats)

        if max_seats == 1:
            if cookie_val:
                # A cookie value is there.  If it's the same as the value
                # in our mapping, it's fine.  Otherwise we'll force a
                # logout.
                existing = self.mapping1.get(login, None)

                if self.DEBUG:
                    if existing:
                        print "authenticateCredentials():: cookie_val is " + cookie_val + ", and active tokens are: " + ', '.join(
                            existing['tokens'])

                if existing and cookie_val not in existing['tokens']:
                    # The cookies values differ, we want to logout the
                    # user by calling resetCredentials.  Note that this
                    # will eventually call our own resetCredentials which
                    # will cleanup our own cookie.
                    try:
                        self.resetAllCredentials(request, response)
                        pas_instance.plone_utils.addPortalMessage(
                            _(u"Someone else logged in under your name.  You have been \
                            logged out"), "error")
                    except:
                        traceback.print_exc()
                elif existing is None:
                    # The browser has the cookie but we don't know about
                    # it.  Let's reset our own cookie:
                    self.setCookie('')

            else:
                # When no cookie is present, we generate one, store it and
                # set it in the response:
                cookie_val = uuid()
                # do some cleanup in our mappings
                existing = self.mapping1.get(login)

                if existing and 'tokens' in existing:
                    try:
                        if existing['tokens'][0] in self.mapping2:
                            del self.mapping2[existing['tokens'][0]]
                    except:
                        pass

                try:
                    from_ip = self.get_ip(request)
                except:
                    traceback.print_exc()

                now = DateTime()
                self.mapping1[login] = {'tokens': []}
                self.mapping1[login]['tokens'].append(cookie_val)
                self.mapping2[cookie_val] = {
                    'userid':
                    login,
                    'ip':
                    from_ip,
                    'startTime':
                    now,
                    'expireTime':
                    DateTime(now.asdatetime() + self.time_to_persist_cookies)
                }
                self.setCookie(cookie_val)
        else:
            # Max seats is not 1. Treat this as a floating licenses scenario.
            # Nobody is logged out, but once the max seats threshold is reached,
            # active tokens must expire before new users may log in.
            if cookie_val:
                # When the cookie value is there, try to verify it or activate it if is it not added yet
                self.verifyToken(cookie_val, login, max_seats, request,
                                 response)
            else:
                if self.DEBUG:
                    print "authenticateCredentials:: Try to issue a token because there is no cookie value."

                # When no cookie is present, attempt to issue a token and use the cookie to store it
                self.issueToken(login, max_seats, request, response)
                # if max_seats are filled, then force logout
                if self.isLoginAtCapacity(login, max_seats):
                    self.forceLogoutForUser(login, request, response)

        return None  # Note that we never return anything useful
Exemplo n.º 11
0
    def authenticateCredentials(self, credentials):
        """See IAuthenticationPlugin.

        This plugin will actually never authenticate.

        o We expect the credentials to be those returned by
          ILoginPasswordExtractionPlugin.
        """
        request = self.REQUEST
	alsoProvides(request, IDisableCSRFProtection)

        response = request['RESPONSE']
        pas_instance = self._getPAS()

        login = credentials.get('login')
        password = credentials.get('password')

        if None in (login, password, pas_instance) and (
            credentials.get('source') != 'plone.session'):
            return None
        else:
            session_source = self.session

            ticket = credentials.get('cookie')

            if session_source._shared_secret is not None:
                ticket_data = tktauth.validateTicket(
                    session_source._shared_secret, ticket,
                    timeout=session_source.timeout,
                    mod_auth_tkt=session_source.mod_auth_tkt)
            else:
                ticket_data = None
                manager = queryUtility(IKeyManager)
                if manager is None:
                    return None
                for secret in manager[u"_system"]:
                    if secret is None:
                        continue

                    ticket_data = tktauth.validateTicket(secret, ticket,
                        timeout=session_source.timeout,
                        mod_auth_tkt=session_source.mod_auth_tkt)

                    if ticket_data is not None:
                        break

            if ticket_data is None:
                return None

            (digest, userid, tokens, user_data, timestamp) = ticket_data
            pas = self._getPAS()
            info = pas._verifyUser(pas.plugins, user_id=userid)

            if info is None:
                return None

            login = info['login']

        cookie_val = self.getCookie()
        
        # get max seats from member data property or cache and default to 1 if not set
        try:
            max_seats = self.getMaxSeatsForLogin(login)
        except:
            traceback.print_exc()

        # When debugging, print the maxSeats value that was resolved
        if self.DEBUG:
            print "authenticateCredentials():: Max Seats is " + str( max_seats )

        if max_seats == 1:
            if cookie_val:
                # A cookie value is there.  If it's the same as the value
                # in our mapping, it's fine.  Otherwise we'll force a
                # logout.
                existing = self.mapping1.get(login, None)
                
                if self.DEBUG:
                    if existing:
                        print "authenticateCredentials():: cookie_val is " + cookie_val + ", and active tokens are: " + ', '.join( existing['tokens'] )
                
                if existing and cookie_val not in existing['tokens']:
                    # The cookies values differ, we want to logout the
                    # user by calling resetCredentials.  Note that this
                    # will eventually call our own resetCredentials which
                    # will cleanup our own cookie.
                    try:
                        self.resetAllCredentials(request, response)
                        pas_instance.plone_utils.addPortalMessage(_(
                            u"Someone else logged in under your name.  You have been \
                            logged out"), "error")
                    except:
                        traceback.print_exc()
                elif existing is None:
                    # The browser has the cookie but we don't know about
                    # it.  Let's reset our own cookie:
                    self.setCookie('')
    
            else:
                # When no cookie is present, we generate one, store it and
                # set it in the response:
                cookie_val = uuid()
                # do some cleanup in our mappings
                existing = self.mapping1.get(login)
                
                if existing and 'tokens' in existing:
                    try:
                        if existing['tokens'][0] in self.mapping2:
                            del self.mapping2[existing['tokens'][0]]
                    except:
                        pass
    
                try:
                    from_ip = self.get_ip( request )
                except:
                    traceback.print_exc()

                now = DateTime()
                self.mapping1[login] = { 'tokens':[] }
                self.mapping1[login]['tokens'].append( cookie_val )
                self.mapping2[cookie_val] = {'userid': login, 'ip': from_ip, 'startTime': now, 'expireTime': DateTime( now.asdatetime() + self.time_to_persist_cookies )}
                self.setCookie(cookie_val)
        else:
            # Max seats is not 1. Treat this as a floating licenses scenario.
            # Nobody is logged out, but once the max seats threshold is reached,
            # active tokens must expire before new users may log in.
            if cookie_val:
                # When the cookie value is there, try to verify it or activate it if is it not added yet
                self.verifyToken( cookie_val, login, max_seats, request, response )
            else:
                if self.DEBUG:
                    print "authenticateCredentials:: Try to issue a token because there is no cookie value."
                    
                # When no cookie is present, attempt to issue a token and use the cookie to store it
                self.issueToken(login, max_seats, request, response)
                # if max_seats are filled, then force logout
                if self.isLoginAtCapacity(login, max_seats):
                    self.forceLogoutForUser(login, request, response)
    
        return None  # Note that we never return anything useful