def prepareForStep(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()

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

            credentials = Identity.instance().getCredentials()
            user = credentials.getUser()

            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 = DeviceRegistrationService.instance()

            userInum = user.getAttribute("inum")

            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(), u2f_application_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

            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)

            context.set("fido_u2f_authentication_request",
                        ServerUtil.asJson(authenticationRequest))
            context.set("fido_u2f_registration_request",
                        ServerUtil.asJson(registrationRequest))

            return True
Beispiel #2
0
    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
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()

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

            session_state = SessionStateService.instance().getSessionStateFromCookie()
            if StringHelper.isEmpty(session_state):
                print "U2F. Prepare for step 2. Failed to determine session_state"
                return False

            credentials = Identity.instance().getCredentials()
            user = credentials.getUser()

            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 = DeviceRegistrationService.instance()

            userInum = user.getAttribute("inum")

            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_state)
                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

            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_state)

            context.set("fido_u2f_authentication_request", ServerUtil.asJson(authenticationRequest))
            context.set("fido_u2f_registration_request", ServerUtil.asJson(registrationRequest))

            return True
Beispiel #4
0
 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))
    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"]
Beispiel #6
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)

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

        if (step == 1):
            print "Basic (with password update). Authenticate for step 1"

            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

            return True
        elif (step == 2):
            print "Basic (with password update). Authenticate for step 2"

            update_button = ServerUtil.getFirstValue(requestParameters, "loginForm:updateButton")
            if ArrayHelper.isEmpty(update_button):
                return True

            new_password = ServerUtil.getFirstValue(requestParameters, "new_password")
            if ArrayHelper.isEmpty(new_password):
                print "Basic (with password update). Authenticate for step 2. New password is empty"
                return False

            print "Basic (with password update). Authenticate for step 2. Attempting to set new user '" + user_name + "' password"

            find_user_by_uid = userService.getUser(user_name)
            if (find_user_by_uid == None):
                print "Basic (with password update). Authenticate for step 2. Failed to find user"
                return False
            
            find_user_by_uid.setAttribute("userPassword", new_password)
            userService.updateUser(find_user_by_uid)
            print "Basic (with password update). Authenticate for step 2. Password updated successfully"

            return True
        else:
            return False
    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
Beispiel #8
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
Beispiel #9
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
Beispiel #10
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        context = Contexts.getEventContext()
        session_attributes = context.get("sessionAttributes")

        self.setEventContextParameters(context)

        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(user_name)
                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'" % (user_name, otp_auth_method)
                    
            if otp_auth_method == "enroll":
                print "OTP. Authenticate for step 1. Setting count steps: '%s'" % 3
                context.set("otp_count_login_steps", 3)

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

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

            session_state_validation = self.validateSessionState(session_attributes)
            if not session_state_validation:
                return False

            # Restore state from session
            otp_auth_method = session_attributes.get("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_name, session_attributes, 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"

            session_state_validation = self.validateSessionState(session_attributes)
            if not session_state_validation:
                return False

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

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

            return otp_auth_result
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        context = Contexts.getEventContext()
        userService = UserService.instance()

        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"
                context.set("cert_selected", False)

                # Return True to inform user how to reset workflow
                return True
            else:
                context.set("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
                context.set("cert_valid", False)

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

            context.set("cert_valid", True)

            # Calculate certificate fingerprint
            x509CertificateFingerprint = self.calculateCertificateFingerprint(
                x509Certificate)
            context.set("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"
                    context.set("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"
                    context.set("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"
            context.set("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

            credentials = Identity.instance().getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                logged_in = userService.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
    def authenticate(self, configurationAttributes, requestParameters, step):

        print "TwilioSMS. Authenticate for Step %s" % str(step)
        identity = CdiUtil.bean(Identity)
        authenticationService = CdiUtil.bean(AuthenticationService)
        user = authenticationService.getAuthenticatedUser()

        if step == 1:

            if user == None:
                credentials = identity.getCredentials()
                user_name = credentials.getUsername()
                user_password = credentials.getPassword()

                if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password):
                    authenticationService.authenticate(user_name, user_password)
                    user = authenticationService.getAuthenticatedUser()

            if user == None:
                return False

            #Attempt to send message now if user has only one mobile number
            mobiles = user.getAttributeValues("mobile")

            if mobiles == None:
                return False
            else:
                code = random.randint(100000, 999999)
                identity.setWorkingParameter("randCode", code)

                sid = configurationAttributes.get("twilio_sid").getValue2()
                token = configurationAttributes.get("twilio_token").getValue2()
                self.from_no = configurationAttributes.get("from_number").getValue2()
                Twilio.init(sid, token)

                if mobiles.size() == 1:
                    self.sendMessage(code, mobiles.get(0))
                else:
                    chopped = ""
                    for numb in mobiles:
                        l = len(numb)
                        chopped += "," + numb[max(0, l-4) : l]

                    #converting to comma-separated list (identity does not remember lists in 3.1.3)
                    identity.setWorkingParameter("numbers", Joiner.on(",").join(mobiles.toArray()))
                    identity.setWorkingParameter("choppedNos", chopped[1:])

                return True
        else:
            if user == None:
                return False

            session_attributes = identity.getSessionId().getSessionAttributes()
            code = session_attributes.get("randCode")
            numbers = session_attributes.get("numbers")

            if step == 2 and numbers != None:
                #Means the selection number page was used
                idx = ServerUtil.getFirstValue(requestParameters, "TwilioSmsloginForm:indexOfNumber")
                if idx != None and code != None:
                    sendToNumber = numbers.split(",")[int(idx)]
                    self.sendMessage(code, sendToNumber)
                    return True
                else:
                    return False

            success = False
            form_passcode = ServerUtil.getFirstValue(requestParameters, "passcode")

            if form_passcode != None and code == form_passcode:
                print "TwilioSMS. authenticate. 6-digit code matches with code sent via SMS"
                success = True
            else:
                facesMessages = CdiUtil.bean(FacesMessages)
                facesMessages.setKeepMessages()
                facesMessages.clear()
                facesMessages.add(FacesMessage.SEVERITY_ERROR, "Wrong code entered")

            return success
Beispiel #13
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:
            jwt_param = None
            if self.isInboundFlow(identity):
                print "Passport. authenticate for step 1. Detected inbound Saml flow"
                jwt_param = identity.getSessionId().getSessionAttributes().get(AuthorizeRequestParam.STATE)

            if jwt_param == None:
                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
                attr = self.getRemoteAttr("mail")
                user_profile = self.getProfileFromJson(json)
                user_profile[attr] = 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 processOtpAuthentication(self, requestParameters, user_name, session_attributes, otp_auth_method):
        facesMessages = FacesMessages.instance()
        FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(True)

        userService = UserService.instance()

        otpCode = ServerUtil.getFirstValue(requestParameters, "loginForm:otpCode")
        if StringHelper.isEmpty(otpCode):
            facesMessages.add(StatusMessage.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 = session_attributes.get("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(StatusMessage.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(StatusMessage.Severity.ERROR, "Failed to authenticate. OTP code is invalid")
        print "OTP. Process OTP authentication. OTP code is invalid"

        return False
Beispiel #15
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:
            # Determine if external provider must be used
            provider = ServerUtil.getFirstValue(requestParameters,
                                                "loginForm:provider")
            if StringHelper.isNotEmpty(provider):
                url = self.getAuthzRequestUrl(provider)
                if url != None:
                    CdiUtil.bean(FacesService).redirectToExternalURL(url)
                return url != None

            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:
                    acr = foundUser.getAttribute("oxPreferredMethod")
                    logged_in = False

                    if acr == None:
                        logged_in = authenticationService.authenticate(
                            user_name, user_password)
                    elif acr in self.authenticators:
                        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 acr == None:
                                identity.setWorkingParameter("skip2FA", True)
                            else:
                                #Determine whether to skip 2FA based on policy defined (global or user custom)
                                skip2FA = self.determineSkip2FA(
                                    userService, identity, foundUser,
                                    ServerUtil.getFirstValue(
                                        requestParameters,
                                        "loginForm:platform"))
                                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",
                                         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
Beispiel #16
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        context = Contexts.getEventContext()
        session_attributes = context.get("sessionAttributes")

        client_redirect_uri = self.getClientRedirecUri(session_attributes)
        if client_redirect_uri == None:
            print "Super-Gluu. Authenticate. redirect_uri is not set"
            return False

        self.setEventContextParameters(context)

        userService = UserService.instance()
        deviceRegistrationService = DeviceRegistrationService.instance()
        if step == 1:
            print "Super-Gluu. Authenticate for step 1"
            if self.oneStep:
  
                session_device_status = self.getSessionDeviceStatus(session_attributes, user_name)
                if session_device_status == None:
                    return

                u2f_device_id = session_device_status['device_id']

                validation_result = self.validateSessionDeviceStatus(client_redirect_uri, session_device_status)
                if validation_result:
                    print "Super-Gluu. Authenticate for step 1. User successfully authenticated with u2f_device '%s'" % u2f_device_id
                else:
                    return False
                    
                if not session_device_status['one_step']:
                    print "Super-Gluu. Authenticate for step 1. u2f_device '%s' is not one step device" % u2f_device_id
                    return False
                    
                # There are two steps only in enrollment mode
                if session_device_status['enroll']:
                    return validation_result

                context.set("super_gluu_count_login_steps", 1)

                user_inum = session_device_status['user_inum']

                u2f_device = deviceRegistrationService.findUserDeviceRegistration(user_inum, u2f_device_id, "oxId")
                if u2f_device == None:
                    print "Super-Gluu. Authenticate for step 1. Failed to load u2f_device '%s'" % u2f_device_id
                    return False

                logged_in = userService.authenticate(user_name)
                if not logged_in:
                    print "Super-Gluu. Authenticate for step 1. Failed to authenticate user '%s'" % user_name
                    return False

                print "Super-Gluu. Authenticate for step 1. User '%s' successfully authenticated with u2f_device '%s'" % (user_name, u2f_device_id)
                
                return True
            elif self.twoStep:
                authenticated_user = self.processBasicAuthentication(credentials)
                if authenticated_user == None:
                    return False
    
                auth_method = 'authenticate'
                enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
                if StringHelper.isNotEmpty(enrollment_mode):
                    auth_method = 'enroll'
                
                if auth_method == 'authenticate':
                    user_inum = userService.getUserInum(authenticated_user)
                    u2f_devices_list = deviceRegistrationService.findUserDeviceRegistrations(user_inum, client_redirect_uri, "oxId")
                    if u2f_devices_list.size() == 0:
                        auth_method = 'enroll'
                        print "Super-Gluu. Authenticate for step 1. There is no U2F '%s' user devices associated with application '%s'. Changing auth_method to '%s'" % (user_name, client_redirect_uri, auth_method)
    
                print "Super-Gluu. Authenticate for step 1. auth_method: '%s'" % auth_method
                
                context.set("super_gluu_auth_method", auth_method)

                return True

            return False
        elif step == 2:
            print "Super-Gluu. Authenticate for step 2"
            session_attributes = context.get("sessionAttributes")

            session_device_status = self.getSessionDeviceStatus(session_attributes, user_name)
            if session_device_status == None:
                return False

            u2f_device_id = session_device_status['device_id']

            # There are two steps only in enrollment mode
            if self.oneStep and session_device_status['enroll']:
                authenticated_user = self.processBasicAuthentication(credentials)
                if authenticated_user == None:
                    return False

                user_inum = userService.getUserInum(authenticated_user)
                
                attach_result = deviceRegistrationService.attachUserDeviceRegistration(user_inum, u2f_device_id)

                print "Super-Gluu. Authenticate for step 2. Result after attaching u2f_device '%s' to user '%s': '%s'" % (u2f_device_id, user_name, attach_result) 

                return attach_result
            elif self.twoStep:
                if user_name == None:
                    print "Super-Gluu. Authenticate for step 2. Failed to determine user name"
                    return False

                validation_result = self.validateSessionDeviceStatus(client_redirect_uri, session_device_status, user_name)
                if validation_result:
                    print "Super-Gluu. Authenticate for step 2. User '%s' successfully authenticated with u2f_device '%s'" % (user_name, u2f_device_id)
                else:
                    return False
                
                super_gluu_request = json.loads(session_device_status['super_gluu_request'])
                auth_method = super_gluu_request['method']
                if auth_method in ['enroll', 'authenticate']:
                    return validation_result

                print "Super-Gluu. Authenticate for step 2. U2F auth_method is invalid"

            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)
        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
Beispiel #18
0
            print "Passport-social: Basic Authentication"
            credentials = 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)

            print "Passport-social: Basic Authentication returning %s" % logged_in
            return logged_in
        else:
            facesContext = CdiUtil.bean(FacesContext)

            # Get JWT token if it's post back call
            jwt_param = ServerUtil.getFirstValue(requestParameters, "user")
            if StringHelper.isEmpty(jwt_param):
                print "Passport-social: Authenticate for step 1. JWT token is missing"
                return False

            # Parse JWT token
            jwt = Jwt.parse(jwt_param)

            # Validate signature
            print "Passport-social: Authenticate for step 1. Checking JWT token signature: '%s'" % jwt
            appConfiguration = AppConfiguration()
            appConfiguration.setWebKeysStorage(WebKeyStorage.KEYSTORE)
            appConfiguration.setKeyStoreFile(self.keyStoreFile)
            appConfiguration.setKeyStoreSecret(self.keyStorePassword)

            cryptoProvider = CryptoProviderFactory.getCryptoProvider(appConfiguration)
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        context = Contexts.getEventContext()
        session_attributes = context.get("sessionAttributes")

        self.setEventContextParameters(context)

        if (step == 1):
            print "UAF. Authenticate for step 1"
            
            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
            
            context.set("uaf_auth_method", uaf_auth_method)

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

            session_state = SessionStateService.instance().getSessionStateFromCookie()
            if StringHelper.isEmpty(session_state):
                print "UAF. Prepare for step 2. Failed to determine session_state"
                return False

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

            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 = UserService.instance()

                # 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):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        context = Contexts.getEventContext()
        userService = UserService.instance()

        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
            
            return True
        elif (step == 2):
            print "Cert. Authenticate for step 2"

            # Validate if user selected certificate
            request = FacesContext.getCurrentInstance().getExternalContext().getRequest()
            x509Certificates = request.getAttribute('javax.servlet.request.X509Certificate')
            if (x509Certificates == None) or (len(x509Certificates) == 0):
                print "Cert. Authenticate for step 2. User not selected any certs"
                context.set("cert_selected", False)
                
                # Return True to inform user how to reset workflow
                return True

            context.set("cert_selected", True)
            
            # Use only first certificate for validation 
            x509Certificate = x509Certificates[0]
            print "Cert. Authenticate for step 2. User selected certificate with DN '%s'" % x509Certificate.getSubjectX500Principal()
            
            # Validate certificates which user selected
            valid = self.validateCertificate(x509Certificate)
            if not valid:
                print "Cert. Authenticate for step 2. Certificate DN '%s' is not valid" % x509Certificate.getSubjectX500Principal()
                context.set("cert_valid", False)
                
                # Return True to inform user how to reset workflow
                return True

            context.set("cert_valid", True)
            context.set("cert_x509", x509Certificate)
            
            # Calculate certificate fingerprint
            x509CertificateFingerprint = self.calculateCertificateFingerprint(x509Certificate)
            context.set("cert_x509_fingerprint", x509CertificateFingerprint)
            print "Cert. Authenticate for step 2. Fingerprint is '%s' of certificate with DN '%s'" % (x509CertificateFingerprint, x509Certificate.getSubjectX500Principal())
            
            # 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"
                    context.set("cert_user_external_uid", cert_user_external_uid)
                    return True
                else:
                    print "Cert. Authenticate for step 2. Mapping cet to user account is not allowed"
                    context.set("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"
            context.set("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

            credentials = Identity.instance().getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                logged_in = userService.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
 def getUserValueFromAuth(self,remote_attr,requestParameters):
     try:
         val=ServerUtil.getFirstValue(requestParameters, "loginForm:"+remote_attr)
         return val.decode('utf-8')
     except Exception,err:
         print("Exception inside getUserValueFromAuth "+str(err))
Beispiel #22
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

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

        session_attributes = identity.getSessionId().getSessionAttributes()

        client_redirect_uri = self.getClientRedirecUri(session_attributes)
        if client_redirect_uri == None:
            print "Super-Gluu. Authenticate. redirect_uri is not set"
            return False

        self.setRequestScopedParameters(identity, step)

        # Validate form result code and initialize QR code regeneration if needed (retry_current_step = True)
        identity.setWorkingParameter("retry_current_step", False)
        form_auth_result = ServerUtil.getFirstValue(requestParameters, "auth_result")
        if StringHelper.isNotEmpty(form_auth_result):
            print "Super-Gluu. Authenticate for step %s. Get auth_result: '%s'" % (step, form_auth_result)
            if form_auth_result in ['error']:
                return False

            if form_auth_result in ['timeout']:
                if ((step == 1) and self.oneStep) or ((step == 2) and self.twoStep):        
                    print "Super-Gluu. Authenticate for step %s. Reinitializing current step" % step
                    identity.setWorkingParameter("retry_current_step", True)
                    return False

        userService = CdiUtil.bean(UserService)
        deviceRegistrationService = CdiUtil.bean(DeviceRegistrationService)
        if step == 1:
            print "Super-Gluu. Authenticate for step 1"

            user_name = credentials.getUsername()
            if self.oneStep:
                session_device_status = self.getSessionDeviceStatus(session_attributes, user_name)
                if session_device_status == None:
                    return False

                u2f_device_id = session_device_status['device_id']

                validation_result = self.validateSessionDeviceStatus(client_redirect_uri, session_device_status)
                if validation_result:
                    print "Super-Gluu. Authenticate for step 1. User successfully authenticated with u2f_device '%s'" % u2f_device_id
                else:
                    return False
                    
                if not session_device_status['one_step']:
                    print "Super-Gluu. Authenticate for step 1. u2f_device '%s' is not one step device" % u2f_device_id
                    return False
                    
                # There are two steps only in enrollment mode
                if session_device_status['enroll']:
                    return validation_result

                identity.setWorkingParameter("super_gluu_count_login_steps", 1)

                user_inum = session_device_status['user_inum']

                u2f_device = deviceRegistrationService.findUserDeviceRegistration(user_inum, u2f_device_id, "oxId")
                if u2f_device == None:
                    print "Super-Gluu. Authenticate for step 1. Failed to load u2f_device '%s'" % u2f_device_id
                    return False

                logged_in = authenticationService.authenticate(user_name)
                if not logged_in:
                    print "Super-Gluu. Authenticate for step 1. Failed to authenticate user '%s'" % user_name
                    return False

                print "Super-Gluu. Authenticate for step 1. User '%s' successfully authenticated with u2f_device '%s'" % (user_name, u2f_device_id)
                
                return True
            elif self.twoStep:
                authenticated_user = self.processBasicAuthentication(credentials)
                if authenticated_user == None:
                    return False

                if (self.use_super_gluu_group):
                    print "Super-Gluu. Authenticate for step 1. Checking if user belong to super_gluu group"
                    is_member_super_gluu_group = self.isUserMemberOfGroup(authenticated_user, self.audit_attribute, self.super_gluu_group)
                    if (is_member_super_gluu_group):
                        print "Super-Gluu. Authenticate for step 1. User '%s' member of super_gluu group" % authenticated_user.getUserId()
                        super_gluu_count_login_steps = 2
                    else:
                        if self.use_audit_group:
                            self.processAuditGroup(authenticated_user, self.audit_attribute, self.audit_group)
                        super_gluu_count_login_steps = 1
    
                    identity.setWorkingParameter("super_gluu_count_login_steps", super_gluu_count_login_steps)
                    
                    if super_gluu_count_login_steps == 1:
                        return True
    
                auth_method = 'authenticate'
                enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
                if StringHelper.isNotEmpty(enrollment_mode):
                    auth_method = 'enroll'
                
                if auth_method == 'authenticate':
                    user_inum = userService.getUserInum(authenticated_user)
                    u2f_devices_list = deviceRegistrationService.findUserDeviceRegistrations(user_inum, client_redirect_uri, "oxId")
                    if u2f_devices_list.size() == 0:
                        auth_method = 'enroll'
                        print "Super-Gluu. Authenticate for step 1. There is no U2F '%s' user devices associated with application '%s'. Changing auth_method to '%s'" % (user_name, client_redirect_uri, auth_method)
    
                print "Super-Gluu. Authenticate for step 1. auth_method: '%s'" % auth_method
                
                identity.setWorkingParameter("super_gluu_auth_method", auth_method)

                return True

            return False
        elif step == 2:
            print "Super-Gluu. Authenticate for step 2"

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

            session_attributes = identity.getSessionId().getSessionAttributes()

            session_device_status = self.getSessionDeviceStatus(session_attributes, user_name)
            if session_device_status == None:
                return False

            u2f_device_id = session_device_status['device_id']

            # There are two steps only in enrollment mode
            if self.oneStep and session_device_status['enroll']:
                authenticated_user = self.processBasicAuthentication(credentials)
                if authenticated_user == None:
                    return False

                user_inum = userService.getUserInum(authenticated_user)
                
                attach_result = deviceRegistrationService.attachUserDeviceRegistration(user_inum, u2f_device_id)

                print "Super-Gluu. Authenticate for step 2. Result after attaching u2f_device '%s' to user '%s': '%s'" % (u2f_device_id, user_name, attach_result) 

                return attach_result
            elif self.twoStep:
                if user_name == None:
                    print "Super-Gluu. Authenticate for step 2. Failed to determine user name"
                    return False

                validation_result = self.validateSessionDeviceStatus(client_redirect_uri, session_device_status, user_name)
                if validation_result:
                    print "Super-Gluu. Authenticate for step 2. User '%s' successfully authenticated with u2f_device '%s'" % (user_name, u2f_device_id)
                else:
                    return False
                
                super_gluu_request = json.loads(session_device_status['super_gluu_request'])
                auth_method = super_gluu_request['method']
                if auth_method in ['enroll', 'authenticate']:
                    if validation_result and self.use_audit_group:
                        user = authenticationService.getAuthenticatedUser()
                        self.processAuditGroup(user, self.audit_attribute, self.audit_group)

                    return validation_result

                print "Super-Gluu. Authenticate for step 2. U2F auth_method is invalid"

            return False
        else:
            return False
Beispiel #23
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"
            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
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().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 = UserService.instance()
                logged_in = userService.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

            credentials = Identity.instance().getCredentials()
            user = credentials.getUser()
            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
Beispiel #25
0
    def authenticate(self, configurationAttributes, requestParameters, step):
     
                    
        print "Forgot Password - Authenticate for step %s" % step

       
        identity = CdiUtil.bean(Identity)
        

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

            print "Forgot Password - user_name = " + str(user_name)


            authenticationService = CdiUtil.bean(AuthenticationService)

            logged_in = authenticationService.authenticate(user_name, user_password)
            

            
            if not logged_in:

                
                email = ServerUtil.getFirstValue(requestParameters, "ForgotPasswordForm:useremail")
                validator = EmailValidator()
                if not validator.check(email):
                    print "Forgot Password - Email format invalid"
                    return False

                else:
                    print "Forgot Password -Email format valid"
 
                    print "Forgot Password - Entered email is %s" % email
                    identity.setWorkingParameter("useremail",email)
                    
                    # Just trying to get the user by the email
                    user_service = CdiUtil.bean(UserService)
                    user2 = user_service.getUserByAttribute("mail", email)

                    if user2 is not None:
                    
                        print user2
                        print "Forgot Password - User with e-mail %s found." % user2.getAttribute("mail")
                    
                        # send email
                        new_token = Token()
                        token = new_token.generateToken()                
                        sender = EmailSender()
                        sender.sendEmail(email,token)

                    
                        identity.setWorkingParameter("token", token)
                        print identity.getWorkingParameter("token")
                    
 
                        
                    else:
                        print "Forgot Password - User with e-mail %s not found" % email

                    return True


            else:
                

                user = authenticationService.getAuthenticatedUser()
                print "Forgot Password - User %s is authenticated" % user.getUserId()

                

                return True

        if step == 2:

            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            
           
            authenticationService = CdiUtil.bean(AuthenticationService)
            logged_in = authenticationService.authenticate(user_name, user_password)


            input_token = ServerUtil.getFirstValue(requestParameters, "ResetTokenForm:inputToken")
            # retrieves token typed by user
            print "Forgot Password - Token inputed by user is %s" % input_token

            token = identity.getWorkingParameter("token")
            print "Forgot Password - Retrieved token"
            email = identity.getWorkingParameter("useremail")
            print "Forgot Password - Retrieved email" 

            if input_token == token:
                print "Forgot Password - token entered correctly"
                identity.setWorkingParameter("token_valid",True)
                
                return True

            else:
                print "Forgot Password - wrong token"
                return False

        
        # step 3 enters new password
        if step == 3:
            user_service = CdiUtil.bean(UserService)

            email = identity.getWorkingParameter("useremail")
            user2 = user_service.getUserByAttribute("mail", email)
            user_name = user2.getUserId()
            
            
            new_password = ServerUtil.getFirstValue(requestParameters, "UpdatePasswordForm:newPassword")
            
            print "Forgot Password - New password submited"
        


            # update user info with new password
            user2.setAttribute("userPassword",new_password)

            user_service.updateUser(user2)

            authenticationService2 = CdiUtil.bean(AuthenticationService)
            
            # authenticates and login user
            login = authenticationService2.authenticate(user_name, new_password)
            
            return True
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        context = Contexts.getEventContext()
        session_attributes = context.get("sessionAttributes")

        self.setEventContextParameters(context)

        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(user_name)
                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'" % (user_name, otp_auth_method)
                    
            if otp_auth_method == "enroll":
                print "OTP. Authenticate for step 1. Setting count steps: '%s'" % 3
                context.set("otp_count_login_steps", 3)

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

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

            session_state_validation = self.validateSessionState(session_attributes)
            if not session_state_validation:
                return False

            # Restore state from session
            otp_auth_method = session_attributes.get("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_name, session_attributes, 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"

            session_state_validation = self.validateSessionState(session_attributes)
            if not session_state_validation:
                return False

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

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

            return otp_auth_result
        else:
            return False
 def getUserValueFromAuth(self, remote_attr, requestParameters):
     try:
         toBeFeatched = "loginForm:" + remote_attr
         return ServerUtil.getFirstValue(requestParameters, toBeFeatched)
     except Exception, err:
         print("Passport: Exception inside getUserValueFromAuth " + str(err))
Beispiel #28
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        userService = UserService.instance()
        session_attributes = context.get("sessionAttributes")

        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 = Identity.instance().getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            
            logged_in = False
            if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password):
                logged_in = userService.authenticate(user_name, user_password)
            
            if not logged_in:
                return False

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

            try:
                mobile_number = foundUser.getAttribute("phoneNumberVerified")
            except:
                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 
            context.set("code", code)

            client = TwilioRestClient(self.ACCOUNT_SID, self.AUTH_TOKEN)
            bodyParam = BasicNameValuePair("Body", str(code))
            toParam = BasicNameValuePair("To", mobile_number)
            fromParam = BasicNameValuePair("From", self.FROM_NUMBER)

            params = ArrayList()
            params.add(bodyParam)
            params.add(toParam)
            params.add(fromParam)
            
            try:
                messageFactory = client.getAccount().getMessageFactory()
                message = messageFactory.create(params)

                print 'TwilioSMs, Message Sid: %s' % (message.getSid())
                return True
            except:
                print "TwilioSMS. Error sending message to Twilio"

            return False
        elif step == 2:
            # Retrieve the session attribute
            print "TwilioSMS. Step 2 SMS/OTP Authentication"
            code = session_attributes.get("code")
            print "TwilioSMS. Code: %s" % str(code)
    
            if code is None:
                print "TwilioSMS. Failed to find previously sent code"
                return False 
    
            if form_passcode is None:
                print "TwilioSMS. Passcode is empty"
                return False 
    
            if len(form_passcode) != 6:
                print "TwilioSMS. Passcode from response is not 6 digits: %s" % form_passcode
                return False

            if form_passcode == code:
                print "TiwlioSMS, SUCCESS! User entered the same code!" 
                return True

            print "TwilioSMS. FAIL! User entered the wrong code! %s != %s" % (form_passcode, code)

            return False            

        print "TwilioSMS. ERROR: step param not found or != (1|2)"

        return False
Beispiel #29
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":
            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
Beispiel #30
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().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 = UserService.instance()
                logged_in = userService.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 = AuthenticationService.instance()
            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):
        '''
        Authenticates user
        Step 1 will be defined according to SCRIPT_FUNCTION custom attribute
        returns: boolean
        '''

        #gets custom attribute
        sf = configurationAttributes.get("SCRIPT_FUNCTION").getValue2()

        print "Forgot Password - %s - Authenticate for step %s" % (sf, step)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()
        user_name = credentials.getUsername()
        user_password = credentials.getPassword()


        if step == 1:

            if sf == "forgot_password":

                
                authenticationService = CdiUtil.bean(AuthenticationService)

                logged_in = authenticationService.authenticate(user_name, user_password)

                
                if not logged_in:

                    
                    email = ServerUtil.getFirstValue(requestParameters, "ForgotPasswordForm:useremail")
                    validator = EmailValidator()
                    if not validator.check(email):
                        print "Forgot Password - Email format invalid"
                        return False

                    else:
                        print "Forgot Password -Email format valid"
     
                        print "Forgot Password - Entered email is %s" % email
                        identity.setWorkingParameter("useremail",email)
                        
                        # Just trying to get the user by the email
                        user_service = CdiUtil.bean(UserService)
                        user2 = user_service.getUserByAttribute("mail", email)

                        if user2 is not None:
                        
                            print user2
                            print "Forgot Password - User with e-mail %s found." % user2.getAttribute("mail")
                        
                            # send email
                            new_token = Token()
                            token = new_token.generateToken()                
                            sender = EmailSender()
                            print "Email: " + email
                            print "Token: " + token
                            sender.sendEmail(email,token)

                        
                            identity.setWorkingParameter("token", token)
                            print identity.getWorkingParameter("token")
                        
     
                            
                        else:
                            print "Forgot Password - User with e-mail %s not found" % email

                        return True


                else:
                    # if user is already authenticated, returns true.

                    user = authenticationService.getAuthenticatedUser()
                    print "Forgot Password - User %s is authenticated" % user.getUserId()

                    return True

            if sf == "email_2FA":

                try:
                    # Just trying to get the user by the uid
                    authenticationService = CdiUtil.bean(AuthenticationService)
                    logged_in = authenticationService.authenticate(user_name, user_password)
                    
                    print 'email_2FA user_name: ' + str(user_name)
                    
                    user_service = CdiUtil.bean(UserService)
                    user2 = user_service.getUserByAttribute("uid", user_name)

                    if user2 is not None:
                        print "user:"******"Forgot Password - User with e-mail %s found." % user2.getAttribute("mail")
                        email = user2.getAttribute("mail")
                        uid = user2.getAttribute("uid")

                        # send token
                        # send email
                        new_token = Token()
                        token = new_token.generateToken()                
                        sender = EmailSender()
                        print "Email: " + email
                        print "Token: " + token
                        sender.sendEmail(email,token)

                        identity.setWorkingParameter("token", token)

                        return True

                except AuthenticationException as err:
                    print err
                    return False

                
   

        if step == 2:
            # step 2 user enters token
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            
            authenticationService = CdiUtil.bean(AuthenticationService)
            logged_in = authenticationService.authenticate(user_name, user_password)

            # retrieves token typed by user
            input_token = ServerUtil.getFirstValue(requestParameters, "ResetTokenForm:inputToken")

            print "Forgot Password - Token inputed by user is %s" % input_token

            token = identity.getWorkingParameter("token")
            print "Forgot Password - Retrieved token"
            email = identity.getWorkingParameter("useremail")
            print "Forgot Password - Retrieved email" 

            # compares token sent and token entered by user
            if input_token == token:
                print "Forgot Password - token entered correctly"
                identity.setWorkingParameter("token_valid", True)
                
                return True

            else:
                print "Forgot Password - wrong token"
                return False

        
        if step == 3:
            # step 3 enters new password (only runs if custom attibute is forgot_password

            user_service = CdiUtil.bean(UserService)

            email = identity.getWorkingParameter("useremail")
            user2 = user_service.getUserByAttribute("mail", email)


            user_name = user2.getUserId()
            
            new_password = ServerUtil.getFirstValue(requestParameters, "UpdatePasswordForm:newPassword")
            
            print "Forgot Password - New password submited"
        
            # update user info with new password
            user2.setAttribute("userPassword",new_password)
            print "Forgot Password - user uid is %s" % user_name
            print "Forgot Password - Updating user with new password..."
            user_service.updateUser(user2)
            print "Forgot Password - User updated with new password"
            # authenticates and login user
            print "Forgot Password - Loading authentication service..."
            authenticationService2 = CdiUtil.bean(AuthenticationService)

            print "Forgot Password - Trying to authenticate user..."
            login = authenticationService2.authenticate(user_name, new_password)
            
            return True
Beispiel #32
0
#                except (HESAuthenticator.UserNotFoundException, HESAuthenticator.InvalidCredentialsException, HESAuthenticator.UserIsLockedout), ex:
#                    logged_in = False
#                    print ex.class.name + ex.message
                except Exception, ex:
                    logged_in = False
                    print ex.class.name + ex.message

        else:
            print "OTP. Authenticate for step 2"

            session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie()
            if StringHelper.isEmpty(session_id):
                print "OTP. Validate session id. Failed to determine session_id"
                return False

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

            user_name = identity.getWorkingParameter("hideez_user_name")
            user_password = identity.getWorkingParameter("hideez_user_password")

            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password) and StringHelper.isNotEmptyString(otpCode)):
                try:
                    authNr = HESAuthenticator(self.hideezUrl)
                    hUser = authNr.authN(user_name, user_password, otpCode)
                    print "Hideez user: Email %s, Name %s, Surname %s" % (hUser.email, hUser.firstName, hUser.lastName)
                    authenticationService.authenticate(user_name)
                    logged_in = True
    def authenticate(self, configurationAttributes, requestParameters, step):
        print "ThumbSignIn. Inside authenticate. Step %d" % step
        authenticationService = CdiUtil.bean(AuthenticationService)
        identity = CdiUtil.bean(Identity)

        global ts_host
        global ts_apiKey
        global ts_apiSecret
        global ts_statusPath

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

        thumbsigninApiController = ThumbsigninApiController()

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

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

            #Logic for ThumbSignIn Authentication Flow
            if (login_flow == "ThumbSignIn_Authentication"
                    or login_flow == "ThumbSignIn_RegistrationSucess"):
                identity.setWorkingParameter("userLoginFlow", login_flow)
                print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(
                    "userLoginFlow")

                transactionId = ServerUtil.getFirstValue(
                    requestParameters, "transactionId")
                print "ThumbSignIn. Value of transactionId is %s" % transactionId
                getUserRequest = "getUser/" + transactionId
                print "ThumbSignIn. Value of getUserRequest is %s" % getUserRequest

                getUserResponseJsonStr = thumbsigninApiController.handleThumbSigninRequest(
                    getUserRequest, ts_apiKey, ts_apiSecret)
                print "ThumbSignIn. Value of getUserResponseJsonStr is %s" % getUserResponseJsonStr
                getUserResponseJsonObj = JSONObject(getUserResponseJsonStr)
                thumbSignIn_UserId = getUserResponseJsonObj.get("userId")
                print "ThumbSignIn. Value of thumbSignIn_UserId is %s" % thumbSignIn_UserId

                logged_in_status = authenticationService.authenticate(
                    thumbSignIn_UserId)
                print "ThumbSignIn. logged_in status : %r" % (logged_in_status)
                return logged_in_status

            #Logic for ThumbSignIn Registration Flow
            identity.setWorkingParameter("userLoginFlow",
                                         "ThumbSignIn_Registration")
            print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(
                "userLoginFlow")
            credentials = identity.getCredentials()

            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            print "ThumbSignIn. user_name: " + user_name
            #print "ThumbSignIn. user_password: "******"ThumbSignIn. Status of LDAP Authentication : %r" % (
                logged_in)

            if (not logged_in):
                # Invoking the authenticate ThumbSignIn API via the Java SDK
                authenticateResponseJsonStr = thumbsigninApiController.handleThumbSigninRequest(
                    "authenticate", ts_apiKey, ts_apiSecret)
                print "ThumbSignIn. Value of authenticateResponseJsonStr is %s" % authenticateResponseJsonStr

                authenticateResponseJsonObj = JSONObject(
                    authenticateResponseJsonStr)
                transactionId = authenticateResponseJsonObj.get(
                    "transactionId")
                authenticationStatusRequest = "authStatus/" + transactionId
                print "ThumbSignIn. Value of authenticationStatusRequest is %s" % authenticationStatusRequest

                authorizationHeaderJsonStr = thumbsigninApiController.getAuthorizationHeaderJsonStr(
                    authenticationStatusRequest, ts_apiKey, ts_apiSecret)
                print "ThumbSignIn. Value of authorizationHeaderJsonStr is %s" % authorizationHeaderJsonStr
                # {"authHeader":"HmacSHA256 Credential=XXX, SignedHeaders=accept;content-type;x-ts-date, Signature=XXX","XTsDate":"XXX"}

                authorizationHeaderJsonObj = JSONObject(
                    authorizationHeaderJsonStr)
                authorizationHeader = authorizationHeaderJsonObj.get(
                    "authHeader")
                xTsDate = authorizationHeaderJsonObj.get("XTsDate")
                print "ThumbSignIn. Value of authorizationHeader is %s" % authorizationHeader
                print "ThumbSignIn. Value of xTsDate is %s" % xTsDate

                identity.setWorkingParameter("authenticateResponseJsonStr",
                                             authenticateResponseJsonStr)
                identity.setWorkingParameter("authorizationHeader",
                                             authorizationHeader)
                identity.setWorkingParameter("xTsDate", xTsDate)
                return False

            print "ThumbSignIn. Authenticate for step 1 successful"
            return True

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

            if (identity.isSetWorkingParameter("userLoginFlow")):
                userLoginFlow = identity.getWorkingParameter("userLoginFlow")
                print "ThumbSignIn. Value of userLoginFlow is %s" % userLoginFlow
            else:
                identity.setWorkingParameter("userLoginFlow",
                                             "ThumbSignIn_Registration")
                print "ThumbSignIn. Setting the value of userLoginFlow to %s" % identity.getWorkingParameter(
                    "userLoginFlow")

            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "ThumbSignIn. Registration flow (step 2). Failed to determine user name"
                return False

            user_name = user.getUserId()
            print "ThumbSignIn. Registration flow (step 2). user_name: " + user_name

            print "ThumbSignIn. Registration flow (step 2) successful"
            return True
        else:
            return False
Beispiel #34
0
class PersonAuthentication(PersonAuthenticationType):
    def __init__(self, currentTimeMillis):
        self.currentTimeMillis = currentTimeMillis

    def init(self, 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.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 1

    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"

            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
Beispiel #35
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"

            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
Beispiel #36
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        userService = UserService.instance()
        session_attributes = context.get("sessionAttributes")

        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 = Identity.instance().getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

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

            if not logged_in:
                return False

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

            try:
                mobile_number = foundUser.getAttribute("phoneNumberVerified")
            except:
                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
            context.set("code", code)

            client = TwilioRestClient(self.ACCOUNT_SID, self.AUTH_TOKEN)
            bodyParam = BasicNameValuePair("Body", str(code))
            toParam = BasicNameValuePair("To", mobile_number)
            fromParam = BasicNameValuePair("From", self.FROM_NUMBER)

            params = ArrayList()
            params.add(bodyParam)
            params.add(toParam)
            params.add(fromParam)

            try:
                messageFactory = client.getAccount().getMessageFactory()
                message = messageFactory.create(params)

                print 'TwilioSMs, Message Sid: %s' % (message.getSid())
                return True
            except:
                print "TwilioSMS. Error sending message to Twilio"

            return False
        elif step == 2:
            # Retrieve the session attribute
            print "TwilioSMS. Step 2 SMS/OTP Authentication"
            code = session_attributes.get("code")
            print "TwilioSMS. Code: %s" % str(code)

            if code is None:
                print "TwilioSMS. Failed to find previously sent code"
                return False

            if form_passcode is None:
                print "TwilioSMS. Passcode is empty"
                return False

            if len(form_passcode) != 6:
                print "TwilioSMS. Passcode from response is not 6 digits: %s" % form_passcode
                return False

            if form_passcode == code:
                print "TiwlioSMS, SUCCESS! User entered the same code!"
                return True

            print "TwilioSMS. FAIL! User entered the wrong code! %s != %s" % (
                form_passcode, code)

            return False

        print "TwilioSMS. ERROR: step param not found or != (1|2)"

        return False
Beispiel #37
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        context = Contexts.getEventContext()
        session_attributes = context.get("sessionAttributes")

        self.setEventContextParameters(context)

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

            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

            context.set("uaf_auth_method", uaf_auth_method)

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

            session_state = SessionStateService.instance(
            ).getSessionStateFromCookie()
            if StringHelper.isEmpty(session_state):
                print "UAF. Prepare for step 2. Failed to determine session_state"
                return False

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

            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 = UserService.instance()

                # 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
Beispiel #38
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        session_attributes = identity.getSessionState().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"
            identity = CdiUtil.bean(Identity)
            credentials = 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 = userService.getUserByAttribute("uid", user_name)
            except:
                print 'TwilioSMS, Error retrieving user %s from LDAP' % (
                    user_name)
                return False

            try:
                mobile_number = foundUser.getAttribute("mobile")
                if isinstance(mobile_number, JSONArray):
                    mobile_number = mobile_number.get(0)
                print "TwilioSMS, Message will be sent to number ", mobile_number
            except:
                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
            identity.setWorkingParameter("code", code)

            try:
                Twilio.init(self.ACCOUNT_SID, self.AUTH_TOKEN)
                message = Message.creator(PhoneNumber(mobile_number),
                                          PhoneNumber(self.FROM_NUMBER),
                                          str(code)).create()

                print 'TwilioSMs, Message Sid: %s' % (message.getSid())
                return True
            except Exception, ex:
                print "TwilioSMS. Error sending message to Twilio"
                print "TwilioSMS. Unexpected error:", ex

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

        identity = CdiUtil.bean(Identity)
        session_attributes = 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"
            identity = CdiUtil.bean(Identity)
            credentials = 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 = userService.getUserByAttribute("uid", user_name)
            except:
                print 'TwilioSMS, Error retrieving user %s from LDAP' % (
                    user_name)
                return False

            try:
                mobile_number = foundUser.getAttribute("phoneNumberVerified")
            except:
                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
            identity.setWorkingParameter("code", code)

            # Store user phone number in authentication session
            identity.setWorkingParameter("mobile_number", mobile_number)

            client = TwilioRestClient(self.ACCOUNT_SID, self.AUTH_TOKEN)
            bodyParam = BasicNameValuePair("Body", str(code))
            toParam = BasicNameValuePair("To", mobile_number)
            fromParam = BasicNameValuePair("From", self.FROM_NUMBER)

            params = ArrayList()
            params.add(bodyParam)
            params.add(toParam)
            params.add(fromParam)

            try:
                messageFactory = client.getAccount().getMessageFactory()
                message = messageFactory.create(params)

                print 'TwilioSMs, Message Sid: %s' % (message.getSid())
                return True
            except Exception, ex:
                print "TwilioSMS. Error sending message to Twilio"
                print "TwilioSMS. Unexpected error:", ex

            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        context = Contexts.getEventContext()

        userService = UserService.instance()
        deviceRegistrationService = DeviceRegistrationService.instance()
        if (step == 1):
            print "oxPush2. Authenticate for step 1"

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

            if (not logged_in):
                return False

            auth_method = 'authenticate'
            enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
            if StringHelper.isNotEmpty(enrollment_mode):
                auth_method = 'enroll'
            
            if (auth_method == 'authenticate'):
                find_user_by_uid = userService.getUser(user_name)
                if (find_user_by_uid == None):
                    print "oxPush. Authenticate for step 1. Failed to find user"
                    return False

                user_inum = userService.getUserInum(find_user_by_uid)
                u2f_devices_list = deviceRegistrationService.findUserDeviceRegistrations(user_inum, self.u2f_application_id, "oxId")
                if (u2f_devices_list.size() == 0):
                    auth_method = 'enroll'
                    print "oxPush2. There is no U2F '%s' user devices associated with application '%s'. Changing auth_method to '%s'" % (user_name, self.u2f_application_id, auth_method)

            print "oxPush2. Authenticate for step 1. auth_method: '%s'" % auth_method
            
            context.set("oxpush2_auth_method", auth_method)

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

            credentials = Identity.instance().getCredentials()
            user = credentials.getUser()
            if (user == None):
                print "oxPush2. Authenticate for step 2. Failed to determine user name"
                return False

            # Find user by uid
            userService = UserService.instance()
            find_user_by_uid = userService.getUser(user_name)
            if (find_user_by_uid == None):
                print "oxPush. Authenticate for step 2. Failed to find user"
                return False

            session_attributes = context.get("sessionAttributes")
            if (not session_attributes.containsKey("oxpush2_request")):
                print "oxPush2. Authenticate for step 2. There is no oxPush2 request in session attributes"
                return False
            
            oxpush2_request_json = session_attributes.get("oxpush2_request")
            oxpush2_request = json.loads(oxpush2_request_json)

            auth_method = oxpush2_request['method']
            if (auth_method in ['enroll', 'authenticate']):
                print "oxPush2. Authenticate for step 2. Validation U2F user device. auth_method: '%s'" % auth_method

                # Check session state extended
                if (not session_attributes.containsKey("session_custom_state")):
                    print "oxPush2. Authenticate for step 2. There is no session_custom_state in session attributes"
                    return False

                session_custom_state = session_attributes.get("session_custom_state")
                if(not StringHelper.equalsIgnoreCase("approved", session_custom_state)):
                    print "oxPush2. Authenticate for step 2. User '%s' not approve or pass U2F authentication. session_custom_state: '%s'" % (user_name, session_custom_state)
                    return False

                # Try to find device_id in session attribute
                if (not session_attributes.containsKey("oxpush2_u2f_device_id")):
                    print "oxPush2. Authenticate for step 2. There is no u2f_device associated with this request"
                    return False
                
                u2f_device_id = session_attributes.get("oxpush2_u2f_device_id")

                # Validate if user has specified device_id enrollment
                user_inum = userService.getUserInum(find_user_by_uid)

                u2f_device = deviceRegistrationService.findUserDeviceRegistration(user_inum, u2f_device_id)
                if (u2f_device == None):
                    print "oxPush2. Authenticate for step 2. There is no u2f_device '%s' associated with user '%s'" % (u2f_device_id, user_inum)
                    return False

                if (not StringHelper.equalsIgnoreCase(self.u2f_application_id, u2f_device.application)):
                    print "oxPush2. Authenticate for step 2. U2F user's '%s' device associated with other application '%s'" % (user_name, u2f_device.application)
                    return False

                print "oxPush2. Authenticate for step 2. U2F user's '%s' device authenticated successfully with U2F device '%s'" % (user_name, u2f_device_id)

                return True
            else:
                print "oxPush2. Authenticate for step 2. U2F auth_method is invalid"

            return False
        else:
            return False