コード例 #1
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        print "U2F. prepareForStep called for step %s" % step
        identity = CdiUtil.bean(Identity)

        if (step == 1):
            session_id = CdiUtil.bean(
                SessionIdService).getSessionIdFromCookie()
            if StringHelper.isEmpty(session_id):
                print "U2F. Prepare for step 1. Failed to determine session_id"
                return False

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "U2F. Prepare for step 1. Failed to determine user name"
                return False

            u2f_application_id = configurationAttributes.get(
                "u2f_application_id").getValue2()

            # Check if user have registered devices
            deviceRegistrationService = CdiUtil.bean(DeviceRegistrationService)

            userInum = user.getAttribute("inum")

            registrationRequest = None
            authenticationRequest = None

            deviceRegistrations = deviceRegistrationService.findUserDeviceRegistrations(
                userInum, u2f_application_id)
            if (deviceRegistrations.size() > 0):
                print "U2F. Prepare for step 1. Call FIDO U2F in order to start authentication workflow"

                try:
                    authenticationRequestService = FidoU2fClientFactory.instance(
                    ).createAuthenticationRequestService(
                        self.metaDataConfiguration)
                    authenticationRequest = authenticationRequestService.startAuthentication(
                        user.getUserId(), None, u2f_application_id, session_id)
                except ClientResponseFailure, ex:
                    if (ex.getResponse().getResponseStatus() !=
                            Response.Status.NOT_FOUND):
                        print "U2F. Prepare for step 1. Failed to start authentication workflow. Exception:", sys.exc_info(
                        )[1]
                        return False
            else:
                print "U2F. Prepare for step 1. Call FIDO U2F in order to start registration workflow"
                registrationRequestService = FidoU2fClientFactory.instance(
                ).createRegistrationRequestService(self.metaDataConfiguration)
                registrationRequest = registrationRequestService.startRegistration(
                    user.getUserId(), u2f_application_id, session_id)

            identity.setWorkingParameter(
                "fido_u2f_authentication_request",
                ServerUtil.asJson(authenticationRequest))
            identity.setWorkingParameter(
                "fido_u2f_registration_request",
                ServerUtil.asJson(registrationRequest))

            return True
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)

        if (step == 1):
            return True
        elif (step == 2):
            print "U2F. Prepare for step 2"

            session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie()
            if StringHelper.isEmpty(session_id):
                print "U2F. Prepare for step 2. Failed to determine session_id"
                return False

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "U2F. Prepare for step 2. Failed to determine user name"
                return False

            u2f_application_id = configurationAttributes.get("u2f_application_id").getValue2()

            # Check if user have registered devices
            deviceRegistrationService = CdiUtil.bean(DeviceRegistrationService)

            userInum = user.getAttribute("inum")

            registrationRequest = None
            authenticationRequest = None

            deviceRegistrations = deviceRegistrationService.findUserDeviceRegistrations(userInum, u2f_application_id)
            if (deviceRegistrations.size() > 0):
                print "U2F. Prepare for step 2. Call FIDO U2F in order to start authentication workflow"

                try:
                    authenticationRequestService = FidoU2fClientFactory.instance().createAuthenticationRequestService(self.metaDataConfiguration)
                    authenticationRequest = authenticationRequestService.startAuthentication(user.getUserId(), None, u2f_application_id, session_id)
                except ClientResponseFailure, ex:
                    if (ex.getResponse().getResponseStatus() != Response.Status.NOT_FOUND):
                        print "U2F. Prepare for step 2. Failed to start authentication workflow. Exception:", sys.exc_info()[1]
                        return False
            else:
                print "U2F. Prepare for step 2. Call FIDO U2F in order to start registration workflow"
                registrationRequestService = FidoU2fClientFactory.instance().createRegistrationRequestService(self.metaDataConfiguration)
                registrationRequest = registrationRequestService.startRegistration(user.getUserId(), u2f_application_id, session_id)

            identity.setWorkingParameter("fido_u2f_authentication_request", ServerUtil.asJson(authenticationRequest))
            identity.setWorkingParameter("fido_u2f_registration_request", ServerUtil.asJson(registrationRequest))

            return True
コード例 #3
0
    def validateRecaptcha(self, recaptcha_response):
        print "Cert. Validate recaptcha response"

        facesContext = CdiUtil.bean(FacesContext)
        request = facesContext.getExternalContext().getRequest()

        remoteip = ServerUtil.getIpAddress(request)
        print "Cert. Validate recaptcha response. remoteip: '%s'" % remoteip

        httpService = CdiUtil.bean(HttpService)

        http_client = httpService.getHttpsClient()
        http_client_params = http_client.getParams()
        http_client_params.setIntParameter(
            CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000)

        recaptcha_validation_url = "https://www.google.com/recaptcha/api/siteverify"
        recaptcha_validation_request = urllib.urlencode({
            "secret":
            self.recaptcha_creds['secret_key'],
            "response":
            recaptcha_response,
            "remoteip":
            remoteip
        })
        recaptcha_validation_headers = {
            "Content-type": "application/x-www-form-urlencoded",
            "Accept": "application/json"
        }

        try:
            http_service_response = httpService.executePost(
                http_client, recaptcha_validation_url, None,
                recaptcha_validation_headers, recaptcha_validation_request)
            http_response = http_service_response.getHttpResponse()
        except:
            print "Cert. Validate recaptcha response. Exception: ", sys.exc_info(
            )[1]
            return False

        try:
            if not httpService.isResponseStastusCodeOk(http_response):
                print "Cert. Validate recaptcha response. Get invalid response from validation server: ", str(
                    http_response.getStatusLine().getStatusCode())
                httpService.consume(http_response)
                return False

            response_bytes = httpService.getResponseContent(http_response)
            response_string = httpService.convertEntityToString(response_bytes)
            httpService.consume(http_response)
        finally:
            http_service_response.closeConnection()

        if response_string == None:
            print "Cert. Validate recaptcha response. Get empty response from validation server"
            return False

        response = json.loads(response_string)

        return response["success"]
コード例 #4
0
ファイル: register.py プロジェクト: kdhttps/jans-auth-server
 def getUserValueFromAuth(self, remote_attr, requestParameters):
     try:
         toBeFeatched = "loginForm:" + remote_attr
         return ServerUtil.getFirstValue(requestParameters, toBeFeatched)
     except Exception, err:
         print("Registration: Exception inside getUserValueFromAuth " +
               str(err))
コード例 #5
0
ファイル: Mfa.py プロジェクト: sign-in-canada/MFA
    def authenticateRecoveryCode(self,requestParameters, username, identity):
        # Inject dependencies
        userService = CdiUtil.bean(UserService)
        authenticationProtectionService = CdiUtil.bean(AuthenticationProtectionService)
        facesMessages = CdiUtil.bean(FacesMessages)
        languageBean = CdiUtil.bean(LanguageBean)

        if (authenticationProtectionService.isEnabled()):
            authenticationProtectionService.doDelayIfNeeded(username)

        recoveryCode = ServerUtil.getFirstValue(requestParameters, "Recover:recoveryCode")

        user = userService.getUser(username, "secretAnswer")
        secretAnswers = userService.getCustomAttribute(user, "secretAnswer")

        if (secretAnswers is not None):
            for secretAnswer in secretAnswers.getValues():
                code = self.decryptAES(self.aesKey, secretAnswer)
                if (StringHelper.equals(code, recoveryCode)):
                    if (authenticationProtectionService.isEnabled()):
                        authenticationProtectionService.storeAttempt(username, True)
                    return True

        if (authenticationProtectionService.isEnabled()):
            authenticationProtectionService.storeAttempt(username, False)

        facesMessages.add( FacesMessage.SEVERITY_ERROR, languageBean.getMessage("mfa.invalidRecoveryCode"))
        return False
コード例 #6
0
ファイル: Mfa.py プロジェクト: sign-in-canada/MFA
 def prepareFidoAuthentication(self, username, identity):
     authenticationRequestService = FidoU2fClientFactory.instance().createAuthenticationRequestService(self.metaDataConfiguration)
     session = identity.getSessionId()
     
     identity.getSessionId().getSessionAttributes().put(Constants.AUTHENTICATED_USER, username)
     authenticationRequest = authenticationRequestService.startAuthentication(username, None, self.u2fApplicationId, session.getId())
     identity.setWorkingParameter("fido_u2f_authentication_request", ServerUtil.asJson(authenticationRequest))
コード例 #7
0
    def authenticateFido2(self, userId, requestParameters):

        if REMOTE_DEBUG:
            pydevd.settrace('localhost',
                            port=5678,
                            stdoutToServer=True,
                            stderrToServer=True)

        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)
        identity = CdiUtil.bean(Identity)
        session = identity.getSessionId()

        tokenResponse = ServerUtil.getFirstValue(requestParameters,
                                                 "fido2Authentication")
        print("%s. Authenticate. Got fido2 authentication response: %s" %
              (self.name, tokenResponse))
        metaDataConfiguration = self.getFidoMetaDataConfiguration()
        assertionService = Fido2ClientFactory.instance(
        ).createAssertionService(metaDataConfiguration)
        assertionStatus = assertionService.verify(tokenResponse)
        authenticationStatusEntity = assertionStatus.readEntity(
            java.lang.String)

        if assertionStatus.getStatus() != Response.Status.OK.getStatusCode():
            print(
                "%s. Authenticate. Got invalid authentication status from Fido2 server"
                % self.name)
            return False

        return authenticationService.authenticate(
            identity.getWorkingParameter("userId"))
コード例 #8
0
    def authenticate(self, configuration_attributes, request_parameters, step):
        print "ThumbSignIn. Inside authenticate. Step %d" % step
        authentication_service = CdiUtil.bean(AuthenticationService)
        identity = CdiUtil.bean(Identity)

        identity.setWorkingParameter("ts_host", ts_host)
        identity.setWorkingParameter("ts_statusPath", ts_statusPath)

        if step == 1 or step == 3:
            print "ThumbSignIn. Authenticate for Step %d" % step

            login_flow = ServerUtil.getFirstValue(request_parameters,
                                                  "login_flow")
            print "ThumbSignIn. Value of login_flow parameter is %s" % login_flow

            # Logic for ThumbSignIn Authentication Flow (Either step 1 or step 3)
            if login_flow == THUMBSIGNIN_AUTHENTICATION or login_flow == THUMBSIGNIN_LOGIN_POST_REGISTRATION:
                identity.setWorkingParameter(USER_LOGIN_FLOW, login_flow)
                print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(
                    USER_LOGIN_FLOW)
                logged_in_status = authentication_service.authenticate(
                    self.get_user_id_from_thumbsignin(request_parameters))
                print "ThumbSignIn. logged_in status : %r" % logged_in_status
                return logged_in_status

            # Logic for traditional login flow (step 1)
            print "ThumbSignIn. User credentials login flow"
            identity.setWorkingParameter(USER_LOGIN_FLOW,
                                         THUMBSIGNIN_REGISTRATION)
            print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(
                USER_LOGIN_FLOW)
            logged_in = self.authenticate_user_credentials(
                identity, authentication_service)
            print "ThumbSignIn. Status of User Credentials based Authentication : %r" % logged_in

            # When the traditional login fails, reinitialize the ThumbSignIn data before sending error response to UI
            if not logged_in:
                self.initialize_thumbsignin(identity, AUTHENTICATE)
                return False

            print "ThumbSignIn. Authenticate successful for step %d" % step
            return True

        elif step == 2:
            print "ThumbSignIn. Registration flow (step 2)"
            self.verify_user_login_flow(identity)

            user = self.get_authenticated_user_from_gluu(
                authentication_service)
            if user is None:
                print "ThumbSignIn. Registration flow (step 2). Failed to determine user name"
                return False

            user_name = user.getUserId()
            print "ThumbSignIn. Registration flow (step 2) successful. user_name: %s" % user_name
            return True

        else:
            return False
コード例 #9
0
    def parsePlatformData(self, requestParameters):
        try:
            #Find device info passed in HTTP request params (see index.xhtml)
            platform = ServerUtil.getFirstValue(requestParameters, "loginForm:platform")
            deviceInf = json.loads(platform)
        except:
            print "Casa. parsePlatformData. Error parsing platform data"
            deviceInf = None

        return deviceInf
コード例 #10
0
    def parsePlatformData(self, requestParameters):
        try:
            #Find device info passed in HTTP request params (see index.xhtml)
            platform = ServerUtil.getFirstValue(requestParameters, "loginForm:platform")
            deviceInf = json.loads(platform)
        except:
            print "Casa. parsePlatformData. Error parsing platform data"
            deviceInf = None

        return deviceInf
コード例 #11
0
    def getCodeFromRequest(self, requestParameters):
        print "MFA Recovery. getCodeFromRequest called"
        try:
            toBeFetched1 = "loginForm:recoveryCode1"
            toBeFetched2 = "loginForm:recoveryCode2"
            toBeFetched3 = "loginForm:recoveryCode3"
            code1 = ServerUtil.getFirstValue(requestParameters, toBeFetched1)
            code2 = ServerUtil.getFirstValue(requestParameters, toBeFetched2)
            code3 = ServerUtil.getFirstValue(requestParameters, toBeFetched3)

            print "MFA Recovery. getCodeFromRequest: fetched loginForm:recoveryCode(s) '%s-%s-%s'" % (
                code1, code2, code3)
            if StringHelper.isNotEmpty(code1) and StringHelper.isNotEmpty(
                    code2) and StringHelper.isNotEmpty(code3):
                code = "%s-%s-%s" % (code1, code2, code3)
                return code
            return Null
        except Exception, err:
            print("MFA Recovery. getCodeFromRequest Exception: " + str(err))
    def get_user_id_from_thumbsignin(self, request_parameters):
        transaction_id = ServerUtil.getFirstValue(request_parameters, TRANSACTION_ID)
        print "ThumbSignIn. Value of transaction_id is %s" % transaction_id
        get_user_request = "getUser/" + transaction_id
        print "ThumbSignIn. Value of get_user_request is %s" % get_user_request

        get_user_response = self.thumbsigninApiController.handleThumbSigninRequest(get_user_request, ts_api_key, ts_api_secret)
        print "ThumbSignIn. Value of get_user_response is %s" % get_user_response
        get_user_response_json = JSONObject(get_user_response)
        thumbsignin_user_id = get_user_response_json.get(USER_ID)
        print "ThumbSignIn. Value of thumbsignin_user_id is %s" % thumbsignin_user_id
        return thumbsignin_user_id
コード例 #13
0
ファイル: MfaNewSelection.py プロジェクト: sign-in-canada/MFA
    def authenticate(self, configurationAttributes, requestParameters, step):
        print "MFA Chooser. authenticate called for step '%s'" % step

        identity = CdiUtil.bean(Identity)

        # What option did they choose?
        choice = ServerUtil.getFirstValue(requestParameters,
                                          "loginForm:mfachoice")
        print "MFA Chooser. Authenticate: %s selected." % choice
        identity.setWorkingParameter("authenticatorType", choice)

        return False
コード例 #14
0
    def getNextStep(self, configurationAttributes, requestParameters, step):

        print "Casa. getNextStep called %s" % str(step)
        if step > 1:
            acr = ServerUtil.getFirstValue(requestParameters, "alternativeMethod")
            if acr != None:
                print "Casa. getNextStep. Use alternative method %s" % acr
                CdiUtil.bean(Identity).setWorkingParameter("ACR", acr)
                #retry step with different acr
                return 2

        return -1
コード例 #15
0
    def get_user_id_from_thumbsignin(self, request_parameters):
        transaction_id = ServerUtil.getFirstValue(request_parameters, TRANSACTION_ID)
        print "ThumbSignIn. Value of transaction_id is %s" % transaction_id
        get_user_request = "getUser/" + transaction_id
        print "ThumbSignIn. Value of get_user_request is %s" % get_user_request

        get_user_response = self.thumbsigninApiController.handleThumbSigninRequest(get_user_request, ts_api_key, ts_api_secret)
        print "ThumbSignIn. Value of get_user_response is %s" % get_user_response
        get_user_response_json = JSONObject(get_user_response)
        thumbsignin_user_id = get_user_response_json.get(USER_ID)
        print "ThumbSignIn. Value of thumbsignin_user_id is %s" % thumbsignin_user_id
        return thumbsignin_user_id
コード例 #16
0
    def getNextStep(self, configurationAttributes, requestParameters, step):

        print "Casa. getNextStep called %s" % str(step)
        if step > 1:
            acr = ServerUtil.getFirstValue(requestParameters, "alternativeMethod")
            if acr != None:
                print "Casa. getNextStep. Use alternative method %s" % acr
                CdiUtil.bean(Identity).setWorkingParameter("ACR", acr)
                #retry step with different acr
                return 2

        return -1
    def authenticate(self, configuration_attributes, request_parameters, step):
        print "ThumbSignIn. Inside authenticate. Step %d" % step
        authentication_service = CdiUtil.bean(AuthenticationService)
        identity = CdiUtil.bean(Identity)

        identity.setWorkingParameter("ts_host", ts_host)
        identity.setWorkingParameter("ts_statusPath", ts_statusPath)

        if step == 1 or step == 3:
            print "ThumbSignIn. Authenticate for Step %d" % step

            login_flow = ServerUtil.getFirstValue(request_parameters, "login_flow")
            print "ThumbSignIn. Value of login_flow parameter is %s" % login_flow

            # Logic for ThumbSignIn Authentication Flow (Either step 1 or step 3)
            if login_flow == THUMBSIGNIN_AUTHENTICATION or login_flow == THUMBSIGNIN_LOGIN_POST_REGISTRATION:
                identity.setWorkingParameter(USER_LOGIN_FLOW, login_flow)
                print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(USER_LOGIN_FLOW)
                logged_in_status = authentication_service.authenticate(self.get_user_id_from_thumbsignin(request_parameters))
                print "ThumbSignIn. logged_in status : %r" % logged_in_status
                return logged_in_status

            # Logic for traditional login flow (step 1)
            print "ThumbSignIn. User credentials login flow"
            identity.setWorkingParameter(USER_LOGIN_FLOW, THUMBSIGNIN_REGISTRATION)
            print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(USER_LOGIN_FLOW)
            logged_in = self.authenticate_user_credentials(identity, authentication_service)
            print "ThumbSignIn. Status of User Credentials based Authentication : %r" % logged_in

            # When the traditional login fails, reinitialize the ThumbSignIn data before sending error response to UI
            if not logged_in:
                self.initialize_thumbsignin(identity, AUTHENTICATE)
                return False

            print "ThumbSignIn. Authenticate successful for step %d" % step
            return True

        elif step == 2:
            print "ThumbSignIn. Registration flow (step 2)"
            self.verify_user_login_flow(identity)

            user = self.get_authenticated_user_from_gluu(authentication_service)
            if user is None:
                print "ThumbSignIn. Registration flow (step 2). Failed to determine user name"
                return False

            user_name = user.getUserId()
            print "ThumbSignIn. Registration flow (step 2) successful. user_name: %s" % user_name
            return True

        else:
            return False
コード例 #18
0
ファイル: MfaNewSelection.py プロジェクト: sign-in-canada/MFA
    def getMfaValueFromAuth(self, requestParameters):
        print "MFA Chooser. getMfaValueFromAuth called"
        try:
            toBeFeatched = "loginForm:mfachoice"
            print "MFA Chooser. getMfaValueFromAuth: fetching '%s'" % toBeFeatched
            new_acr_value = ServerUtil.getFirstValue(requestParameters,
                                                     toBeFeatched)

            print "MFA Chooser. getMfaValueFromAuth: fetched new_acr_value '%s'" % new_acr_value
            if StringHelper.isNotEmpty(new_acr_value):
                return new_acr_value
            return Null
        except Exception, err:
            print("MFA Chooser. getMfaValueFromAuth Exception: " + str(err))
コード例 #19
0
    def getAcrValueFromAuth(self, requestParameters):
        print "IDP Chooser. getAcrValueFromAuth called"
        try:
            toBeFeatched = "loginForm:acrname"
            print "IDP Chooser. getAcrValueFromAuth: fetching '%s'" % toBeFeatched
            new_acr_provider_value = ServerUtil.getFirstValue(
                requestParameters, toBeFeatched)

            print "IDP Chooser. getAcrValueFromAuth: fetched new_acr_provider_value '%s'" % new_acr_provider_value
            if StringHelper.isNotEmpty(new_acr_provider_value):
                return new_acr_provider_value
            return None
        except Exception, err:
            print("IDP Chooser. getAcrValueFromAuth Exception: " + str(err))
コード例 #20
0
    def getSwitchValueFromAuth(self, requestParameters):
        print "IDP Chooser. getSwitchValueFromAuth called"
        try:
            switchCredential = "loginForm:switchCredentialBox"
            print "IDP Chooser. getSwitchValueFromAuth: fetching '%s'" % switchCredential
            switch_credential_selected = ServerUtil.getFirstValue(
                requestParameters, switchCredential)

            print "IDP Chooser. getSwitchValueFromAuth: fetched switch_credential_selected = '%s'" % switch_credential_selected
            if switch_credential_selected == "on":
                return True
            return False
        except Exception, err:
            print("IDP Chooser. getSwitchValueFromAuth Exception: " + str(err))
コード例 #21
0
    def alternateActionRequested(self, requestParameters):
        print "MFA Enroll Recovery. alternateActionRequested called"
        try:
            toBeFetched = "loginForm:action"
            print "MFA Enroll Recovery. alternateActionRequested: fetching '%s'" % toBeFetched
            action_value = ServerUtil.getFirstValue(requestParameters, toBeFetched)

            print "MFA Enroll Recovery. alternateActionRequested: fetched action_value '%s'" % action_value
            if ( StringHelper.isNotEmpty(action_value) ):
                return action_value
            return None
        except Exception, err:
            print("MFA Enroll Recovery. alternateActionRequested Exception: " + str(err))
            return None
コード例 #22
0
ファイル: Mfa.py プロジェクト: sign-in-canada/MFA
    def authenticateTOTP(self, requestParameters, username, identity):
        print "MFA. authenticateTOTP called"

        # Inject dependencies
        facesMessages = CdiUtil.bean(FacesMessages)
        languageBean = CdiUtil.bean(LanguageBean)
        userService = CdiUtil.bean(UserService)
        authenticationProtectionService = CdiUtil.bean(AuthenticationProtectionService)

        facesMessages.setKeepMessages()

        if (authenticationProtectionService.isEnabled()):
            authenticationProtectionService.doDelayIfNeeded(username)

        totpCode = ServerUtil.getFirstValue(requestParameters, "TOTPauthenticate:totpCode")
        # Do some basic input validation
        if (totpCode is None or len(totpCode) != 6 or not totpCode.isdigit()):
            facesMessages.add(FacesMessage.SEVERITY_ERROR, languageBean.getMessage("mfa.otpInvalid"))
            return False

        # Find the user, retrieve and decrypt their TOTP code
        user = userService.getUser(username, "oxExternalUid")
        if (user is None):
            print "MFA. authenticateTOTP. Failed to find user"
            identity.setWorkingParameter("nextStep", -1) # Error page
            return True

        externalUids = userService.getCustomAttribute(user, "oxExternalUid")
        if (externalUids is not None):
            for externalUid in externalUids.getValues():
                if (externalUid.startswith("totp:")):
                    secretKey = self.decryptAES(self.aesKey, externalUid[5:])
                    break
        
        if (secretKey is None):
            print "MFA. authenticateTOTP. Failed to find TOTP secret"
            identity.setWorkingParameter("nextStep", -1) # Error page
            return True

        # Authenticate the TOTP code
        if (not self.validateTotpKey(self.fromBase64Url(secretKey), totpCode)):
            facesMessages.add(FacesMessage.SEVERITY_ERROR, languageBean.getMessage("mfa.otpInvalid"))
            if (authenticationProtectionService.isEnabled()):
                authenticationProtectionService.storeAttempt(username, False)
            return False

        if (authenticationProtectionService.isEnabled()):
            authenticationProtectionService.storeAttempt(username, True)
        return True
コード例 #23
0
ファイル: Mfa.py プロジェクト: sign-in-canada/MFA
    def registerFIDO(self, requestParameters, username, identity):
        print "MFA. registerFIDO called"

        registrationRequestService = FidoU2fClientFactory.instance().createRegistrationRequestService(self.metaDataConfiguration)

        token_response = ServerUtil.getFirstValue(requestParameters, "tokenResponse")
        registrationStatus = registrationRequestService.finishRegistration(username, token_response)

        if (registrationStatus.getStatus() != Constants.RESULT_SUCCESS):
            print "MFA. Register FIDO. Failed to register U2F device"
            identity.setWorkingParameter("flow", "Error") # Trigger the error page
            return False
        
        self.deleteTOTP(username, identity)
        return True
    def validateRecaptcha(self, recaptcha_response):
        print "Cert. Validate recaptcha response"

        facesContext = CdiUtil.bean(FacesContext)
        request = facesContext.getExternalContext().getRequest()

        remoteip = ServerUtil.getIpAddress(request)
        print "Cert. Validate recaptcha response. remoteip: '%s'" % remoteip

        httpService = CdiUtil.bean(HttpService)

        http_client = httpService.getHttpsClient()
        http_client_params = http_client.getParams()
        http_client_params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000)
        
        recaptcha_validation_url = "https://www.google.com/recaptcha/api/siteverify"
        recaptcha_validation_request = urllib.urlencode({ "secret" : self.recaptcha_creds['secret_key'], "response" : recaptcha_response, "remoteip" : remoteip })
        recaptcha_validation_headers = { "Content-type" : "application/x-www-form-urlencoded", "Accept" : "application/json" }

        try:
            http_service_response = httpService.executePost(http_client, recaptcha_validation_url, None, recaptcha_validation_headers, recaptcha_validation_request)
            http_response = http_service_response.getHttpResponse()
        except:
            print "Cert. Validate recaptcha response. Exception: ", sys.exc_info()[1]
            return False

        try:
            if not httpService.isResponseStastusCodeOk(http_response):
                print "Cert. Validate recaptcha response. Get invalid response from validation server: ", str(http_response.getStatusLine().getStatusCode())
                httpService.consume(http_response)
                return False
    
            response_bytes = httpService.getResponseContent(http_response)
            response_string = httpService.convertEntityToString(response_bytes)
            httpService.consume(http_response)
        finally:
            http_service_response.closeConnection()

        if response_string == None:
            print "Cert. Validate recaptcha response. Get empty response from validation server"
            return False
        
        response = json.loads(response_string)
        
        return response["success"]
コード例 #25
0
    def handleResponse(self, requestParameters):
        """Process an authentication response from passport. Returns a User object, or None in case of failure."""

        jwt = None
        externalProfile = None
        try:
            # gets jwt parameter "user" sent after authentication by passport (if exists)
            jwt_param = ServerUtil.getFirstValue(requestParameters, "user")

            # Parse JWT and validate
            # TODO: Log a security event whenever JWT validation fails
            jwt = Jwt.parse(jwt_param)
            if not self.verifySignature(jwt):
                return None
            if self.jwtHasExpired(jwt):
                return None

            claims = jwt.getClaims()
            externalProfileJson = CdiUtil.bean(EncryptionService).decrypt(
                claims.getClaimAsString("data"))
            externalProfile = json.loads(externalProfileJson)

            providerId = externalProfile["provider"]
            providerConfig = self.registeredProviders.get(providerId)
            providerType = providerConfig["type"]

            sub = claims.getClaimAsString("sub")
            if providerType == "saml":  # This is silly. It should be consistent.
                externalProfile["externalUid"] = "passport-saml:%s:%s" % (
                    providerId, sub)
            else:
                externalProfile["externalUid"] = "passport-%s:%s" % (
                    providerId, sub)

        except:
            print("Passport. handleResponse. Invalid JWT from passport")
            return None

        return externalProfile
コード例 #26
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        print "MFA Enroll Recovery. authenticate called for step '%s'" % step

        # if it's the confirmation page then just get on with it and finish
        if (step == 2):
            return True

        identity = CdiUtil.bean(Identity)
        # For authentication then check if someone enrolling clicked CANCEL button
        alternateAction = self.alternateActionRequested(requestParameters)
        if ( alternateAction == 'cancel'):
            identity.getSessionId().getSessionAttributes().put("authenticationFlow", "RESTART_ENROLLMENT")
            CdiUtil.bean(SessionIdService).updateSessionId( identity.getSessionId() )
            return True

        ########################################################################################
        # 1. Make sure we have a session and a user with no existing codes in the profile
        session_id_validation = self.validateSessionId(identity)
        if not session_id_validation:
            print "MFA Enroll Recovery. prepareForStep for step %s. Failed to validate session state" % step
            return False

        authenticationService = CdiUtil.bean(AuthenticationService)
        authenticated_user = authenticationService.getAuthenticatedUser()

        if authenticated_user == None:
            print "MFA Enroll Recovery. prepareForStep. Failed to determine authenticated user from previous module"
            return False

        ########################################################################################
        # 2. Get the confirmation checkbox value
        confirmCodeBox = None
        try:
            toBeFeatched = "loginForm:confirmCodeBox"
            print "MFA Enroll Recovery. authenticate: fetching '%s'" % toBeFeatched
            confirmCodeBox = ServerUtil.getFirstValue(requestParameters, toBeFeatched)
        except Exception, err:
            print("MFA Enroll Recovery. authenticate Exception getting form checkbox: " + str(err))
コード例 #27
0
ファイル: Mfa.py プロジェクト: sign-in-canada/MFA
    def authenticateFIDO(self, requestParameters, username, identity):
        facesMessages = CdiUtil.bean(FacesMessages)
        languageBean = CdiUtil.bean(LanguageBean)
        authenticationProtectionService = CdiUtil.bean(AuthenticationProtectionService)

        facesMessages.setKeepMessages()

        if (authenticationProtectionService.isEnabled()):
            authenticationProtectionService.doDelayIfNeeded(username)

        token_response = ServerUtil.getFirstValue(requestParameters, "tokenResponse")
        authenticationRequestService = FidoU2fClientFactory.instance().createAuthenticationRequestService(self.metaDataConfiguration)
        authenticationStatus = authenticationRequestService.finishAuthentication(username, token_response)

        if (authenticationStatus.getStatus() != Constants.RESULT_SUCCESS):
            print "MFA. Authenticate FIDO. Failed to authenticate  U2F device"
            facesMessages.add(FacesMessage.SEVERITY_ERROR, languageBean.getMessage("mfa.FIDOInvalid"))
            if (authenticationProtectionService.isEnabled()):
                authenticationProtectionService.storeAttempt(username, False)
            return False
        
        if (authenticationProtectionService.isEnabled()):
            authenticationProtectionService.storeAttempt(username, True)
        return True
    def authenticate(self, configurationAttributes, requestParameters, step):

        extensionResult = self.extensionAuthenticate(configurationAttributes, requestParameters, step)
        if extensionResult != None:
            return extensionResult

        print "Passport. authenticate for step %s called" % str(step)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            # Get JWT token
            jwt_param = ServerUtil.getFirstValue(requestParameters, "user")
            if jwt_param != None:
                print "Passport. authenticate for step 1. JWT user profile token found"

                # Parse JWT and validate
                jwt = Jwt.parse(jwt_param)
                if not self.validSignature(jwt):
                    return False

                (user_profile, json) = self.getUserProfile(jwt)
                if user_profile == None:
                    return False

                return self.attemptAuthentication(identity, user_profile, json)

            #See passportlogin.xhtml
            provider = ServerUtil.getFirstValue(requestParameters, "loginForm:provider")
            if StringHelper.isEmpty(provider):

                #it's username + passw auth
                print "Passport. authenticate for step 1. Basic authentication detected"
                logged_in = False

                credentials = identity.getCredentials()
                user_name = credentials.getUsername()
                user_password = credentials.getPassword()

                if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password):
                    authenticationService = CdiUtil.bean(AuthenticationService)
                    logged_in = authenticationService.authenticate(user_name, user_password)

                print "Passport. authenticate for step 1. Basic authentication returned: %s" % logged_in
                return logged_in

            elif provider in self.registeredProviders:
                #it's a recognized external IDP
                identity.setWorkingParameter("selectedProvider", provider)
                print "Passport. authenticate for step 1. Retrying step 1"
                #see prepareForStep (step = 1)
                return True

        if step == 2:
            mail = ServerUtil.getFirstValue(requestParameters, "loginForm:email")
            json = identity.getWorkingParameter("passport_user_profile")

            if mail == None:
                self.setEmailMessageError()
            elif json != None:
                # Completion of profile takes place
                user_profile = self.getProfileFromJson(json)
                user_profile["mail"] = mail

                return self.attemptAuthentication(identity, user_profile, json)

            print "Passport. authenticate for step 2. Failed: expected mail value in HTTP request and json profile in session"
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        user_name = credentials.getUsername()

        if (step == 1):
            print "U2F. Authenticate for step 1"

            user_password = credentials.getPassword()
            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                userService = CdiUtil.bean(UserService)
                logged_in = authenticationService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

            return True
        elif (step == 2):
            print "U2F. Authenticate for step 2"

            token_response = ServerUtil.getFirstValue(requestParameters, "tokenResponse")
            if token_response == None:
                print "U2F. Authenticate for step 2. tokenResponse is empty"
                return False

            auth_method = ServerUtil.getFirstValue(requestParameters, "authMethod")
            if auth_method == None:
                print "U2F. Authenticate for step 2. authMethod is empty"
                return False

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "U2F. Prepare for step 2. Failed to determine user name"
                return False

            if (auth_method == 'authenticate'):
                print "U2F. Prepare for step 2. Call FIDO U2F in order to finish authentication workflow"
                authenticationRequestService = FidoU2fClientFactory.instance().createAuthenticationRequestService(self.metaDataConfiguration)
                authenticationStatus = authenticationRequestService.finishAuthentication(user.getUserId(), token_response)

                if (authenticationStatus.getStatus() != Constants.RESULT_SUCCESS):
                    print "U2F. Authenticate for step 2. Get invalid authentication status from FIDO U2F server"
                    return False

                return True
            elif (auth_method == 'enroll'):
                print "U2F. Prepare for step 2. Call FIDO U2F in order to finish registration workflow"
                registrationRequestService = FidoU2fClientFactory.instance().createRegistrationRequestService(self.metaDataConfiguration)
                registrationStatus = registrationRequestService.finishRegistration(user.getUserId(), token_response)

                if (registrationStatus.getStatus() != Constants.RESULT_SUCCESS):
                    print "U2F. Authenticate for step 2. Get invalid registration status from FIDO U2F server"
                    return False

                return True
            else:
                print "U2F. Prepare for step 2. Authenticatiod method is invalid"
                return False

            return False
        else:
            return False
コード例 #30
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        self.setRequestScopedParameters(identity)

        if step == 1:
            print "OTP. Authenticate for step 1"

            # Modified for Casa compliance
            authenticated_user = authenticationService.getAuthenticatedUser()
            if authenticated_user == None:
                authenticated_user = self.processBasicAuthentication(
                    credentials)
                if authenticated_user == None:
                    return False

            otp_auth_method = "authenticate"
            # Uncomment this block if you need to allow user second OTP registration
            #enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
            #if StringHelper.isNotEmpty(enrollment_mode):
            #    otp_auth_method = "enroll"

            # Modified for Casa compliance
            if not self.hasEnrollments(configurationAttributes,
                                       authenticated_user):
                return False

            #if otp_auth_method == "authenticate":
            #    user_enrollments = self.findEnrollments(authenticated_user.getUserId())
            #    if len(user_enrollments) == 0:
            #        otp_auth_method = "enroll"
            #        print "OTP. Authenticate for step 1. There is no OTP enrollment for user '%s'. Changing otp_auth_method to '%s'" % (authenticated_user.getUserId(), otp_auth_method)

            if otp_auth_method == "enroll":
                print "OTP. Authenticate for step 1. Setting count steps: '%s'" % 3
                identity.setWorkingParameter("otp_count_login_steps", 3)

            print "OTP. Authenticate for step 1. otp_auth_method: '%s'" % otp_auth_method
            identity.setWorkingParameter("otp_auth_method", otp_auth_method)

            return True
        elif step == 2:
            print "OTP. Authenticate for step 2"

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "OTP. Authenticate for step 2. Failed to determine user name"
                return False

            session_id_validation = self.validateSessionId(identity)
            if not session_id_validation:
                return False

            # Restore state from session
            otp_auth_method = identity.getWorkingParameter("otp_auth_method")
            if otp_auth_method == 'enroll':
                auth_result = ServerUtil.getFirstValue(requestParameters,
                                                       "auth_result")
                if not StringHelper.isEmpty(auth_result):
                    print "OTP. Authenticate for step 2. User not enrolled OTP"
                    return False

                print "OTP. Authenticate for step 2. Skipping this step during enrollment"
                return True

            otp_auth_result = self.processOtpAuthentication(
                requestParameters, user.getUserId(), identity, otp_auth_method)
            print "OTP. Authenticate for step 2. OTP authentication result: '%s'" % otp_auth_result

            return otp_auth_result
        elif step == 3:
            print "OTP. Authenticate for step 3"

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "OTP. Authenticate for step 2. Failed to determine user name"
                return False

            session_id_validation = self.validateSessionId(identity)
            if not session_id_validation:
                return False

            # Restore state from session
            otp_auth_method = identity.getWorkingParameter("otp_auth_method")
            if otp_auth_method != 'enroll':
                return False

            otp_auth_result = self.processOtpAuthentication(
                requestParameters, user.getUserId(), identity, otp_auth_method)
            print "OTP. Authenticate for step 3. OTP authentication result: '%s'" % otp_auth_result

            return otp_auth_result
        else:
            return False
コード例 #31
0
    def processOtpAuthentication(self, requestParameters, user_name, identity,
                                 otp_auth_method):
        facesMessages = CdiUtil.bean(FacesMessages)
        facesMessages.setKeepMessages()

        userService = CdiUtil.bean(UserService)

        otpCode = ServerUtil.getFirstValue(requestParameters,
                                           "loginForm:otpCode")
        if StringHelper.isEmpty(otpCode):
            facesMessages.add(FacesMessage.SEVERITY_ERROR,
                              "Failed to authenticate. OTP code is empty")
            print "OTP. Process OTP authentication. otpCode is empty"

            return False

        if otp_auth_method == "enroll":
            # Get key from session
            otp_secret_key_encoded = identity.getWorkingParameter(
                "otp_secret_key")
            if otp_secret_key_encoded == None:
                print "OTP. Process OTP authentication. OTP secret key is invalid"
                return False

            otp_secret_key = self.fromBase64Url(otp_secret_key_encoded)

            if self.otpType == "hotp":
                validation_result = self.validateHotpKey(
                    otp_secret_key, 1, otpCode)

                if (validation_result != None) and validation_result["result"]:
                    print "OTP. Process HOTP authentication during enrollment. otpCode is valid"
                    # Store HOTP Secret Key and moving factor in user entry
                    otp_user_external_uid = "hotp:%s;%s" % (
                        otp_secret_key_encoded,
                        validation_result["movingFactor"])

                    # Add otp_user_external_uid to user's external GUID list
                    find_user_by_external_uid = userService.addUserAttribute(
                        user_name, "oxExternalUid", otp_user_external_uid)
                    if find_user_by_external_uid != None:
                        return True

                    print "OTP. Process HOTP authentication during enrollment. Failed to update user entry"
            elif self.otpType == "totp":
                validation_result = self.validateTotpKey(
                    otp_secret_key, otpCode)
                if (validation_result != None) and validation_result["result"]:
                    print "OTP. Process TOTP authentication during enrollment. otpCode is valid"
                    # Store TOTP Secret Key and moving factor in user entry
                    otp_user_external_uid = "totp:%s" % otp_secret_key_encoded

                    # Add otp_user_external_uid to user's external GUID list
                    find_user_by_external_uid = userService.addUserAttribute(
                        user_name, "oxExternalUid", otp_user_external_uid)
                    if find_user_by_external_uid != None:
                        return True

                    print "OTP. Process TOTP authentication during enrollment. Failed to update user entry"
        elif otp_auth_method == "authenticate":
            # Modified for Casa compliance

            user_enrollments = self.findEnrollments(user_name, "hotp")

            #if len(user_enrollments) == 0:
            #    print "OTP. Process OTP authentication. There is no OTP enrollment for user '%s'" % user_name
            #    facesMessages.add(FacesMessage.SEVERITY_ERROR, "There is no valid OTP user enrollments")
            #    return False

            if len(user_enrollments) > 0:
                for user_enrollment in user_enrollments:
                    user_enrollment_data = user_enrollment.split(";")
                    otp_secret_key_encoded = user_enrollment_data[0]

                    # Get current moving factor from user entry
                    moving_factor = StringHelper.toInteger(
                        user_enrollment_data[1])
                    otp_secret_key = self.fromBase64Url(otp_secret_key_encoded)

                    # Validate TOTP
                    validation_result = self.validateHotpKey(
                        otp_secret_key, moving_factor, otpCode)
                    if (validation_result !=
                            None) and validation_result["result"]:
                        print "OTP. Process HOTP authentication during authentication. otpCode is valid"
                        otp_user_external_uid = "hotp:%s;%s" % (
                            otp_secret_key_encoded, moving_factor)
                        new_otp_user_external_uid = "hotp:%s;%s" % (
                            otp_secret_key_encoded,
                            validation_result["movingFactor"])

                        # Update moving factor in user entry
                        find_user_by_external_uid = userService.replaceUserAttribute(
                            user_name, "oxExternalUid", otp_user_external_uid,
                            new_otp_user_external_uid)
                        if find_user_by_external_uid != None:
                            return True

                        print "OTP. Process HOTP authentication during authentication. Failed to update user entry"

            user_enrollments = self.findEnrollments(user_name, "totp")

            if len(user_enrollments) > 0:
                for user_enrollment in user_enrollments:
                    otp_secret_key = self.fromBase64Url(user_enrollment)

                    # Validate TOTP
                    validation_result = self.validateTotpKey(
                        otp_secret_key, otpCode)
                    if (validation_result !=
                            None) and validation_result["result"]:
                        print "OTP. Process TOTP authentication during authentication. otpCode is valid"
                        return True

        facesMessages.add(FacesMessage.SEVERITY_ERROR,
                          "Failed to authenticate. OTP code is invalid")
        print "OTP. Process OTP authentication. OTP code is invalid"

        return False
コード例 #32
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)

        facesMessages = CdiUtil.bean(FacesMessages)
        facesMessages.setKeepMessages()

        session_attributes = self.identity.getSessionId().getSessionAttributes()
        form_passcode = ServerUtil.getFirstValue(requestParameters, "passcode")
        form_name = ServerUtil.getFirstValue(requestParameters, "TwilioSmsloginForm")

        print "TwilioSMS. form_response_passcode: %s" % str(form_passcode)

        if step == 1:
            print "TwilioSMS. Step 1 Password Authentication"
            credentials = self.identity.getCredentials()

            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

            logged_in = False
            if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password):
                logged_in = authenticationService.authenticate(user_name, user_password)

            if not logged_in:
                return False

            # Get the Person's number and generate a code
            foundUser = None
            try:
                foundUser = authenticationService.getAuthenticatedUser()
            except:
                print 'TwilioSMS, Error retrieving user %s from LDAP' % (user_name)
                return False

            try:
                isVerified = foundUser.getAttribute("phoneNumberVerified")
                if isVerified:
                    self.mobile_number = foundUser.getAttribute("employeeNumber")
                if  self.mobile_number == None:
                    self.mobile_number = foundUser.getAttribute("mobile")
                if  self.mobile_number == None:
                    self.mobile_number = foundUser.getAttribute("telephoneNumber")
                if  self.mobile_number == None:
                    print "TwilioSMS, Error finding mobile number for user '%'" % user_name    
                    
            except:
                facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to determine mobile phone number")
                print 'TwilioSMS, Error finding mobile number for' % (user_name)
                return False

            # Generate Random six digit code and store it in array
            code = random.randint(100000, 999999)

            # Get code and save it in LDAP temporarily with special session entry
            self.identity.setWorkingParameter("code", code)

            try:
                Twilio.init(self.ACCOUNT_SID, self.AUTH_TOKEN);
                message = Message.creator(PhoneNumber(self.mobile_number), PhoneNumber(self.FROM_NUMBER), str(code)).create();
                print "++++++++++++++++++++++++++++++++++++++++++++++"
                print 'TwilioSMs, Message Sid: %s' % (message.getSid())
                print 'TwilioSMs, User phone: %s' % (self.mobile_number)
                print "++++++++++++++++++++++++++++++++++++++++++++++"
                self.identity.setWorkingParameter("mobile_number", self.mobile_number)
                self.identity.getSessionId().getSessionAttributes().put("mobile_number",self.mobile_number)
                self.identity.setWorkingParameter("mobile", self.mobile_number)
                self.identity.getSessionId().getSessionAttributes().put("mobile",self.mobile_number)
                print "++++++++++++++++++++++++++++++++++++++++++++++"
                print "Number: %s" % (self.identity.getWorkingParameter("mobile_number"))
                print "Mobile: %s" % (self.identity.getWorkingParameter("mobile"))
                print "++++++++++++++++++++++++++++++++++++++++++++++"
                return True
            except Exception, ex:
                facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to send message to mobile phone")
                print "TwilioSMS. Error sending message to Twilio"
                print "TwilioSMS. Unexpected error:", ex

            return False
コード例 #33
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        user_name = credentials.getUsername()

        if (step == 1):
            print "U2F. Authenticate for step 1"

            if authenticationService.getAuthenticatedUser() != None:
                return True

            user_password = credentials.getPassword()
            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                userService = CdiUtil.bean(UserService)
                logged_in = authenticationService.authenticate(
                    user_name, user_password)

            if (not logged_in):
                return False

            return True
        elif (step == 2):
            print "U2F. Authenticate for step 2"

            token_response = ServerUtil.getFirstValue(requestParameters,
                                                      "tokenResponse")
            if token_response == None:
                print "U2F. Authenticate for step 2. tokenResponse is empty"
                return False

            auth_method = ServerUtil.getFirstValue(requestParameters,
                                                   "authMethod")
            if auth_method == None:
                print "U2F. Authenticate for step 2. authMethod is empty"
                return False

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "U2F. Prepare for step 2. Failed to determine user name"
                return False

            if (auth_method == 'authenticate'):
                print "U2F. Prepare for step 2. Call FIDO U2F in order to finish authentication workflow"
                authenticationRequestService = FidoU2fClientFactory.instance(
                ).createAuthenticationRequestService(
                    self.metaDataConfiguration)
                authenticationStatus = authenticationRequestService.finishAuthentication(
                    user.getUserId(), token_response)

                if (authenticationStatus.getStatus() !=
                        Constants.RESULT_SUCCESS):
                    print "U2F. Authenticate for step 2. Get invalid authentication status from FIDO U2F server"
                    return False

                return True
            elif (auth_method == 'enroll'):
                print "U2F. Prepare for step 2. Call FIDO U2F in order to finish registration workflow"
                registrationRequestService = FidoU2fClientFactory.instance(
                ).createRegistrationRequestService(self.metaDataConfiguration)
                registrationStatus = registrationRequestService.finishRegistration(
                    user.getUserId(), token_response)

                if (registrationStatus.getStatus() !=
                        Constants.RESULT_SUCCESS):
                    print "U2F. Authenticate for step 2. Get invalid registration status from FIDO U2F server"
                    return False

                return True
            else:
                print "U2F. Prepare for step 2. Authenticatiod method is invalid"
                return False

            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        session_attributes = identity.getSessionId().getSessionAttributes()

        self.setRequestScopedParameters(identity)

        if (step == 1):
            print "UAF. Authenticate for step 1"

            user_name = credentials.getUsername()

            authenticated_user = self.processBasicAuthentication(credentials)
            if authenticated_user == None:
                return False

            uaf_auth_method = "authenticate"
            # Uncomment this block if you need to allow user second device registration
            #enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
            #if StringHelper.isNotEmpty(enrollment_mode):
            #    uaf_auth_method = "enroll"
            
            if uaf_auth_method == "authenticate":
                user_enrollments = self.findEnrollments(credentials)
                if len(user_enrollments) == 0:
                    uaf_auth_method = "enroll"
                    print "UAF. Authenticate for step 1. There is no UAF enrollment for user '%s'. Changing uaf_auth_method to '%s'" % (user_name, uaf_auth_method)

            print "UAF. Authenticate for step 1. uaf_auth_method: '%s'" % uaf_auth_method
            
            identity.setWorkingParameter("uaf_auth_method", uaf_auth_method)

            return True
        elif (step == 2):
            print "UAF. Authenticate for step 2"

            session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie()
            if StringHelper.isEmpty(session_id):
                print "UAF. Prepare for step 2. Failed to determine session_id"
                return False

            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "UAF. Authenticate for step 2. Failed to determine user name"
                return False
            user_name = user.getUserId()

            uaf_auth_result = ServerUtil.getFirstValue(requestParameters, "auth_result")
            if uaf_auth_result != "success":
                print "UAF. Authenticate for step 2. auth_result is '%s'" % uaf_auth_result
                return False

            # Restore state from session
            uaf_auth_method = session_attributes.get("uaf_auth_method")

            if not uaf_auth_method in ['enroll', 'authenticate']:
                print "UAF. Authenticate for step 2. Failed to authenticate user. uaf_auth_method: '%s'" % uaf_auth_method
                return False

            # Request STATUS_OBB
            if True:
                #TODO: Remove this condition
                # It's workaround becuase it's not possible to call STATUS_OBB 2 times. First time on browser and second ime on server
                uaf_user_device_handle = ServerUtil.getFirstValue(requestParameters, "auth_handle")
            else:
                uaf_obb_auth_method = session_attributes.get("uaf_obb_auth_method")
                uaf_obb_server_uri = session_attributes.get("uaf_obb_server_uri")
                uaf_obb_start_response = session_attributes.get("uaf_obb_start_response")

                # Prepare STATUS_OBB
                uaf_obb_start_response_json = json.loads(uaf_obb_start_response)
                uaf_obb_status_request_dictionary = { "operation": "STATUS_%s" % uaf_obb_auth_method,
                                                      "userName": user_name,
                                                      "needDetails": 1,
                                                      "oobStatusHandle": uaf_obb_start_response_json["oobStatusHandle"],
                                                    }
    
                uaf_obb_status_request = json.dumps(uaf_obb_status_request_dictionary, separators=(',',':'))
                print "UAF. Authenticate for step 2. Prepared STATUS request: '%s' to send to '%s'" % (uaf_obb_status_request, uaf_obb_server_uri)

                uaf_status_obb_response = self.executePost(uaf_obb_server_uri, uaf_obb_status_request)
                if uaf_status_obb_response == None:
                    return False

                print "UAF. Authenticate for step 2. Get STATUS response: '%s'" % uaf_status_obb_response
                uaf_status_obb_response_json = json.loads(uaf_status_obb_response)
                
                if uaf_status_obb_response_json["statusCode"] != 4000:
                    print "UAF. Authenticate for step 2. UAF operation status is invalid. statusCode: '%s'" % uaf_status_obb_response_json["statusCode"]
                    return False

                uaf_user_device_handle = uaf_status_obb_response_json["additionalInfo"]["authenticatorsResult"]["handle"]

            if StringHelper.isEmpty(uaf_user_device_handle):
                print "UAF. Prepare for step 2. Failed to get UAF handle"
                return False

            uaf_user_external_uid = "uaf:%s" % uaf_user_device_handle
            print "UAF. Authenticate for step 2. UAF handle: '%s'" % uaf_user_external_uid

            if uaf_auth_method == "authenticate":
                # Validate if user used device with same keYHandle
                user_enrollments = self.findEnrollments(credentials)
                if len(user_enrollments) == 0:
                    uaf_auth_method = "enroll"
                    print "UAF. Authenticate for step 2. There is no UAF enrollment for user '%s'." % user_name
                    return False
                
                for user_enrollment in user_enrollments:
                    if StringHelper.equalsIgnoreCase(user_enrollment, uaf_user_device_handle):
                        print "UAF. Authenticate for step 2. There is UAF enrollment for user '%s'. User authenticated successfully" % user_name
                        return True
            else:
                userService = CdiUtil.bean(UserService)

                # Double check just to make sure. We did checking in previous step
                # Check if there is user which has uaf_user_external_uid
                # Avoid mapping user cert to more than one IDP account
                find_user_by_external_uid = userService.getUserByAttribute("oxExternalUid", uaf_user_external_uid)
                if find_user_by_external_uid == None:
                    # Add uaf_user_external_uid to user's external GUID list
                    find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", uaf_user_external_uid)
                    if find_user_by_external_uid == None:
                        print "UAF. Authenticate for step 2. Failed to update current user"
                        return False
    
                    return True

            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        user_name = credentials.getUsername()

        if (step == 1):
            print "Fido2. Authenticate for step 1"

            user_password = credentials.getPassword()
            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                userService = CdiUtil.bean(UserService)
                logged_in = authenticationService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

            return True
        elif (step == 2):
            print "Fido2. Authenticate for step 2"

            token_response = ServerUtil.getFirstValue(requestParameters, "tokenResponse")
            if token_response == None:
                print "Fido2. Authenticate for step 2. tokenResponse is empty"
                return False

            auth_method = ServerUtil.getFirstValue(requestParameters, "authMethod")
            if auth_method == None:
                print "Fido2. Authenticate for step 2. authMethod is empty"
                return False

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "Fido2. Prepare for step 2. Failed to determine user name"
                return False

            if (auth_method == 'authenticate'):
                print "Fido2. Prepare for step 2. Call Fido2 in order to finish authentication flow"
                assertionService = Fido2ClientFactory.instance().createAssertionService(self.metaDataConfiguration)
                assertionStatus = assertionService.verify(token_response)
                authenticationStatusEntity = assertionStatus.readEntity(java.lang.String)

                if (assertionStatus.getStatus() != Response.Status.OK.getStatusCode()):
                    print "Fido2. Authenticate for step 2. Get invalid authentication status from Fido2 server"
                    return False

                return True
            elif (auth_method == 'enroll'):
                print "Fido2. Prepare for step 2. Call Fido2 in order to finish registration flow"
                attestationService = Fido2ClientFactory.instance().createAttestationService(self.metaDataConfiguration)
                attestationStatus = attestationService.verify(token_response)

                if (attestationStatus.getStatus() != Response.Status.OK.getStatusCode()):
                    print "Fido2. Authenticate for step 2. Get invalid registration status from Fido2 server"
                    return False

                return True
            else:
                print "Fido2. Prepare for step 2. Authentication method is invalid"
                return False

            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        user_name = credentials.getUsername()

        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)

        if step == 1:
            print "Cert. Authenticate for step 1"
            login_button = ServerUtil.getFirstValue(requestParameters, "loginForm:loginButton")
            if StringHelper.isEmpty(login_button):
                print "Cert. Authenticate for step 1. Form were submitted incorrectly"
                return False
            if self.enabled_recaptcha:
                print "Cert. Authenticate for step 1. Validating recaptcha response"
                recaptcha_response = ServerUtil.getFirstValue(requestParameters, "g-recaptcha-response")

                recaptcha_result = self.validateRecaptcha(recaptcha_response)
                print "Cert. Authenticate for step 1. recaptcha_result: '%s'" % recaptcha_result
                
                return recaptcha_result

            return True
        elif step == 2:
            print "Cert. Authenticate for step 2"

            # Validate if user selected certificate
            cert_x509 = self.getSessionAttribute("cert_x509")
            if cert_x509 == None:
                print "Cert. Authenticate for step 2. User not selected any certs"
                identity.setWorkingParameter("cert_selected", False)
                    
                # Return True to inform user how to reset workflow
                return True
            else:
                identity.setWorkingParameter("cert_selected", True)
                x509Certificate = self.certFromString(cert_x509)

            subjectX500Principal = x509Certificate.getSubjectX500Principal()
            print "Cert. Authenticate for step 2. User selected certificate with DN '%s'" % subjectX500Principal
            
            # Validate certificates which user selected
            valid = self.validateCertificate(x509Certificate)
            if not valid:
                print "Cert. Authenticate for step 2. Certificate DN '%s' is not valid" % subjectX500Principal
                identity.setWorkingParameter("cert_valid", False)
                
                # Return True to inform user how to reset workflow
                return True

            identity.setWorkingParameter("cert_valid", True)
            
            # Calculate certificate fingerprint
            x509CertificateFingerprint = self.calculateCertificateFingerprint(x509Certificate)
            identity.setWorkingParameter("cert_x509_fingerprint", x509CertificateFingerprint)
            print "Cert. Authenticate for step 2. Fingerprint is '%s' of certificate with DN '%s'" % (x509CertificateFingerprint, subjectX500Principal)
            
            # Attempt to find user by certificate fingerprint
            cert_user_external_uid = "cert:%s" % x509CertificateFingerprint
            print "Cert. Authenticate for step 2. Attempting to find user by oxExternalUid attribute value %s" % cert_user_external_uid

            find_user_by_external_uid = userService.getUserByAttribute("oxExternalUid", cert_user_external_uid)
            if find_user_by_external_uid == None:
                print "Cert. Authenticate for step 2. Failed to find user"
                
                if self.map_user_cert:
                    print "Cert. Authenticate for step 2. Storing cert_user_external_uid for step 3"
                    identity.setWorkingParameter("cert_user_external_uid", cert_user_external_uid)
                    return True
                else:
                    print "Cert. Authenticate for step 2. Mapping cert to user account is not allowed"
                    identity.setWorkingParameter("cert_count_login_steps", 2)
                    return False

            foundUserName = find_user_by_external_uid.getUserId()
            print "Cert. Authenticate for step 2. foundUserName: "******"Cert. Authenticate for step 2. Setting count steps to 2"
            identity.setWorkingParameter("cert_count_login_steps", 2)

            return logged_in
        elif step == 3:
            print "Cert. Authenticate for step 3"

            cert_user_external_uid = self.getSessionAttribute("cert_user_external_uid")
            if cert_user_external_uid == None:
                print "Cert. Authenticate for step 3. cert_user_external_uid is empty"
                return False

            user_password = credentials.getPassword()

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                logged_in = authenticationService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

            # Double check just to make sure. We did checking in previous step
            # Check if there is user which has cert_user_external_uid
            # Avoid mapping user cert to more than one IDP account
            find_user_by_external_uid = userService.getUserByAttribute("oxExternalUid", cert_user_external_uid)
            if find_user_by_external_uid == None:
                # Add cert_user_external_uid to user's external GUID list
                find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", cert_user_external_uid)
                if find_user_by_external_uid == None:
                    print "Cert. Authenticate for step 3. Failed to update current user"
                    return False

                return True
        
            return True
        else:
            return False
コード例 #37
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        user_name = credentials.getUsername()

        if (step == 1):
            print "Fido2. Authenticate for step 1"

            if authenticationService.getAuthenticatedUser() != None:
                return True

            user_password = credentials.getPassword()
            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                userService = CdiUtil.bean(UserService)
                logged_in = authenticationService.authenticate(
                    user_name, user_password)

            if (not logged_in):
                return False

            return True
        elif (step == 2):
            print "Fido2. Authenticate for step 2"

            token_response = ServerUtil.getFirstValue(requestParameters,
                                                      "tokenResponse")
            if token_response == None:
                print "Fido2. Authenticate for step 2. tokenResponse is empty"
                return False

            auth_method = ServerUtil.getFirstValue(requestParameters,
                                                   "authMethod")
            if auth_method == None:
                print "Fido2. Authenticate for step 2. authMethod is empty"
                return False

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "Fido2. Prepare for step 2. Failed to determine user name"
                return False

            if (auth_method == 'authenticate'):
                print "Fido2. Prepare for step 2. Call Fido2 in order to finish authentication flow"
                assertionService = Fido2ClientFactory.instance(
                ).createAssertionService(self.metaDataConfiguration)
                assertionStatus = assertionService.verify(token_response)
                authenticationStatusEntity = assertionStatus.readEntity(
                    java.lang.String)

                if (assertionStatus.getStatus() !=
                        Response.Status.OK.getStatusCode()):
                    print "Fido2. Authenticate for step 2. Get invalid authentication status from Fido2 server"
                    return False

                return True
            elif (auth_method == 'enroll'):
                print "Fido2. Prepare for step 2. Call Fido2 in order to finish registration flow"
                attestationService = Fido2ClientFactory.instance(
                ).createAttestationService(self.metaDataConfiguration)
                attestationStatus = attestationService.verify(token_response)

                if (attestationStatus.getStatus() !=
                        Response.Status.OK.getStatusCode()):
                    print "Fido2. Authenticate for step 2. Get invalid registration status from Fido2 server"
                    return False

                return True
            else:
                print "Fido2. Prepare for step 2. Authentication method is invalid"
                return False

            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):

        extensionResult = self.extensionAuthenticate(configurationAttributes, requestParameters, step)
        if extensionResult != None:
            return extensionResult

        print "Passport. authenticate for step %s called" % str(step)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            jwt_param = None

            if self.isInboundFlow(identity):
                # if is idp-initiated inbound flow
                print "Passport. authenticate for step 1. Detected idp-initiated inbound Saml flow"
                # get request from session attributes
                jwt_param = identity.getSessionId().getSessionAttributes().get(AuthorizeRequestParam.STATE)
                # now jwt_param != None



            if jwt_param == None:
                # gets jwt parameter "user" sent after authentication by passport (if exists)
                jwt_param = ServerUtil.getFirstValue(requestParameters, "user")


            if jwt_param != None:
                # and now that the jwt_param user exists...
                
                print "Passport. authenticate for step 1. JWT user profile token found"

                # Parse JWT and validate
                jwt = Jwt.parse(jwt_param)
                
                if not self.validSignature(jwt):
                    return False

                if self.jwtHasExpired(jwt):
                    return False

                # Gets user profile as string and json using the information on JWT
                (user_profile, jsonp) = self.getUserProfile(jwt)

                if user_profile == None:
                    return False

                return self.attemptAuthentication(identity, user_profile, jsonp)

            #See passportlogin.xhtml
            provider = ServerUtil.getFirstValue(requestParameters, "loginForm:provider")
            if StringHelper.isEmpty(provider):

                #it's username + passw auth
                print "Passport. authenticate for step 1. Basic authentication detected"
                logged_in = False

                credentials = identity.getCredentials()
                user_name = credentials.getUsername()
                user_password = credentials.getPassword()

                if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password):
                    authenticationService = CdiUtil.bean(AuthenticationService)
                    logged_in = authenticationService.authenticate(user_name, user_password)

                print "Passport. authenticate for step 1. Basic authentication returned: %s" % logged_in
                return logged_in


            elif provider in self.registeredProviders:
                # user selected provider
                # it's a recognized external IDP

                identity.setWorkingParameter("selectedProvider", provider)
                print "Passport. authenticate for step 1. Retrying step 1"

                #see prepareForStep (step = 1)
                return True

        if step == 2:
            mail = ServerUtil.getFirstValue(requestParameters, "loginForm:email")
            jsonp = identity.getWorkingParameter("passport_user_profile")

            if mail == None:
                self.setMessageError(FacesMessage.SEVERITY_ERROR, "Email was missing in user profile")
            elif jsonp != None:
                # Completion of profile takes place
                user_profile = json.loads(jsonp)
                user_profile["mail"] = [ mail ]

                return self.attemptAuthentication(identity, user_profile, jsonp)

            print "Passport. authenticate for step 2. Failed: expected mail value in HTTP request and json profile in session"
            return False
コード例 #39
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        user_name = credentials.getUsername()

        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)

        if step == 1:
            print "Cert. Authenticate for step 1"
            login_button = ServerUtil.getFirstValue(requestParameters,
                                                    "loginForm:loginButton")
            if StringHelper.isEmpty(login_button):
                print "Cert. Authenticate for step 1. Form were submitted incorrectly"
                return False
            if self.enabled_recaptcha:
                print "Cert. Authenticate for step 1. Validating recaptcha response"
                recaptcha_response = ServerUtil.getFirstValue(
                    requestParameters, "g-recaptcha-response")

                recaptcha_result = self.validateRecaptcha(recaptcha_response)
                print "Cert. Authenticate for step 1. recaptcha_result: '%s'" % recaptcha_result

                return recaptcha_result

            return True
        elif step == 2:
            print "Cert. Authenticate for step 2"

            # Validate if user selected certificate
            cert_x509 = self.getSessionAttribute("cert_x509")
            if cert_x509 == None:
                print "Cert. Authenticate for step 2. User not selected any certs"
                identity.setWorkingParameter("cert_selected", False)

                # Return True to inform user how to reset workflow
                return True
            else:
                identity.setWorkingParameter("cert_selected", True)
                x509Certificate = self.certFromString(cert_x509)

            subjectX500Principal = x509Certificate.getSubjectX500Principal()
            print "Cert. Authenticate for step 2. User selected certificate with DN '%s'" % subjectX500Principal

            # Validate certificates which user selected
            valid = self.validateCertificate(x509Certificate)
            if not valid:
                print "Cert. Authenticate for step 2. Certificate DN '%s' is not valid" % subjectX500Principal
                identity.setWorkingParameter("cert_valid", False)

                # Return True to inform user how to reset workflow
                return True

            identity.setWorkingParameter("cert_valid", True)

            # Calculate certificate fingerprint
            x509CertificateFingerprint = self.calculateCertificateFingerprint(
                x509Certificate)
            identity.setWorkingParameter("cert_x509_fingerprint",
                                         x509CertificateFingerprint)
            print "Cert. Authenticate for step 2. Fingerprint is '%s' of certificate with DN '%s'" % (
                x509CertificateFingerprint, subjectX500Principal)

            # Attempt to find user by certificate fingerprint
            cert_user_external_uid = "cert:%s" % x509CertificateFingerprint
            print "Cert. Authenticate for step 2. Attempting to find user by oxExternalUid attribute value %s" % cert_user_external_uid

            find_user_by_external_uid = userService.getUserByAttribute(
                "oxExternalUid", cert_user_external_uid, True)
            if find_user_by_external_uid == None:
                print "Cert. Authenticate for step 2. Failed to find user"

                if self.map_user_cert:
                    print "Cert. Authenticate for step 2. Storing cert_user_external_uid for step 3"
                    identity.setWorkingParameter("cert_user_external_uid",
                                                 cert_user_external_uid)
                    return True
                else:
                    print "Cert. Authenticate for step 2. Mapping cert to user account is not allowed"
                    identity.setWorkingParameter("cert_count_login_steps", 2)
                    return False

            foundUserName = find_user_by_external_uid.getUserId()
            print "Cert. Authenticate for step 2. foundUserName: "******"Cert. Authenticate for step 2. Setting count steps to 2"
            identity.setWorkingParameter("cert_count_login_steps", 2)

            return logged_in
        elif step == 3:
            print "Cert. Authenticate for step 3"

            cert_user_external_uid = self.getSessionAttribute(
                "cert_user_external_uid")
            if cert_user_external_uid == None:
                print "Cert. Authenticate for step 3. cert_user_external_uid is empty"
                return False

            user_password = credentials.getPassword()

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                logged_in = authenticationService.authenticate(
                    user_name, user_password)

            if (not logged_in):
                return False

            # Double check just to make sure. We did checking in previous step
            # Check if there is user which has cert_user_external_uid
            # Avoid mapping user cert to more than one IDP account
            find_user_by_external_uid = userService.getUserByAttribute(
                "oxExternalUid", cert_user_external_uid, True)
            if find_user_by_external_uid == None:
                # Add cert_user_external_uid to user's external GUID list
                find_user_by_external_uid = userService.addUserAttribute(
                    user_name, "oxExternalUid", cert_user_external_uid, True)
                if find_user_by_external_uid == None:
                    print "Cert. Authenticate for step 3. Failed to update current user"
                    return False

                return True

            return True
        else:
            return False
コード例 #40
0
class PersonAuthentication(PersonAuthenticationType):
    def __init__(self, currentTimeMillis):
        self.currentTimeMillis = currentTimeMillis

    def init(self, customScript, configurationAttributes):
        print "Fido2. Initialization"

        if not configurationAttributes.containsKey("fido2_server_uri"):
            print "fido2_server_uri. Initialization. Property fido2_server_uri is not specified"
            return False

        self.fido2_server_uri = configurationAttributes.get(
            "fido2_server_uri").getValue2()

        #self.fido2_domain = None
        #if configurationAttributes.containsKey("fido2_domain"):
        #    self.fido2_domain = configurationAttributes.get("fido2_domain").getValue2()

        self.metaDataLoaderLock = ReentrantLock()
        self.metaDataConfiguration = None

        print "Fido2. Initialized successfully"
        return True

    def destroy(self, configurationAttributes):
        print "Fido2. Destroy"
        print "Fido2. Destroyed successfully"
        return True

    def getApiVersion(self):
        return 11

    def isValidAuthenticationMethod(self, usageType, configurationAttributes):
        return True

    def getAlternativeAuthenticationMethod(self, usageType,
                                           configurationAttributes):
        return None

    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        user_name = credentials.getUsername()

        if (step == 1):
            print "Fido2. Authenticate for step 1"

            if authenticationService.getAuthenticatedUser() != None:
                return True

            user_password = credentials.getPassword()
            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                userService = CdiUtil.bean(UserService)
                logged_in = authenticationService.authenticate(
                    user_name, user_password)

            if (not logged_in):
                return False

            return True
        elif (step == 2):
            print "Fido2. Authenticate for step 2"

            token_response = ServerUtil.getFirstValue(requestParameters,
                                                      "tokenResponse")
            if token_response == None:
                print "Fido2. Authenticate for step 2. tokenResponse is empty"
                return False

            auth_method = ServerUtil.getFirstValue(requestParameters,
                                                   "authMethod")
            if auth_method == None:
                print "Fido2. Authenticate for step 2. authMethod is empty"
                return False

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "Fido2. Prepare for step 2. Failed to determine user name"
                return False

            if (auth_method == 'authenticate'):
                print "Fido2. Prepare for step 2. Call Fido2 in order to finish authentication flow"
                assertionService = Fido2ClientFactory.instance(
                ).createAssertionService(self.metaDataConfiguration)
                assertionStatus = assertionService.verify(token_response)
                authenticationStatusEntity = assertionStatus.readEntity(
                    java.lang.String)

                if (assertionStatus.getStatus() !=
                        Response.Status.OK.getStatusCode()):
                    print "Fido2. Authenticate for step 2. Get invalid authentication status from Fido2 server"
                    return False

                return True
            elif (auth_method == 'enroll'):
                print "Fido2. Prepare for step 2. Call Fido2 in order to finish registration flow"
                attestationService = Fido2ClientFactory.instance(
                ).createAttestationService(self.metaDataConfiguration)
                attestationStatus = attestationService.verify(token_response)

                if (attestationStatus.getStatus() !=
                        Response.Status.OK.getStatusCode()):
                    print "Fido2. Authenticate for step 2. Get invalid registration status from Fido2 server"
                    return False

                return True
            else:
                print "Fido2. Prepare for step 2. Authentication method is invalid"
                return False

            return False
        else:
            return False

    def prepareForStep(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)

        if (step == 1):
            return True
        elif (step == 2):
            print "Fido2. Prepare for step 2"

            session_id = CdiUtil.bean(
                SessionIdService).getSessionIdFromCookie()
            if StringHelper.isEmpty(session_id):
                print "Fido2. Prepare for step 2. Failed to determine session_id"
                return False

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "Fido2. Prepare for step 2. Failed to determine user name"
                return False

            userName = user.getUserId()

            metaDataConfiguration = self.getMetaDataConfiguration()

            # Check if user have registered devices
            registrationPersistenceService = CdiUtil.bean(
                RegistrationPersistenceService)

            assertionResponse = None
            attestationResponse = None

            userFido2Devices = registrationPersistenceService.findAllRegisteredByUsername(
                userName)
            if (userFido2Devices.size() > 0):
                print "Fido2. Prepare for step 2. Call Fido2 endpoint in order to start assertion flow"

                try:
                    assertionService = Fido2ClientFactory.instance(
                    ).createAssertionService(metaDataConfiguration)
                    assertionRequest = json.dumps({'username': userName},
                                                  separators=(',', ':'))
                    assertionResponse = assertionService.authenticate(
                        assertionRequest).readEntity(java.lang.String)
                except ClientResponseFailure, ex:
                    print "Fido2. Prepare for step 2. Failed to start assertion flow. Exception:", sys.exc_info(
                    )[1]
                    return False
            else:
                print "Fido2. Prepare for step 2. Call Fido2 endpoint in order to start attestation flow"

                try:
                    attestationService = Fido2ClientFactory.instance(
                    ).createAttestationService(metaDataConfiguration)
                    attestationRequest = json.dumps(
                        {
                            'username': userName,
                            'displayName': userName
                        },
                        separators=(',', ':'))
                    attestationResponse = attestationService.register(
                        attestationRequest).readEntity(java.lang.String)
                except ClientResponseFailure, ex:
                    print "Fido2. Prepare for step 2. Failed to start attestation flow. Exception:", sys.exc_info(
                    )[1]
                    return False

            identity.setWorkingParameter("fido2_assertion_request",
                                         ServerUtil.asJson(assertionResponse))
            identity.setWorkingParameter(
                "fido2_attestation_request",
                ServerUtil.asJson(attestationResponse))
            print "Fido2. Prepare for step 2. Successfully start flow with next requests.\nfido2_assertion_request: '%s'\nfido2_attestation_request: '%s'" % (
                assertionResponse, attestationResponse)

            return True
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        self.setRequestScopedParameters(identity)

        if step == 1:
            print "OTP. Authenticate for step 1"
            authenticated_user = self.processBasicAuthentication(credentials)
            if authenticated_user == None:
                return False

            otp_auth_method = "authenticate"
            # Uncomment this block if you need to allow user second OTP registration
            #enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
            #if StringHelper.isNotEmpty(enrollment_mode):
            #    otp_auth_method = "enroll"
            
            if otp_auth_method == "authenticate":
                user_enrollments = self.findEnrollments(authenticated_user.getUserId())
                if len(user_enrollments) == 0:
                    otp_auth_method = "enroll"
                    print "OTP. Authenticate for step 1. There is no OTP enrollment for user '%s'. Changing otp_auth_method to '%s'" % (authenticated_user.getUserId(), otp_auth_method)
                    
            if otp_auth_method == "enroll":
                print "OTP. Authenticate for step 1. Setting count steps: '%s'" % 3
                identity.setWorkingParameter("otp_count_login_steps", 3)

            print "OTP. Authenticate for step 1. otp_auth_method: '%s'" % otp_auth_method
            identity.setWorkingParameter("otp_auth_method", otp_auth_method)

            return True
        elif step == 2:
            print "OTP. Authenticate for step 2"

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "OTP. Authenticate for step 2. Failed to determine user name"
                return False

            session_id_validation = self.validateSessionId(identity)
            if not session_id_validation:
                return False

            # Restore state from session
            otp_auth_method = identity.getWorkingParameter("otp_auth_method")
            if otp_auth_method == 'enroll':
                auth_result = ServerUtil.getFirstValue(requestParameters, "auth_result")
                if not StringHelper.isEmpty(auth_result):
                    print "OTP. Authenticate for step 2. User not enrolled OTP"
                    return False

                print "OTP. Authenticate for step 2. Skipping this step during enrollment"
                return True

            otp_auth_result = self.processOtpAuthentication(requestParameters, user.getUserId(), identity, otp_auth_method)
            print "OTP. Authenticate for step 2. OTP authentication result: '%s'" % otp_auth_result

            return otp_auth_result
        elif step == 3:
            print "OTP. Authenticate for step 3"

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "OTP. Authenticate for step 2. Failed to determine user name"
                return False

            session_id_validation = self.validateSessionId(identity)
            if not session_id_validation:
                return False

            # Restore state from session
            otp_auth_method = identity.getWorkingParameter("otp_auth_method")
            if otp_auth_method != 'enroll':
                return False

            otp_auth_result = self.processOtpAuthentication(requestParameters, user.getUserId(), identity, otp_auth_method)
            print "OTP. Authenticate for step 3. OTP authentication result: '%s'" % otp_auth_result

            return otp_auth_result
        else:
            return False
コード例 #42
0
    def authenticate(self, configurationAttributes, requestParameters, step):

        extensionResult = self.extensionAuthenticate(configurationAttributes,
                                                     requestParameters, step)
        if extensionResult != None:
            return extensionResult

        print "Passport. authenticate for step %s called" % str(step)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            # Get JWT token
            jwt_param = ServerUtil.getFirstValue(requestParameters, "user")
            if jwt_param != None:
                print "Passport. authenticate for step 1. JWT user profile token found"

                # Parse JWT and validate
                jwt = Jwt.parse(jwt_param)
                if not self.validSignature(jwt):
                    return False

                (user_profile, json) = self.getUserProfile(jwt)
                if user_profile == None:
                    return False

                return self.attemptAuthentication(identity, user_profile, json)

            #See passportlogin.xhtml
            provider = ServerUtil.getFirstValue(requestParameters,
                                                "loginForm:provider")
            if StringHelper.isEmpty(provider):

                #it's username + passw auth
                print "Passport. authenticate for step 1. Basic authentication detected"
                logged_in = False

                credentials = identity.getCredentials()
                user_name = credentials.getUsername()
                user_password = credentials.getPassword()

                if StringHelper.isNotEmptyString(
                        user_name) and StringHelper.isNotEmptyString(
                            user_password):
                    authenticationService = CdiUtil.bean(AuthenticationService)
                    logged_in = authenticationService.authenticate(
                        user_name, user_password)

                print "Passport. authenticate for step 1. Basic authentication returned: %s" % logged_in
                return logged_in

            elif provider in self.registeredProviders:
                #it's a recognized external IDP
                identity.setWorkingParameter("selectedProvider", provider)
                print "Passport. authenticate for step 1. Retrying step 1"
                #see prepareForStep (step = 1)
                return True

        if step == 2:
            mail = ServerUtil.getFirstValue(requestParameters,
                                            "loginForm:email")
            json = identity.getWorkingParameter("passport_user_profile")

            if mail == None:
                self.setMessageError(FacesMessage.SEVERITY_ERROR,
                                     "Email was missing in user profile")
            elif json != None:
                # Completion of profile takes place
                user_profile = self.getProfileFromJson(json)
                user_profile["mail"] = mail

                return self.attemptAuthentication(identity, user_profile, json)

            print "Passport. authenticate for step 2. Failed: expected mail value in HTTP request and json profile in session"
            return False
コード例 #43
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        print "Casa. authenticate %s" % str(step)

        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

            if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password):

                foundUser = userService.getUserByAttribute(self.uid_attr, user_name)
                #foundUser = userService.getUser(user_name)
                if foundUser == None:
                    print "Casa. authenticate for step 1. Unknown username"
                else:
                    platform_data = self.parsePlatformData(requestParameters)
                    mfaOff = foundUser.getAttribute("oxPreferredMethod") == None
                    logged_in = False

                    if mfaOff:
                        logged_in = authenticationService.authenticate(user_name, user_password)
                    else:
                        acr = self.getSuitableAcr(foundUser, platform_data['isMobile'])
                        if acr != None:
                            module = self.authenticators[acr]
                            logged_in = module.authenticate(module.configAttrs, requestParameters, step)

                    if logged_in:
                        foundUser = authenticationService.getAuthenticatedUser()

                        if foundUser == None:
                            print "Casa. authenticate for step 1. Cannot retrieve logged user"
                        else:
                            if mfaOff:
                                identity.setWorkingParameter("skip2FA", True)
                            else:
                                #Determine whether to skip 2FA based on policy defined (global or user custom)
                                skip2FA = self.determineSkip2FA(userService, identity, foundUser, platform_data)
                                identity.setWorkingParameter("skip2FA", skip2FA)
                                identity.setWorkingParameter("ACR", acr)

                            return True

                    else:
                        print "Casa. authenticate for step 1 was not successful"
            return False

        else:
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "Casa. authenticate for step 2. Cannot retrieve logged user"
                return False

            #see casa.xhtml
            alter = ServerUtil.getFirstValue(requestParameters, "alternativeMethod")
            if alter != None:
                #bypass the rest of this step if an alternative method was provided. Current step will be retried (see getNextStep)
                self.simulateFirstStep(requestParameters, alter)
                return True

            session_attributes = identity.getSessionId().getSessionAttributes()
            acr = session_attributes.get("ACR")
            #this working parameter is used in casa.xhtml
            identity.setWorkingParameter("methods", ArrayList(self.getAvailMethodsUser(user, acr)))

            success = False
            if acr in self.authenticators:
                module = self.authenticators[acr]
                success = module.authenticate(module.configAttrs, requestParameters, step)

            #Update the list of trusted devices if 2fa passed
            if success:
                print "Casa. authenticate. 2FA authentication was successful"
                tdi = session_attributes.get("trustedDevicesInfo")
                if tdi == None:
                    print "Casa. authenticate. List of user's trusted devices was not updated"
                else:
                    user.setAttribute("oxTrustedDevicesInfo", tdi)
                    userService.updateUser(user)
            else:
                print "Casa. authenticate. 2FA authentication failed"

            return success

        return False
コード例 #44
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        print "Casa. authenticate for step %s" % str(step)

        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

            if StringHelper.isNotEmptyString(
                    user_name) and StringHelper.isNotEmptyString(
                        user_password):

                foundUser = userService.getUserByAttribute(
                    self.uid_attr, user_name)
                #foundUser = userService.getUser(user_name)
                if foundUser == None:
                    print "Casa. authenticate for step 1. Unknown username"
                else:
                    platform_data = self.parsePlatformData(requestParameters)
                    mfaOff = foundUser.getAttribute(
                        "oxPreferredMethod") == None
                    logged_in = False

                    if mfaOff:
                        logged_in = authenticationService.authenticate(
                            user_name, user_password)
                    else:
                        acr = self.getSuitableAcr(foundUser, platform_data)
                        if acr != None:
                            module = self.authenticators[acr]
                            logged_in = module.authenticate(
                                module.configAttrs, requestParameters, step)

                    if logged_in:
                        foundUser = authenticationService.getAuthenticatedUser(
                        )

                        if foundUser == None:
                            print "Casa. authenticate for step 1. Cannot retrieve logged user"
                        else:
                            if mfaOff:
                                identity.setWorkingParameter("skip2FA", True)
                            else:
                                #Determine whether to skip 2FA based on policy defined (global or user custom)
                                skip2FA = self.determineSkip2FA(
                                    userService, identity, foundUser,
                                    platform_data)
                                identity.setWorkingParameter(
                                    "skip2FA", skip2FA)
                                identity.setWorkingParameter("ACR", acr)

                            return True

                    else:
                        print "Casa. authenticate for step 1 was not successful"
            return False

        else:
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "Casa. authenticate for step 2. Cannot retrieve logged user"
                return False

            #see casa.xhtml
            alter = ServerUtil.getFirstValue(requestParameters,
                                             "alternativeMethod")
            if alter != None:
                #bypass the rest of this step if an alternative method was provided. Current step will be retried (see getNextStep)
                self.simulateFirstStep(requestParameters, alter)
                return True

            session_attributes = identity.getSessionId().getSessionAttributes()
            acr = session_attributes.get("ACR")
            #this working parameter is used in casa.xhtml
            identity.setWorkingParameter(
                "methods", ArrayList(self.getAvailMethodsUser(user, acr)))

            success = False
            if acr in self.authenticators:
                module = self.authenticators[acr]
                success = module.authenticate(module.configAttrs,
                                              requestParameters, step)

            #Update the list of trusted devices if 2fa passed
            if success:
                print "Casa. authenticate. 2FA authentication was successful"
                tdi = session_attributes.get("trustedDevicesInfo")
                if tdi == None:
                    print "Casa. authenticate. List of user's trusted devices was not updated"
                else:
                    user.setAttribute("oxTrustedDevicesInfo", tdi)
                    userService.updateUser(user)
            else:
                print "Casa. authenticate. 2FA authentication failed"

            return success

        return False
    def processOtpAuthentication(self, requestParameters, user_name, identity, otp_auth_method):
        facesMessages = CdiUtil.bean(FacesMessages)
        facesMessages.setKeepMessages()

        userService = CdiUtil.bean(UserService)

        otpCode = ServerUtil.getFirstValue(requestParameters, "loginForm:otpCode")
        if StringHelper.isEmpty(otpCode):
            facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to authenticate. OTP code is empty")
            print "OTP. Process OTP authentication. otpCode is empty"

            return False
        
        if otp_auth_method == "enroll":
            # Get key from session
            otp_secret_key_encoded = identity.getWorkingParameter("otp_secret_key")
            if otp_secret_key_encoded == None:
                print "OTP. Process OTP authentication. OTP secret key is invalid"
                return False
            
            otp_secret_key = self.fromBase64Url(otp_secret_key_encoded)

            if self.otpType == "hotp":
                validation_result = self.validateHotpKey(otp_secret_key, 1, otpCode)
                
                if (validation_result != None) and validation_result["result"]:
                    print "OTP. Process HOTP authentication during enrollment. otpCode is valid"
                    # Store HOTP Secret Key and moving factor in user entry
                    otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, validation_result["movingFactor"] )

                    # Add otp_user_external_uid to user's external GUID list
                    find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", otp_user_external_uid)
                    if find_user_by_external_uid != None:
                        return True

                    print "OTP. Process HOTP authentication during enrollment. Failed to update user entry"
            elif self.otpType == "totp":
                validation_result = self.validateTotpKey(otp_secret_key, otpCode)
                if (validation_result != None) and validation_result["result"]:
                    print "OTP. Process TOTP authentication during enrollment. otpCode is valid"
                    # Store TOTP Secret Key and moving factor in user entry
                    otp_user_external_uid = "totp:%s" % otp_secret_key_encoded

                    # Add otp_user_external_uid to user's external GUID list
                    find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", otp_user_external_uid)
                    if find_user_by_external_uid != None:
                        return True

                    print "OTP. Process TOTP authentication during enrollment. Failed to update user entry"
        elif otp_auth_method == "authenticate":
            user_enrollments = self.findEnrollments(user_name)

            if len(user_enrollments) == 0:
                print "OTP. Process OTP authentication. There is no OTP enrollment for user '%s'" % user_name
                facesMessages.add(FacesMessage.SEVERITY_ERROR, "There is no valid OTP user enrollments")
                return False

            if self.otpType == "hotp":
                for user_enrollment in user_enrollments:
                    user_enrollment_data = user_enrollment.split(";")
                    otp_secret_key_encoded = user_enrollment_data[0]

                    # Get current moving factor from user entry
                    moving_factor = StringHelper.toInteger(user_enrollment_data[1])
                    otp_secret_key = self.fromBase64Url(otp_secret_key_encoded)

                    # Validate TOTP
                    validation_result = self.validateHotpKey(otp_secret_key, moving_factor, otpCode)
                    if (validation_result != None) and validation_result["result"]:
                        print "OTP. Process HOTP authentication during authentication. otpCode is valid"
                        otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, moving_factor )
                        new_otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, validation_result["movingFactor"] )
    
                        # Update moving factor in user entry
                        find_user_by_external_uid = userService.replaceUserAttribute(user_name, "oxExternalUid", otp_user_external_uid, new_otp_user_external_uid)
                        if find_user_by_external_uid != None:
                            return True
    
                        print "OTP. Process HOTP authentication during authentication. Failed to update user entry"
            elif self.otpType == "totp":
                for user_enrollment in user_enrollments:
                    otp_secret_key = self.fromBase64Url(user_enrollment)

                    # Validate TOTP
                    validation_result = self.validateTotpKey(otp_secret_key, otpCode)
                    if (validation_result != None) and validation_result["result"]:
                        print "OTP. Process TOTP authentication during authentication. otpCode is valid"
                        return True

        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to authenticate. OTP code is invalid")
        print "OTP. Process OTP authentication. OTP code is invalid"

        return False