def init(self, configurationAttributes): print "oxPush2. Initialization" if not (configurationAttributes.containsKey("application_id") and configurationAttributes.containsKey("authentication_mode")): print "oxPush2. Initialization. Properties application_id and authentication_mode are mandatory" return False self.application_id = configurationAttributes.get("application_id").getValue2() if StringHelper.isEmpty(self.application_id): print "oxPush2. Initialization. Failed to determine application_id. application_id configuration parameter is empty" return False authentication_mode = configurationAttributes.get("authentication_mode").getValue2() if StringHelper.isEmpty(authentication_mode): print "oxPush2. Initialization. Failed to determine authentication_mode. authentication_mode configuration parameter is empty" return False self.oneStep = StringHelper.equalsIgnoreCase(authentication_mode, "one_step") self.twoStep = StringHelper.equalsIgnoreCase(authentication_mode, "two_step") if not (self.oneStep or self.twoStep): print "oxPush2. Initialization. Valid authentication_mode values are one_step and two_step" return False self.enabledPushNotifications = self.initPushNotificationService(configurationAttributes) print "oxPush2. Initialized successfully. oneStep: '%s', twoStep: '%s', pushNotifications: '%s'" % (self.oneStep, self.twoStep, self.enabledPushNotifications) return True
def init(self, configurationAttributes): print "Passport: Basic. Initialization init method call" self.extensionModule = None self.attributesMapping = None if (configurationAttributes.containsKey("generic_remote_attributes_list") and configurationAttributes.containsKey("generic_local_attributes_list")): remoteAttributesList = configurationAttributes.get("generic_remote_attributes_list").getValue2() if (StringHelper.isEmpty(remoteAttributesList)): print "Passport: Initialization. The property generic_remote_attributes_list is empty" return False localAttributesList = configurationAttributes.get("generic_local_attributes_list").getValue2() if (StringHelper.isEmpty(localAttributesList)): print "Passport: Initialization. The property generic_local_attributes_list is empty" return False self.attributesMapping = self.prepareAttributesMapping(remoteAttributesList, localAttributesList) if (self.attributesMapping == None): print "Passport: Initialization. The attributes mapping isn't valid" return False if (configurationAttributes.containsKey("extension_module")): extensionModuleName = configurationAttributes.get("extension_module").getValue2() try: self.extensionModule = __import__(extensionModuleName) extensionModuleInitResult = self.extensionModule.init(configurationAttributes) if (not extensionModuleInitResult): return False except ImportError, ex: print "Passport: Initialization. Failed to load generic_extension_module:", extensionModuleName print "Passport: Initialization. Unexpected error:", ex return False
def init(self, configurationAttributes): print "Basic (multi login) initialization" login_attributes_list_object = configurationAttributes.get("login_attributes_list") if (login_attributes_list_object == None): print "Basic (multi login) initialization. There is no property login_attributes_list" return False login_attributes_list = login_attributes_list_object.getValue2() if (StringHelper.isEmpty(login_attributes_list)): print "Basic (multi login) initialization. There is no attributes specified in login_attributes property" return False login_attributes_list_array = StringHelper.split(login_attributes_list, ",") if (ArrayHelper.isEmpty(login_attributes_list_array)): print "Basic (multi login) initialization. There is no attributes specified in login_attributes property" return False if (configurationAttributes.containsKey("local_login_attributes_list")): local_login_attributes_list = configurationAttributes.get("local_login_attributes_list").getValue2() local_login_attributes_list_array = StringHelper.split(local_login_attributes_list, ",") else: print "Basic (multi login) initialization. There is no property local_login_attributes_list. Assuming that login attributes are equal to local login attributes." local_login_attributes_list_array = login_attributes_list_array if (len(login_attributes_list_array) != len(local_login_attributes_list_array)): print "Basic (multi login) initialization. The number of attributes in login_attributes_list and local_login_attributes_list isn't equal" return False self.login_attributes_list_array = login_attributes_list_array self.local_login_attributes_list_array = local_login_attributes_list_array print "Basic (multi login) initialized successfully" return True
def validateInweboToken(self, iw_api_uri, iw_service_id, user_name, iw_token): httpService = HttpService.instance() xmlService = XmlService.instance(); if StringHelper.isEmpty(iw_token): print "InWebo. Token verification. iw_token is empty" return False request_uri = iw_api_uri + "?action=authenticate" + "&serviceId=" + httpService.encodeUrl(iw_service_id) + "&userId=" + httpService.encodeUrl(user_name) + "&token=" + httpService.encodeUrl(iw_token) print "InWebo. Token verification. Attempting to send authentication request:", request_uri # Execute request http_response = httpService.executeGet(self.client, request_uri) # Validate response code response_validation = httpService.isResponseStastusCodeOk(http_response) if response_validation == False: print "InWebo. Token verification. Get unsuccessful response code" return False authentication_response_bytes = httpService.getResponseContent(http_response) print "InWebo. Token verification. Get response:", httpService.convertEntityToString(authentication_response_bytes) # Validate authentication response response_validation = httpService.isContentTypeXml(http_response) if response_validation == False: print "InWebo. Token verification. Get invalid response" return False # Parse XML response try: xmlDocument = xmlService.getXmlDocument(authentication_response_bytes) except Exception, err: print "InWebo. Token verification. Failed to parse XML response:", err return False
def getCurrentSamlConfiguration(self, currentSamlConfiguration, configurationAttributes, requestParameters): saml_client_configuration = self.getClientConfiguration(configurationAttributes, requestParameters) if (saml_client_configuration == None): return currentSamlConfiguration saml_client_configuration_value = json.loads(saml_client_configuration.getValue()) client_saml_certificate = None client_saml_certificate_file = saml_client_configuration_value["saml_certificate_file"] if (StringHelper.isNotEmpty(client_saml_certificate_file)): client_saml_certificate = self.loadCeritificate(client_saml_certificate_file) if (StringHelper.isEmpty(client_saml_certificate)): print "Saml. BuildClientSamlConfiguration. File with x509 certificate should be not empty. Using default configuration" return currentSamlConfiguration clientSamlConfiguration = currentSamlConfiguration.clone() if (client_saml_certificate != None): clientSamlConfiguration.loadCertificateFromString(client_saml_certificate) client_saml_issuer = saml_client_configuration_value["saml_issuer"] clientSamlConfiguration.setIssuer(client_saml_issuer) saml_use_authn_context = saml_client_configuration_value["saml_use_authn_context"] client_use_saml_use_authn_context = StringHelper.toBoolean(saml_use_authn_context, True) clientSamlConfiguration.setUseRequestedAuthnContext(client_use_saml_use_authn_context) return clientSamlConfiguration
def prepareForStep(self, configurationAttributes, requestParameters, step): context = Contexts.getEventContext() if (step == 1): context.set("display_register_action", True) return True elif (step == 2): print "oxPush2. Prepare for step 2" credentials = Identity.instance().getCredentials() user = credentials.getUser() if (user == None): print "oxPush2. Prepare for step 2. Failed to determine user name" return False session_attributes = context.get("sessionAttributes") if session_attributes.containsKey("oxpush2_request"): print "oxPush2. Prepare for step 2. Request was generated already" return True session_state = SessionStateService.instance().getSessionStateFromCookie() if StringHelper.isEmpty(session_state): print "oxPush2. Prepare for step 2. Failed to determine session_state" return False auth_method = session_attributes.get("oxpush2_auth_method") if StringHelper.isEmpty(auth_method): print "oxPush2. Prepare for step 2. Failed to determine auth_method" return False print "oxPush2. Prepare for step 2. auth_method: '%s'" % auth_method issuer = ConfigurationFactory.instance().getConfiguration().getIssuer() oxpush2_request = json.dumps({'username': user.getUserId(), 'app': self.u2f_application_id, 'issuer': issuer, 'method': auth_method, 'state': session_state}, separators=(',',':')) print "oxPush2. Prepare for step 2. Prepared oxpush2_request:", oxpush2_request context.set("oxpush2_request", oxpush2_request) return True else: return False
def init(self, configurationAttributes): print "Google+ initialization" if (not configurationAttributes.containsKey("gplus_client_secrets_file")): print "Google+ initialization. The property gplus_client_secrets_file is empty" return False clientSecretsFile = configurationAttributes.get("gplus_client_secrets_file").getValue2() self.clientSecrets = self.loadClientSecrets(clientSecretsFile) if (self.clientSecrets == None): print "Google+ initialization. File with Google+ client secrets should be not empty" return False self.attributesMapping = None if (configurationAttributes.containsKey("gplus_remote_attributes_list") and configurationAttributes.containsKey("gplus_local_attributes_list")): remoteAttributesList = configurationAttributes.get("gplus_remote_attributes_list").getValue2() if (StringHelper.isEmpty(remoteAttributesList)): print "Google+ initialization. The property gplus_remote_attributes_list is empty" return False localAttributesList = configurationAttributes.get("gplus_local_attributes_list").getValue2() if (StringHelper.isEmpty(localAttributesList)): print "Google+ initialization. The property gplus_local_attributes_list is empty" return False self.attributesMapping = self.prepareAttributesMapping(remoteAttributesList, localAttributesList) if (self.attributesMapping == None): print "Google+ initialization. The attributes mapping isn't valid" return False self.extensionModule = None if (configurationAttributes.containsKey("extension_module")): extensionModuleName = configurationAttributes.get("extension_module").getValue2() try: self.extensionModule = __import__(extensionModuleName) extensionModuleInitResult = self.extensionModule.init(configurationAttributes) if (not extensionModuleInitResult): return False except ImportError, ex: print "Failed to load gplus_extension_module:", extensionModuleName print "Unexpected error:", ex return False
def getSamlNameId(self, samlResponse): saml_response_name_id = samlResponse.getNameId() if (StringHelper.isEmpty(saml_response_name_id)): print "Saml. Get Saml response. saml_response_name_id is invalid" return None print "Saml. Get Saml response. saml_response_name_id: '%s'" % saml_response_name_id # Use persistent Id as saml_user_uid return saml_response_name_id
def init(self, configurationAttributes): print "oxPush2. Initialization" self.u2f_application_id = configurationAttributes.get("u2f_application_id").getValue2() if StringHelper.isEmpty(self.u2f_application_id): print "oxPush2. Initialization. Failed to determine application_id. u2f_application_id configuration parameter is empty" return False print "oxPush2. Initialized successfully" return True
def validateSessionState(self, session_attributes): session_state = SessionStateService.instance().getSessionStateFromCookie() if StringHelper.isEmpty(session_state): print "OTP. Validate session state. Failed to determine session_state" return False otp_auth_method = session_attributes.get("otp_auth_method") if not otp_auth_method in ['enroll', 'authenticate']: print "OTP. Validate session state. Failed to authenticate user. otp_auth_method: '%s'" % otp_auth_method return False 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
def authenticate(self, configurationAttributes, requestParameters, step): credentials = Identity.instance().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)): userService = UserService.instance() logged_in = userService.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" userService = UserService.instance() update_button = requestParameters.get("loginForm:updateButton") if ArrayHelper.isEmpty(update_button): return True new_password_array = requestParameters.get("new_password") if ArrayHelper.isEmpty(new_password_array) or StringHelper.isEmpty(new_password_array[0]): print "Basic (with password update). Authenticate for step 2. New password is empty" return False new_password = new_password_array[0] print "Basic (with password update). Authenticate for step 2. Attemprin 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 setUserAttributeValue(self, user_name, attribute_name, attribute_value): if StringHelper.isEmpty(user_name): return None userService = UserService.instance() find_user_by_uid = userService.getUser(user_name) if find_user_by_uid == None: return None userService.setCustomAttribute(find_user_by_uid, attribute_name, attribute_value) updated_user = userService.updateUser(find_user_by_uid) print "Basic (lock account). Set user attribute. User's '%s' attribute '%s' value is '%s'" % (user_name, attribute_name, attribute_value) return updated_user
def getUserAttributeValue(self, user_name, attribute_name): if StringHelper.isEmpty(user_name): return None userService = UserService.instance() find_user_by_uid = userService.getUser(user_name, attribute_name) if find_user_by_uid == None: return None custom_attribute_value = userService.getCustomAttribute(find_user_by_uid, attribute_name) if custom_attribute_value == None: return None attribute_value = custom_attribute_value.getValue() print "Basic (lock account). Get user attribute. User's '%s' attribute '%s' value is '%s'" % (user_name, attribute_name, attribute_value) return attribute_value
def lockUser(self, user_name): if StringHelper.isEmpty(user_name): return None userService = UserService.instance() find_user_by_uid = userService.getUser(user_name) if (find_user_by_uid == None): return None status_attribute_value = userService.getCustomAttribute(find_user_by_uid, "gluuStatus") if status_attribute_value != None: user_status = status_attribute_value.getValue() if StringHelper.equals(user_status, "inactive"): print "Basic (lock account). Lock user. User '%s' locked already" % user_name return userService.setCustomAttribute(find_user_by_uid, "gluuStatus", "inactive") updated_user = userService.updateUser(find_user_by_uid) print "Basic (lock account). Lock user. User '%s' locked" % user_name
def getClientConfiguration(self, configurationAttributes, requestParameters): # Get client configuration if (configurationAttributes.containsKey("gplus_client_configuration_attribute")): clientConfigurationAttribute = configurationAttributes.get("gplus_client_configuration_attribute").getValue2() print "Google+ GetClientConfiguration. Using client attribute:", clientConfigurationAttribute if (requestParameters == None): return None clientId = None # Attempt to determine client_id from request clientIdArray = requestParameters.get("client_id") if (ArrayHelper.isNotEmpty(clientIdArray) and StringHelper.isNotEmptyString(clientIdArray[0])): clientId = clientIdArray[0] # Attempt to determine client_id from event context if (clientId == None): eventContext = Contexts.getEventContext() if (eventContext.isSet("stored_request_parameters")): clientId = eventContext.get("stored_request_parameters").get("client_id") if (clientId == None): print "Google+ GetClientConfiguration. client_id is empty" return None clientService = ClientService.instance() client = clientService.getClient(clientId) if (client == None): print "Google+ GetClientConfiguration. Failed to find client", clientId, " in local LDAP" return None clientConfiguration = clientService.getCustomAttribute(client, clientConfigurationAttribute) if ((clientConfiguration == None) or StringHelper.isEmpty(clientConfiguration.getValue())): print "Google+ GetClientConfiguration. Client", clientId, " attribute", clientConfigurationAttribute, " is empty" else: print "Google+ GetClientConfiguration. Client", clientId, " attribute", clientConfigurationAttribute, " is", clientConfiguration return clientConfiguration return None
def getClientConfiguration(self, configurationAttributes, requestParameters): # Get client configuration if (configurationAttributes.containsKey("saml_client_configuration_attribute")): saml_client_configuration_attribute = configurationAttributes.get("saml_client_configuration_attribute").getValue2() print "Saml. GetClientConfiguration. Using client attribute:", saml_client_configuration_attribute if (requestParameters == None): return None client_id = None client_id_array = requestParameters.get("client_id") if (ArrayHelper.isNotEmpty(client_id_array) and StringHelper.isNotEmptyString(client_id_array[0])): client_id = client_id_array[0] if (client_id == None): eventContext = Contexts.getEventContext() if (eventContext.isSet("sessionAttributes")): client_id = eventContext.get("sessionAttributes").get("client_id") if (client_id == None): print "Saml. GetClientConfiguration. client_id is empty" return None clientService = ClientService.instance() client = clientService.getClient(client_id) if (client == None): print "Saml. GetClientConfiguration. Failed to find client", client_id, " in local LDAP" return None saml_client_configuration = clientService.getCustomAttribute(client, saml_client_configuration_attribute) if ((saml_client_configuration == None) or StringHelper.isEmpty(saml_client_configuration.getValue())): print "Saml. GetClientConfiguration. Client", client_id, " attribute", saml_client_configuration_attribute, " is empty" else: print "Saml. GetClientConfiguration. Client", client_id, " attribute", saml_client_configuration_attribute, " is", saml_client_configuration return saml_client_configuration return None
def prepareClientRedirectUris(self, configurationAttributes): clientRedirectUrisSet = HashSet() if not configurationAttributes.containsKey("client_redirect_uris"): return clientRedirectUrisSet clientRedirectUrisList = configurationAttributes.get("client_redirect_uris").getValue2() if StringHelper.isEmpty(clientRedirectUrisList): print "Casa client registration. The property client_redirect_uris is empty" return clientRedirectUrisSet clientRedirectUrisArray = StringHelper.split(clientRedirectUrisList, ",") if ArrayHelper.isEmpty(clientRedirectUrisArray): print "Casa client registration. No clients specified in client_redirect_uris property" return clientRedirectUrisSet # Convert to HashSet to quick search i = 0 count = len(clientRedirectUrisArray) while i < count: uris = clientRedirectUrisArray[i] clientRedirectUrisSet.add(uris) i = i + 1 return clientRedirectUrisSet
def init(self, configurationAttributes): print "Super-Gluu. Initialization" if not configurationAttributes.containsKey("authentication_mode"): print "Super-Gluu. Initialization. Property authentication_mode is mandatory" return False self.registrationUri = None if configurationAttributes.containsKey("registration_uri"): self.registrationUri = configurationAttributes.get("registration_uri").getValue2() authentication_mode = configurationAttributes.get("authentication_mode").getValue2() if StringHelper.isEmpty(authentication_mode): print "Super-Gluu. Initialization. Failed to determine authentication_mode. authentication_mode configuration parameter is empty" return False self.oneStep = StringHelper.equalsIgnoreCase(authentication_mode, "one_step") self.twoStep = StringHelper.equalsIgnoreCase(authentication_mode, "two_step") if not (self.oneStep or self.twoStep): print "Super-Gluu. Initialization. Valid authentication_mode values are one_step and two_step" return False self.enabledPushNotifications = self.initPushNotificationService(configurationAttributes) self.customLabel = None if configurationAttributes.containsKey("label"): self.customLabel = configurationAttributes.get("label").getValue2() self.customQrOptions = {} if configurationAttributes.containsKey("qr_options"): self.customQrOptions = configurationAttributes.get("qr_options").getValue2() print "Super-Gluu. Initialized successfully. oneStep: '%s', twoStep: '%s', pushNotifications: '%s', customLabel: '%s'" % (self.oneStep, self.twoStep, self.enabledPushNotifications, self.customLabel) return True
def init(self, configuration_attributes): print "ThumbSignIn. Initialization" global ts_host ts_host = configuration_attributes.get("ts_host").getValue2() print "ThumbSignIn. Initialization. Value of ts_host is %s" % ts_host global ts_api_key ts_api_key = configuration_attributes.get("ts_apiKey").getValue2() print "ThumbSignIn. Initialization. Value of ts_api_key is %s" % ts_api_key global ts_api_secret ts_api_secret = configuration_attributes.get("ts_apiSecret").getValue2() global ts_statusPath ts_statusPath = "/ts/secure/txn-status/" global AUTHENTICATE AUTHENTICATE = "authenticate" global REGISTER REGISTER = "register" global TRANSACTION_ID TRANSACTION_ID = "transactionId" global USER_ID USER_ID = "userId" global USER_LOGIN_FLOW USER_LOGIN_FLOW = "userLoginFlow" global THUMBSIGNIN_AUTHENTICATION THUMBSIGNIN_AUTHENTICATION = "ThumbSignIn_Authentication" global THUMBSIGNIN_REGISTRATION THUMBSIGNIN_REGISTRATION = "ThumbSignIn_Registration" global THUMBSIGNIN_LOGIN_POST_REGISTRATION THUMBSIGNIN_LOGIN_POST_REGISTRATION = "ThumbSignIn_RegistrationSucess" global RELYING_PARTY_ID RELYING_PARTY_ID = "relyingPartyId" global RELYING_PARTY_LOGIN_URL RELYING_PARTY_LOGIN_URL = "relyingPartyLoginUrl" global TSI_LOGIN_PAGE TSI_LOGIN_PAGE = "/auth/thumbsignin/tsLogin.xhtml" global TSI_REGISTER_PAGE TSI_REGISTER_PAGE = "/auth/thumbsignin/tsRegister.xhtml" global TSI_LOGIN_POST_REGISTRATION_PAGE TSI_LOGIN_POST_REGISTRATION_PAGE = "/auth/thumbsignin/tsRegistrationSuccess.xhtml" global azure_tenant_id azure_tenant_id = configuration_attributes.get("azure_tenant_id").getValue2() print "ThumbSignIn. Initialization. Value of azure_tenant_id is %s" % azure_tenant_id global azure_client_id azure_client_id = configuration_attributes.get("azure_client_id").getValue2() print "ThumbSignIn. Initialization. Value of azure_client_id is %s" % azure_client_id global azure_client_secret azure_client_secret = configuration_attributes.get("azure_client_secret").getValue2() global ADMIN ADMIN = 'admin' global azure_user_uuid azure_user_uuid = "oid" global gluu_ldap_uuid gluu_ldap_uuid = "uid" global attributes_mapping if (configuration_attributes.containsKey("azure_ad_attributes_list") and configuration_attributes.containsKey("gluu_ldap_attributes_list")): azure_ad_attributes_list = configuration_attributes.get("azure_ad_attributes_list").getValue2() if StringHelper.isEmpty(azure_ad_attributes_list): print "ThumbSignIn: Initialization. The property azure_ad_attributes_list is empty" return False gluu_ldap_attributes_list = configuration_attributes.get("gluu_ldap_attributes_list").getValue2() if StringHelper.isEmpty(gluu_ldap_attributes_list): print "ThumbSignIn: Initialization. The property gluu_ldap_attributes_list is empty" return False attributes_mapping = self.attribute_mapping_function(azure_ad_attributes_list, gluu_ldap_attributes_list) if attributes_mapping is None: print "ThumbSignIn: Initialization. The attributes mapping isn't valid" return False print "ThumbSignIn. Initialized successfully" 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 authenticate(self, configurationAttributes, requestParameters, step): context = Contexts.getEventContext() authenticationService = AuthenticationService.instance() userService = UserService.instance() saml_map_user = False saml_enroll_user = False saml_enroll_all_user_attr = False # Use saml_deployment_type only if there is no attributes mapping if (configurationAttributes.containsKey("saml_deployment_type")): saml_deployment_type = StringHelper.toLowerCase( configurationAttributes.get( "saml_deployment_type").getValue2()) if (StringHelper.equalsIgnoreCase(saml_deployment_type, "map")): saml_map_user = True if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll")): saml_enroll_user = True if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll_all_attr")): saml_enroll_all_user_attr = True saml_allow_basic_login = False if (configurationAttributes.containsKey("saml_allow_basic_login")): saml_allow_basic_login = StringHelper.toBoolean( configurationAttributes.get( "saml_allow_basic_login").getValue2(), False) use_basic_auth = False if (saml_allow_basic_login): # Detect if user used basic authnetication method credentials = Identity.instance().getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() if (StringHelper.isNotEmpty(user_name) and StringHelper.isNotEmpty(user_password)): use_basic_auth = True if ((step == 1) and saml_allow_basic_login and use_basic_auth): print "Saml. Authenticate for step 1. Basic authentication" context.set("saml_count_login_steps", 1) 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)): userService = UserService.instance() logged_in = userService.authenticate(user_name, user_password) if (not logged_in): return False return True if (step == 1): print "Saml. Authenticate for step 1" currentSamlConfiguration = self.getCurrentSamlConfiguration( self.samlConfiguration, configurationAttributes, requestParameters) if (currentSamlConfiguration == None): print "Saml. Prepare for step 1. Client saml configuration is invalid" return False saml_response_array = requestParameters.get("SAMLResponse") if ArrayHelper.isEmpty(saml_response_array): print "Saml. Authenticate for step 1. saml_response is empty" return False saml_response = saml_response_array[0] print "Saml. Authenticate for step 1. saml_response: '%s'" % saml_response samlResponse = Response(currentSamlConfiguration) samlResponse.loadXmlFromBase64(saml_response) saml_validate_response = True if (configurationAttributes.containsKey("saml_validate_response")): saml_validate_response = StringHelper.toBoolean( configurationAttributes.get( "saml_validate_response").getValue2(), False) if (saml_validate_response): if (not samlResponse.isValid()): print "Saml. Authenticate for step 1. saml_response isn't valid" saml_response_name_id = samlResponse.getNameId() if (StringHelper.isEmpty(saml_response_name_id)): print "Saml. Authenticate for step 1. saml_response_name_id is invalid" return False print "Saml. Authenticate for step 1. saml_response_name_id: '%s'" % saml_response_name_id saml_response_attributes = samlResponse.getAttributes() print "Saml. Authenticate for step 1. attributes: '%s'" % saml_response_attributes # Use persistent Id as saml_user_uid saml_user_uid = saml_response_name_id if (saml_map_user): # Use mapping to local IDP user print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml: '%s'" % saml_user_uid # Check if the is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" print "Saml. Authenticate for step 1. Setting count steps to 2" context.set("saml_count_login_steps", 2) context.set("saml_user_uid", saml_user_uid) return True found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (saml_enroll_user): # Use auto enrollment to local IDP print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml: '%s'" % saml_user_uid # Check if the is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): # Auto user enrollemnt print "Saml. Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP" # Convert saml result attributes keys to lover case saml_response_normalized_attributes = HashMap() for saml_response_attribute_entry in saml_response_attributes.entrySet( ): saml_response_normalized_attributes.put( StringHelper.toLowerCase( saml_response_attribute_entry.getKey()), saml_response_attribute_entry.getValue()) currentAttributesMapping = self.prepareCurrentAttributesMapping( self.attributesMapping, configurationAttributes, requestParameters) print "Saml. Authenticate for step 1. Using next attributes mapping '%s'" % currentAttributesMapping newUser = User() # Set custom object classes if self.userObjectClasses != None: print "Saml. Authenticate for step 1. User custom objectClasses to add persons: '%s'" % Util.array2ArrayList( self.userObjectClasses) newUser.setCustomObjectClasses(self.userObjectClasses) for attributesMappingEntry in currentAttributesMapping.entrySet( ): idpAttribute = attributesMappingEntry.getKey() localAttribute = attributesMappingEntry.getValue() if self.debugEnrollment: print "Saml. Authenticate for step 1. Trying to map '%s' into '%s'" % ( idpAttribute, localAttribute) localAttributeValue = saml_response_normalized_attributes.get( idpAttribute) if (localAttributeValue != None): if self.debugEnrollment: print "Saml. Authenticate for step 1. Setting attribute '%s' value '%s'" % ( localAttribute, localAttributeValue) newUser.setAttribute(localAttribute, localAttributeValue) newUser.setAttribute("oxExternalUid", "saml:" + saml_user_uid) print "Saml. Authenticate for step 1. Attempting to add user '%s' with next attributes: '%s'" % ( saml_user_uid, newUser.getCustomAttributes()) user_unique = self.checkUserUniqueness(newUser) if not user_unique: print "Saml. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getAttribute( "uid") facesMessages = FacesMessages.instance() facesMessages.add( StatusMessage.Severity.ERROR, "Failed to enroll. User with same key attributes exist already" ) FacesContext.getCurrentInstance().getExternalContext( ).getFlash().setKeepMessages(True) return False find_user_by_uid = userService.addUser(newUser, True) print "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId( ) found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user: '******'" % found_user_name return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (saml_enroll_all_user_attr): print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml:" + saml_user_uid # Check if the is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" user = User() # Set custom object classes if self.userObjectClasses != None: print "Saml. Authenticate for step 1. User custom objectClasses to add persons: '%s'" % Util.array2ArrayList( self.userObjectClasses) user.setCustomObjectClasses(self.userObjectClasses) customAttributes = ArrayList() for key in saml_response_attributes.keySet(): ldapAttributes = attributeService.getAllAttributes() for ldapAttribute in ldapAttributes: saml2Uri = ldapAttribute.getSaml2Uri() if (saml2Uri == None): saml2Uri = attributeService.getDefaultSaml2Uri( ldapAttribute.getName()) if (saml2Uri == key): attribute = CustomAttribute( ldapAttribute.getName()) attribute.setValues(attributes.get(key)) customAttributes.add(attribute) attribute = CustomAttribute("oxExternalUid") attribute.setValue("saml:" + saml_user_uid) customAttributes.add(attribute) user.setCustomAttributes(customAttributes) if (user.getAttribute("sn") == None): attribute = CustomAttribute("sn") attribute.setValue(saml_user_uid) customAttributes.add(attribute) if (user.getAttribute("cn") == None): attribute = CustomAttribute("cn") attribute.setValue(saml_user_uid) customAttributes.add(attribute) user_unique = self.checkUserUniqueness(user) if not user_unique: print "Saml. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getAttribute( "uid") facesMessages = FacesMessages.instance() facesMessages.add( StatusMessage.Severity.ERROR, "Failed to enroll. User with same key attributes exist already" ) FacesContext.getCurrentInstance().getExternalContext( ).getFlash().setKeepMessages(True) return False find_user_by_uid = userService.addUser(user, True) print "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId( ) found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result else: # Check if the is user with specified saml_user_uid print "Saml. Authenticate for step 1. Attempting to find user by uid: '%s'" % saml_user_uid find_user_by_uid = userService.getUser(saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" return False found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (step == 2): print "Saml. Authenticate for step 2" sessionAttributes = context.get("sessionAttributes") if (sessionAttributes == None ) or not sessionAttributes.containsKey("saml_user_uid"): print "Saml. Authenticate for step 2. saml_user_uid is empty" return False saml_user_uid = sessionAttributes.get("saml_user_uid") passed_step1 = StringHelper.isNotEmptyString(saml_user_uid) if (not passed_step1): 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 # Check if there is user which has saml_user_uid # Avoid mapping Saml account to more than one IDP account find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): # Add saml_user_uid to user one id UIDs find_user_by_uid = userService.addUserAttribute( user_name, "oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 2. Failed to update current user" return False post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 2. post_login_result: '%s'" % post_login_result return post_login_result else: found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 2. found_user_name: '%s'" % found_user_name if StringHelper.equals(user_name, found_user_name): post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 2. post_login_result: '%s'" % post_login_result return post_login_result return False else: 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
def prepareForStep(self, configurationAttributes, requestParameters, step): credentials = Identity.instance().getCredentials() context = Contexts.getEventContext() session_attributes = context.get("sessionAttributes") self.setEventContextParameters(context) if (step == 1): return True elif (step == 2): print "UAF. Prepare 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 authenticationService = AuthenticationService.instance() user = authenticationService.getAuthenticatedUser() if (user == None): print "UAF. Prepare for step 2. Failed to determine user name" return False uaf_auth_method = session_attributes.get("uaf_auth_method") if StringHelper.isEmpty(uaf_auth_method): print "UAF. Prepare for step 2. Failed to determine auth_method" return False print "UAF. Prepare for step 2. uaf_auth_method: '%s'" % uaf_auth_method uaf_obb_auth_method = "OOB_REG" uaf_obb_server_uri = self.uaf_server_uri + "/nnl/v2/reg" if StringHelper.equalsIgnoreCase(uaf_auth_method, "authenticate"): uaf_obb_auth_method = "OOB_AUTH" uaf_obb_server_uri = self.uaf_server_uri + "/nnl/v2/auth" # Prepare START_OBB uaf_obb_start_request_dictionary = { "operation": "START_%s" % uaf_obb_auth_method, "userName": user.getUserId(), "policyName": "default", "oobMode": { "qr": "true", "rawData": "false", "push": "false" } } uaf_obb_start_request = json.dumps(uaf_obb_start_request_dictionary, separators=(',',':')) print "UAF. Prepare for step 2. Prepared START request: '%s' to send to '%s'" % (uaf_obb_start_request, uaf_obb_server_uri) # Request START_OBB uaf_obb_start_response = self.executePost(uaf_obb_server_uri, uaf_obb_start_request) if uaf_obb_start_response == None: return False print "UAF. Prepare for step 2. Get START response: '%s'" % uaf_obb_start_response uaf_obb_start_response_json = json.loads(uaf_obb_start_response) # Prepare STATUS_OBB #TODO: Remove needDetails parameter uaf_obb_status_request_dictionary = { "operation": "STATUS_%s" % uaf_obb_auth_method, "userName": user.getUserId(), "needDetails": 1, "oobStatusHandle": uaf_obb_start_response_json["oobStatusHandle"], } uaf_obb_status_request = json.dumps(uaf_obb_status_request_dictionary, separators=(',',':')) print "UAF. Prepare for step 2. Prepared STATUS request: '%s' to send to '%s'" % (uaf_obb_status_request, uaf_obb_server_uri) context.set("uaf_obb_auth_method", uaf_obb_auth_method) context.set("uaf_obb_server_uri", uaf_obb_server_uri) context.set("uaf_obb_start_response", uaf_obb_start_response) context.set("qr_image", uaf_obb_start_response_json["modeResult"]["qrCode"]["qrImage"]) context.set("uaf_obb_status_request", uaf_obb_status_request) return True else: return False
def prepareForStep(self, configurationAttributes, requestParameters, step): context = Contexts.getEventContext() session_attributes = context.get("sessionAttributes") client_redirect_uri = self.getClientRedirecUri(session_attributes) if client_redirect_uri == None: print "Super-Gluu. Prepare for step. redirect_uri is not set" return False self.setEventContextParameters(context) if step == 1: print "Super-Gluu. Prepare for step 1" if self.oneStep: session_state = SessionStateService.instance().getSessionStateFromCookie() if StringHelper.isEmpty(session_state): print "Super-Gluu. Prepare for step 2. Failed to determine session_state" return False issuer = ConfigurationFactory.instance().getConfiguration().getIssuer() super_gluu_request_dictionary = {'app': client_redirect_uri, 'issuer': issuer, 'state': session_state, 'created': datetime.datetime.now().isoformat()} self.addGeolocationData(session_attributes, super_gluu_request_dictionary) super_gluu_request = json.dumps(super_gluu_request_dictionary, separators=(',',':')) print "Super-Gluu. Prepare for step 1. Prepared super_gluu_request:", super_gluu_request context.set("super_gluu_request", super_gluu_request) # elif self.twoStep: # context.set("display_register_action", True) return True elif step == 2: print "Super-Gluu. Prepare for step 2" if self.oneStep: return True authenticationService = AuthenticationService.instance() user = authenticationService.getAuthenticatedUser() if user == None: print "Super-Gluu. Prepare for step 2. Failed to determine user name" return False if session_attributes.containsKey("super_gluu_request"): print "Super-Gluu. Prepare for step 2. Request was generated already" return True session_state = SessionStateService.instance().getSessionStateFromCookie() if StringHelper.isEmpty(session_state): print "Super-Gluu. Prepare for step 2. Failed to determine session_state" return False auth_method = session_attributes.get("super_gluu_auth_method") if StringHelper.isEmpty(auth_method): print "Super-Gluu. Prepare for step 2. Failed to determine auth_method" return False print "Super-Gluu. Prepare for step 2. auth_method: '%s'" % auth_method issuer = ConfigurationFactory.instance().getConfiguration().getIssuer() super_gluu_request_dictionary = {'username': user.getUserId(), 'app': client_redirect_uri, 'issuer': issuer, 'method': auth_method, 'state': session_state, 'created': datetime.datetime.now().isoformat()} self.addGeolocationData(session_attributes, super_gluu_request_dictionary) super_gluu_request = json.dumps(super_gluu_request_dictionary, separators=(',',':')) print "Super-Gluu. Prepare for step 2. Prepared super_gluu_request:", super_gluu_request context.set("super_gluu_request", super_gluu_request) if auth_method in ['authenticate']: self.sendPushNotification(client_redirect_uri, user, super_gluu_request) return True else: return False
def authenticate(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() userService = CdiUtil.bean(UserService) requestParameterService = CdiUtil.bean(RequestParameterService) authenticationService = CdiUtil.bean(AuthenticationService) httpService = CdiUtil.bean(HttpService) if step == 1: print "CAS2. Authenticate for step 1" ticket_array = requestParameters.get("ticket") if ArrayHelper.isEmpty(ticket_array): print "CAS2. Authenticate for step 1. ticket is empty" return False ticket = ticket_array[0] print "CAS2. Authenticate for step 1. ticket: " + ticket if StringHelper.isEmptyString(ticket): print "CAS2. Authenticate for step 1. ticket is invalid" return False # Validate ticket facesContext = CdiUtil.bean(FacesContext) request = facesContext.getExternalContext().getRequest() parametersMap = HashMap() parametersMap.put( "service", httpService.constructServerUrl(request) + "/postlogin") if self.cas_renew_opt: parametersMap.put("renew", "true") parametersMap.put("ticket", ticket) cas_service_request_uri = requestParameterService.parametersAsString( parametersMap) cas_service_request_uri = self.cas_host + "/serviceValidate?" + cas_service_request_uri if self.cas_extra_opts != None: cas_service_request_uri = cas_service_request_uri + "&" + self.cas_extra_opts print "CAS2. Authenticate for step 1. cas_service_request_uri: " + cas_service_request_uri http_client = httpService.getHttpsClient() http_service_response = httpService.executeGet( http_client, cas_service_request_uri) try: validation_content = httpService.convertEntityToString( httpService.getResponseContent( http_service_response.getHttpResponse())) finally: http_service_response.closeConnection() print "CAS2. Authenticate for step 1. validation_content: " + validation_content if StringHelper.isEmpty(validation_content): print "CAS2. Authenticate for step 1. Ticket validation response is invalid" return False cas2_auth_failure = self.parse_tag(validation_content, "cas:authenticationFailure") print "CAS2. Authenticate for step 1. cas2_auth_failure: ", cas2_auth_failure cas2_user_uid = self.parse_tag(validation_content, "cas:user") print "CAS2. Authenticate for step 1. cas2_user_uid: ", cas2_user_uid if (cas2_auth_failure != None) or (cas2_user_uid == None): print "CAS2. Authenticate for step 1. Ticket is invalid" return False if self.cas_map_user: print "CAS2. Authenticate for step 1. Attempting to find user by oxExternalUid: cas2:" + cas2_user_uid # Check if the is user with specified cas2_user_uid find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "cas2:" + cas2_user_uid) if find_user_by_uid == None: print "CAS2. Authenticate for step 1. Failed to find user" print "CAS2. Authenticate for step 1. Setting count steps to 2" identity.setWorkingParameter("cas2_count_login_steps", 2) identity.setWorkingParameter("cas2_user_uid", cas2_user_uid) return True found_user_name = find_user_by_uid.getUserId() print "CAS2. Authenticate for step 1. found_user_name: " + found_user_name authenticationService.authenticate(found_user_name) print "CAS2. Authenticate for step 1. Setting count steps to 1" identity.setWorkingParameter("cas2_count_login_steps", 1) return True else: print "CAS2. Authenticate for step 1. Attempting to find user by uid:" + cas2_user_uid # Check if there is user with specified cas2_user_uid find_user_by_uid = userService.getUser(cas2_user_uid) if find_user_by_uid == None: print "CAS2. Authenticate for step 1. Failed to find user" return False found_user_name = find_user_by_uid.getUserId() print "CAS2. Authenticate for step 1. found_user_name: " + found_user_name authenticationService.authenticate(found_user_name) print "CAS2. Authenticate for step 1. Setting count steps to 1" identity.setWorkingParameter("cas2_count_login_steps", 1) return True elif step == 2: print "CAS2. Authenticate for step 2" if identity.isSetWorkingParameter("cas2_user_uid"): print "CAS2. Authenticate for step 2. cas2_user_uid is empty" return False cas2_user_uid = identity.getWorkingParameter("cas2_user_uid") passed_step1 = StringHelper.isNotEmptyString(cas2_user_uid) if not passed_step1: return False 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 # Check if there is user which has cas2_user_uid # Avoid mapping CAS2 account to more than one IDP account find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "cas2:" + cas2_user_uid) if find_user_by_uid == None: # Add cas2_user_uid to user one id UIDs find_user_by_uid = userService.addUserAttribute( user_name, "oxExternalUid", "cas2:" + cas2_user_uid) if find_user_by_uid == None: print "CAS2. Authenticate for step 2. Failed to update current user" return False return True else: found_user_name = find_user_by_uid.getUserId() print "CAS2. Authenticate for step 2. found_user_name: " + found_user_name if StringHelper.equals(user_name, found_user_name): return True return False else: return False
def processOtpAuthentication(self, requestParameters, user_name, identity, otp_auth_method): facesMessages = CdiUtil.bean(FacesMessages) facesMessages.setKeepMessages() userService = CdiUtil.bean(UserService) otpCode = ServerUtil.getFirstValue(requestParameters, "loginForm:otpCode") if StringHelper.isEmpty(otpCode): facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to authenticate. OTP code is empty") print "OTP. Process OTP authentication. otpCode is empty" return False if otp_auth_method == "enroll": # Get key from session otp_secret_key_encoded = identity.getWorkingParameter( "otp_secret_key") if otp_secret_key_encoded == None: print "OTP. Process OTP authentication. OTP secret key is invalid" return False otp_secret_key = self.fromBase64Url(otp_secret_key_encoded) if self.otpType == "hotp": validation_result = self.validateHotpKey( otp_secret_key, 1, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process HOTP authentication during enrollment. otpCode is valid" # Store HOTP Secret Key and moving factor in user entry otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, validation_result["movingFactor"]) # Add otp_user_external_uid to user's external GUID list find_user_by_external_uid = userService.addUserAttribute( user_name, "oxExternalUid", otp_user_external_uid) if find_user_by_external_uid != None: return True print "OTP. Process HOTP authentication during enrollment. Failed to update user entry" elif self.otpType == "totp": validation_result = self.validateTotpKey( otp_secret_key, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process TOTP authentication during enrollment. otpCode is valid" # Store TOTP Secret Key and moving factor in user entry otp_user_external_uid = "totp:%s" % otp_secret_key_encoded # Add otp_user_external_uid to user's external GUID list find_user_by_external_uid = userService.addUserAttribute( user_name, "oxExternalUid", otp_user_external_uid) if find_user_by_external_uid != None: return True print "OTP. Process TOTP authentication during enrollment. Failed to update user entry" elif otp_auth_method == "authenticate": user_enrollments = self.findEnrollments(user_name) if len(user_enrollments) == 0: print "OTP. Process OTP authentication. There is no OTP enrollment for user '%s'" % user_name facesMessages.add(FacesMessage.SEVERITY_ERROR, "There is no valid OTP user enrollments") return False if self.otpType == "hotp": for user_enrollment in user_enrollments: user_enrollment_data = user_enrollment.split(";") otp_secret_key_encoded = user_enrollment_data[0] # Get current moving factor from user entry moving_factor = StringHelper.toInteger( user_enrollment_data[1]) otp_secret_key = self.fromBase64Url(otp_secret_key_encoded) # Validate TOTP validation_result = self.validateHotpKey( otp_secret_key, moving_factor, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process HOTP authentication during authentication. otpCode is valid" otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, moving_factor) new_otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, validation_result["movingFactor"]) # Update moving factor in user entry find_user_by_external_uid = userService.replaceUserAttribute( user_name, "oxExternalUid", otp_user_external_uid, new_otp_user_external_uid) if find_user_by_external_uid != None: return True print "OTP. Process HOTP authentication during authentication. Failed to update user entry" elif self.otpType == "totp": for user_enrollment in user_enrollments: otp_secret_key = self.fromBase64Url(user_enrollment) # Validate TOTP validation_result = self.validateTotpKey( otp_secret_key, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process TOTP authentication during authentication. otpCode is valid" return True facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to authenticate. OTP code is invalid") print "OTP. Process OTP authentication. OTP code is invalid" return False
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 init(self, configurationAttributes): print "Saml. Initialization" saml_certificate_file = configurationAttributes.get("saml_certificate_file").getValue2() saml_idp_sso_target_url = configurationAttributes.get("saml_idp_sso_target_url").getValue2() saml_issuer = configurationAttributes.get("saml_issuer").getValue2() saml_use_authn_context = StringHelper.toBoolean(configurationAttributes.get("saml_use_authn_context").getValue2(), True) if (saml_use_authn_context): saml_name_identifier_format = configurationAttributes.get("saml_name_identifier_format").getValue2() else: saml_name_identifier_format = None saml_certificate = self.loadCeritificate(saml_certificate_file) if (StringHelper.isEmpty(saml_certificate)): print "Saml. Initialization. File with x509 certificate should be not empty" return False samlConfiguration = SamlConfiguration() # Set the issuer of the authentication request. This would usually be the URL of the issuing web application samlConfiguration.setIssuer(saml_issuer) # Tells the IdP to return a persistent identifier for the user samlConfiguration.setNameIdentifierFormat(saml_name_identifier_format) # The URL at the Identity Provider where to the authentication request should be sent samlConfiguration.setIdpSsoTargetUrl(saml_idp_sso_target_url) # Enablediable RequestedAuthnContext samlConfiguration.setUseRequestedAuthnContext(saml_use_authn_context) # Load x509 certificate samlConfiguration.loadCertificateFromString(saml_certificate) self.samlConfiguration = samlConfiguration self.attributesMapping = None if (configurationAttributes.containsKey("saml_idp_attributes_list") and configurationAttributes.containsKey("saml_local_attributes_list")): saml_idp_attributes_list = configurationAttributes.get("saml_idp_attributes_list").getValue2() if (StringHelper.isEmpty(saml_idp_attributes_list)): print "Saml. Initialization. The property saml_idp_attributes_list is empty" return False saml_local_attributes_list = configurationAttributes.get("saml_local_attributes_list").getValue2() if (StringHelper.isEmpty(saml_local_attributes_list)): print "Saml. Initialization. The property saml_local_attributes_list is empty" return False self.attributesMapping = self.prepareAttributesMapping(saml_idp_attributes_list, saml_local_attributes_list) if (self.attributesMapping == None): print "Saml. Initialization. The attributes mapping isn't valid" return False self.samlExtensionModule = None if (configurationAttributes.containsKey("saml_extension_module")): saml_extension_module_name = configurationAttributes.get("saml_extension_module").getValue2() try: self.samlExtensionModule = __import__(saml_extension_module_name) saml_extension_module_init_result = self.samlExtensionModule.init(configurationAttributes) if (not saml_extension_module_init_result): return False except ImportError, ex: print "Saml. Initialization. Failed to load saml_extension_module:", saml_extension_module_name print "Saml. Initialization. Unexpected error:", ex return False
def prepareForStep(self, configurationAttributes, requestParameters, step): credentials = Identity.instance().getCredentials() context = Contexts.getEventContext() session_attributes = context.get("sessionAttributes") self.setEventContextParameters(context) if (step == 1): return True elif (step == 2): print "UAF. Prepare 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 user = credentials.getUser() if (user == None): print "UAF. Prepare for step 2. Failed to determine user name" return False uaf_auth_method = session_attributes.get("uaf_auth_method") if StringHelper.isEmpty(uaf_auth_method): print "UAF. Prepare for step 2. Failed to determine auth_method" return False print "UAF. Prepare for step 2. uaf_auth_method: '%s'" % uaf_auth_method uaf_obb_auth_method = "OOB_REG" uaf_obb_server_uri = self.uaf_server_uri + "/nnl/v2/reg" if StringHelper.equalsIgnoreCase(uaf_auth_method, "authenticate"): uaf_obb_auth_method = "OOB_AUTH" uaf_obb_server_uri = self.uaf_server_uri + "/nnl/v2/auth" # Prepare START_OBB uaf_obb_start_request_dictionary = { "operation": "START_%s" % uaf_obb_auth_method, "userName": user.getUserId(), "policyName": "default", "oobMode": { "qr": "true", "rawData": "false", "push": "false" } } uaf_obb_start_request = json.dumps( uaf_obb_start_request_dictionary, separators=(',', ':')) print "UAF. Prepare for step 2. Prepared START request: '%s' to send to '%s'" % ( uaf_obb_start_request, uaf_obb_server_uri) # Request START_OBB uaf_obb_start_response = self.executePost(uaf_obb_server_uri, uaf_obb_start_request) if uaf_obb_start_response == None: return False print "UAF. Prepare for step 2. Get START response: '%s'" % uaf_obb_start_response uaf_obb_start_response_json = json.loads(uaf_obb_start_response) # Prepare STATUS_OBB #TODO: Remove needDetails parameter uaf_obb_status_request_dictionary = { "operation": "STATUS_%s" % uaf_obb_auth_method, "userName": user.getUserId(), "needDetails": 1, "oobStatusHandle": uaf_obb_start_response_json["oobStatusHandle"], } uaf_obb_status_request = json.dumps( uaf_obb_status_request_dictionary, separators=(',', ':')) print "UAF. Prepare for step 2. Prepared STATUS request: '%s' to send to '%s'" % ( uaf_obb_status_request, uaf_obb_server_uri) context.set("uaf_obb_auth_method", uaf_obb_auth_method) context.set("uaf_obb_server_uri", uaf_obb_server_uri) context.set("uaf_obb_start_response", uaf_obb_start_response) context.set( "qr_image", uaf_obb_start_response_json["modeResult"]["qrCode"]["qrImage"]) context.set("uaf_obb_status_request", uaf_obb_status_request) return True else: return False
def authenticate(self, configurationAttributes, requestParameters, step): credentials = Identity.instance().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)): userService = UserService.instance() logged_in = userService.authenticate(user_name, user_password) if (not logged_in): return False return True elif (step == 2): userService = UserService.instance() 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 user_expDate = find_user_by_uid.getAttribute( "oxPasswordExpirationDate", False) if (user_expDate == None): print "Failed to get Date" return False print "Exp Date is : '" + user_expDate + "' ." now = datetime.datetime.now() myDate = self.parseDate(user_expDate) prevExpDate = self.previousExpDate(myDate) expDate = self.newExpirationDate(myDate) temp = expDate.strftime("%y%m%d") expDate = (expDate + temp + "195000Z") if prevExpDate < now: print "Basic (with password update). Authenticate for step 2" find_user_by_uid.setAttribute("oxPasswordExpirationDate", expDate) update_button = requestParameters.get("loginForm:updateButton") if ArrayHelper.isEmpty(update_button): return True new_password_array = requestParameters.get("new_password") if ArrayHelper.isEmpty( new_password_array) or StringHelper.isEmpty( new_password_array[0]): print "Basic (with password update). Authenticate for step 2. New password is empty" return False new_password = new_password_array[0] print "Basic (with password update). Authenticate for step 2. Attempting to set new user '" + user_name + "' password" userService.updateUser(find_user_by_uid) print "Basic (with password update). Authenticate for step 2. Password updated successfully" return True else: return False
identity.setWorkingParameter("hideez_user_name", user_name) identity.setWorkingParameter("hideez_user_password", user_password) self.hideez_count_login_steps = 2 logged_in = True # 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)
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 authenticationService = AuthenticationService.instance() 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 = DeviceRegistrationService.instance() 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_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 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_state) context.set("fido_u2f_authentication_request", ServerUtil.asJson(authenticationRequest)) context.set("fido_u2f_registration_request", ServerUtil.asJson(registrationRequest)) return True
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) valid = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), jwt.getHeader().getKeyId(),
def init(self, configurationAttributes): print "Saml. Initialization" asimba_saml_certificate_file = configurationAttributes.get( "asimba_saml_certificate_file").getValue2() saml_idp_sso_target_url = configurationAttributes.get( "saml_idp_sso_target_url").getValue2() asimba_entity_id = configurationAttributes.get( "asimba_entity_id").getValue2() saml_use_authn_context = StringHelper.toBoolean( configurationAttributes.get("saml_use_authn_context").getValue2(), True) if (saml_use_authn_context): saml_name_identifier_format = configurationAttributes.get( "saml_name_identifier_format").getValue2() else: saml_name_identifier_format = None asimba_saml_certificate = self.loadCeritificate( asimba_saml_certificate_file) if (StringHelper.isEmpty(asimba_saml_certificate)): print "Saml. Initialization. File with x509 certificate should be not empty" return False samlConfiguration = SamlConfiguration() # Set the issuer of the authentication request. This would usually be the URL of the issuing web application samlConfiguration.setIssuer(asimba_entity_id) # Tells the IdP to return a persistent identifier for the user samlConfiguration.setNameIdentifierFormat(saml_name_identifier_format) # The URL at the Identity Provider where to the authentication request should be sent samlConfiguration.setIdpSsoTargetUrl(saml_idp_sso_target_url) # Enablediable RequestedAuthnContext samlConfiguration.setUseRequestedAuthnContext(saml_use_authn_context) # Load x509 certificate samlConfiguration.loadCertificateFromString(asimba_saml_certificate) self.samlConfiguration = samlConfiguration self.generateNameId = False if configurationAttributes.containsKey("saml_generate_name_id"): self.generateNameId = StringHelper.toBoolean( configurationAttributes.get( "saml_generate_name_id").getValue2(), False) print "Saml. Initialization. The property saml_generate_name_id is %s" % self.generateNameId self.updateUser = False if configurationAttributes.containsKey("saml_update_user"): self.updateUser = StringHelper.toBoolean( configurationAttributes.get("saml_update_user").getValue2(), False) print "Saml. Initialization. The property saml_update_user is %s" % self.updateUser self.userObjectClasses = None if configurationAttributes.containsKey("user_object_classes"): self.userObjectClasses = self.prepareUserObjectClasses( configurationAttributes) self.userEnforceAttributesUniqueness = None if configurationAttributes.containsKey("enforce_uniqueness_attr_list"): self.userEnforceAttributesUniqueness = self.prepareUserEnforceUniquenessAttributes( configurationAttributes) self.attributesMapping = None if configurationAttributes.containsKey("saml_idp_attributes_mapping"): saml_idp_attributes_mapping = configurationAttributes.get( "saml_idp_attributes_mapping").getValue2() if (StringHelper.isEmpty(saml_idp_attributes_mapping)): print "Saml. Initialization. The property saml_idp_attributes_mapping is empty" return False self.attributesMapping = self.prepareAttributesMapping( saml_idp_attributes_mapping) if (self.attributesMapping == None): print "Saml. Initialization. The attributes mapping isn't valid" return False self.samlExtensionModule = None if (configurationAttributes.containsKey("saml_extension_module")): saml_extension_module_name = configurationAttributes.get( "saml_extension_module").getValue2() try: self.samlExtensionModule = __import__( saml_extension_module_name) saml_extension_module_init_result = self.samlExtensionModule.init( configurationAttributes) if (not saml_extension_module_init_result): return False except ImportError, ex: print "Saml. Initialization. Failed to load saml_extension_module: '%s'" % saml_extension_module_name print "Saml. Initialization. Unexpected error:", ex return False
def init(self, configurationAttributes): print "Saml. Initialization" asimba_saml_certificate_file = configurationAttributes.get("asimba_saml_certificate_file").getValue2() saml_idp_sso_target_url = configurationAttributes.get("saml_idp_sso_target_url").getValue2() asimba_entity_id = configurationAttributes.get("asimba_entity_id").getValue2() saml_use_authn_context = StringHelper.toBoolean(configurationAttributes.get("saml_use_authn_context").getValue2(), True) if (saml_use_authn_context): saml_name_identifier_format = configurationAttributes.get("saml_name_identifier_format").getValue2() else: saml_name_identifier_format = None asimba_saml_certificate = self.loadCeritificate(asimba_saml_certificate_file) if (StringHelper.isEmpty(asimba_saml_certificate)): print "Saml. Initialization. File with x509 certificate should be not empty" return False samlConfiguration = SamlConfiguration() # Set the issuer of the authentication request. This would usually be the URL of the issuing web application samlConfiguration.setIssuer(asimba_entity_id) # Tells the IdP to return a persistent identifier for the user samlConfiguration.setNameIdentifierFormat(saml_name_identifier_format) # The URL at the Identity Provider where to the authentication request should be sent samlConfiguration.setIdpSsoTargetUrl(saml_idp_sso_target_url) # Enablediable RequestedAuthnContext samlConfiguration.setUseRequestedAuthnContext(saml_use_authn_context) # Load x509 certificate samlConfiguration.loadCertificateFromString(asimba_saml_certificate) self.samlConfiguration = samlConfiguration self.generateNameId = False if configurationAttributes.containsKey("saml_generate_name_id"): self.generateNameId = StringHelper.toBoolean(configurationAttributes.get("saml_generate_name_id").getValue2(), False) print "Saml. Initialization. The property saml_generate_name_id is %s" % self.generateNameId self.updateUser = False if configurationAttributes.containsKey("saml_update_user"): self.updateUser = StringHelper.toBoolean(configurationAttributes.get("saml_update_user").getValue2(), False) print "Saml. Initialization. The property saml_update_user is %s" % self.updateUser self.userObjectClasses = None if configurationAttributes.containsKey("user_object_classes"): self.userObjectClasses = self.prepareUserObjectClasses(configurationAttributes) self.userEnforceAttributesUniqueness = None if configurationAttributes.containsKey("enforce_uniqueness_attr_list"): self.userEnforceAttributesUniqueness = self.prepareUserEnforceUniquenessAttributes(configurationAttributes) self.attributesMapping = None if configurationAttributes.containsKey("saml_idp_attributes_mapping"): saml_idp_attributes_mapping = configurationAttributes.get("saml_idp_attributes_mapping").getValue2() if (StringHelper.isEmpty(saml_idp_attributes_mapping)): print "Saml. Initialization. The property saml_idp_attributes_mapping is empty" return False self.attributesMapping = self.prepareAttributesMapping(saml_idp_attributes_mapping) if (self.attributesMapping == None): print "Saml. Initialization. The attributes mapping isn't valid" return False self.samlExtensionModule = None if (configurationAttributes.containsKey("saml_extension_module")): saml_extension_module_name = configurationAttributes.get("saml_extension_module").getValue2() try: self.samlExtensionModule = __import__(saml_extension_module_name) saml_extension_module_init_result = self.samlExtensionModule.init(configurationAttributes) if (not saml_extension_module_init_result): return False except ImportError, ex: print "Saml. Initialization. Failed to load saml_extension_module: '%s'" % saml_extension_module_name print "Saml. Initialization. Unexpected error:", ex return False
def authenticate(self, configurationAttributes, requestParameters, step): context = Contexts.getEventContext() authenticationService = AuthenticationService.instance() userService = UserService.instance() saml_map_user = False saml_enroll_user = False saml_enroll_all_user_attr = False # Use saml_deployment_type only if there is no attributes mapping if (configurationAttributes.containsKey("saml_deployment_type")): saml_deployment_type = StringHelper.toLowerCase(configurationAttributes.get("saml_deployment_type").getValue2()) if (StringHelper.equalsIgnoreCase(saml_deployment_type, "map")): saml_map_user = True if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll")): saml_enroll_user = True if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll_all_attr")): saml_enroll_all_user_attr = True saml_allow_basic_login = False if (configurationAttributes.containsKey("saml_allow_basic_login")): saml_allow_basic_login = StringHelper.toBoolean(configurationAttributes.get("saml_allow_basic_login").getValue2(), False) use_basic_auth = False if (saml_allow_basic_login): # Detect if user used basic authnetication method credentials = Identity.instance().getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() if (StringHelper.isNotEmpty(user_name) and StringHelper.isNotEmpty(user_password)): use_basic_auth = True if ((step == 1) and saml_allow_basic_login and use_basic_auth): print "Saml. Authenticate for step 1. Basic authentication" context.set("saml_count_login_steps", 1) 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)): userService = UserService.instance() logged_in = userService.authenticate(user_name, user_password) if (not logged_in): return False return True if (step == 1): print "Saml. Authenticate for step 1" currentSamlConfiguration = self.getCurrentSamlConfiguration(self.samlConfiguration, configurationAttributes, requestParameters) if (currentSamlConfiguration == None): print "Saml. Prepare for step 1. Client saml configuration is invalid" return False saml_response_array = requestParameters.get("SAMLResponse") if ArrayHelper.isEmpty(saml_response_array): print "Saml. Authenticate for step 1. saml_response is empty" return False saml_response = saml_response_array[0] print "Saml. Authenticate for step 1. saml_response:", saml_response samlResponse = Response(currentSamlConfiguration) samlResponse.loadXmlFromBase64(saml_response) saml_validate_response = True if (configurationAttributes.containsKey("saml_validate_response")): saml_validate_response = StringHelper.toBoolean(configurationAttributes.get("saml_validate_response").getValue2(), False) if (saml_validate_response): if (not samlResponse.isValid()): print "Saml. Authenticate for step 1. saml_response isn't valid" saml_response_name_id = samlResponse.getNameId() if (StringHelper.isEmpty(saml_response_name_id)): print "Saml. Authenticate for step 1. saml_response_name_id is invalid" return False print "Saml. Authenticate for step 1. saml_response_name_id:", saml_response_name_id saml_response_attributes = samlResponse.getAttributes() print "Saml. Authenticate for step 1. attributes: ", saml_response_attributes # Use persistent Id as saml_user_uid saml_user_uid = saml_response_name_id if (saml_map_user): # Use mapping to local IDP user print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml:", saml_user_uid # Check if the is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" print "Saml. Authenticate for step 1. Setting count steps to 2" context.set("saml_count_login_steps", 2) context.set("saml_user_uid", saml_user_uid) return True found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name:", found_user_name user_authenticated = authenticationService.authenticate(found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result:", post_login_result return post_login_result elif (saml_enroll_user): # Use auto enrollment to local IDP print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml:", saml_user_uid # Check if the is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): # Auto user enrollemnt print "Saml. Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP" # Convert saml result attributes keys to lover case saml_response_normalized_attributes = HashMap() for saml_response_attribute_entry in saml_response_attributes.entrySet(): saml_response_normalized_attributes.put( StringHelper.toLowerCase(saml_response_attribute_entry.getKey()), saml_response_attribute_entry.getValue()) currentAttributesMapping = self.prepareCurrentAttributesMapping(self.attributesMapping, configurationAttributes, requestParameters) print "Saml. Authenticate for step 1. Using next attributes mapping", currentAttributesMapping newUser = User() for attributesMappingEntry in currentAttributesMapping.entrySet(): idpAttribute = attributesMappingEntry.getKey() localAttribute = attributesMappingEntry.getValue() localAttributeValue = saml_response_normalized_attributes.get(idpAttribute) if (localAttribute != None): newUser.setAttribute(localAttribute, localAttributeValue) newUser.setAttribute("oxExternalUid", "saml:" + saml_user_uid) print "Saml. Authenticate for step 1. Attempting to add user", saml_user_uid, " with next attributes", newUser.getCustomAttributes() find_user_by_uid = userService.addUser(newUser, True) print "Saml. Authenticate for step 1. Added new user with UID", find_user_by_uid.getUserId() found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name:", found_user_name user_authenticated = authenticationService.authenticate(found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result:", post_login_result return post_login_result elif (saml_enroll_all_user_attr): print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml:" + saml_user_uid # Check if the is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" user = User() customAttributes = ArrayList() for key in attributes.keySet(): ldapAttributes = attributeService.getAllAttributes() for ldapAttribute in ldapAttributes: saml2Uri = ldapAttribute.getSaml2Uri() if(saml2Uri == None): saml2Uri = attributeService.getDefaultSaml2Uri(ldapAttribute.getName()) if(saml2Uri == key): attribute = CustomAttribute(ldapAttribute.getName()) attribute.setValues(attributes.get(key)) customAttributes.add(attribute) attribute = CustomAttribute("oxExternalUid") attribute.setValue("saml:" + saml_user_uid) customAttributes.add(attribute) user.setCustomAttributes(customAttributes) if(user.getAttribute("sn") == None): attribute = CustomAttribute("sn") attribute.setValue(saml_user_uid) customAttributes.add(attribute) if(user.getAttribute("cn") == None): attribute = CustomAttribute("cn") attribute.setValue(saml_user_uid) customAttributes.add(attribute) find_user_by_uid = userService.addUser(user, True) print "Saml. Authenticate for step 1. Added new user with UID", find_user_by_uid.getUserId() found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name:", found_user_name user_authenticated = authenticationService.authenticate(found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result:", post_login_result return post_login_result else: # Check if the is user with specified saml_user_uid print "Saml. Authenticate for step 1. Attempting to find user by uid:", saml_user_uid find_user_by_uid = userService.getUser(saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" return False found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name:", found_user_name user_authenticated = authenticationService.authenticate(found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result:", post_login_result return post_login_result elif (step == 2): print "Saml. Authenticate for step 2" sessionAttributes = context.get("sessionAttributes") if (sessionAttributes == None) or not sessionAttributes.containsKey("saml_user_uid"): print "Saml. Authenticate for step 2. saml_user_uid is empty" return False saml_user_uid = sessionAttributes.get("saml_user_uid") passed_step1 = StringHelper.isNotEmptyString(saml_user_uid) if (not passed_step1): 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 # Check if there is user which has saml_user_uid # Avoid mapping Saml account to more than one IDP account find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): # Add saml_user_uid to user one id UIDs find_user_by_uid = userService.addUserAttribute(user_name, "oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 2. Failed to update current user" return False post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 2. post_login_result:", post_login_result return post_login_result else: found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 2. found_user_name:", found_user_name if StringHelper.equals(user_name, found_user_name): post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 2. post_login_result:", post_login_result return post_login_result return False else: return False
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): identity = CdiUtil.bean(Identity) userService = CdiUtil.bean(UserService) authenticationService = CdiUtil.bean(AuthenticationService) if step == 1: credentials = identity.getCredentials() user_name = credentials.getUsername() 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 else: find_user_by_uid = userService.getUser(user_name) status_attribute_value = userService.getCustomAttribute( find_user_by_uid, "mail") user_mail = status_attribute_value.getValue() self.setRequestScopedParameters(identity) isCompromised = False isCompromised = self.is_compromised(user_mail, user_password, configurationAttributes) if (isCompromised): identity.setWorkingParameter("pwd_compromised", isCompromised) identity.setWorkingParameter("user_name", user_name) return True else: return True elif step == 2: print "compromised_password. Authenticate for step 2" form_answer_array = requestParameters.get("loginForm:question") if ArrayHelper.isEmpty(form_answer_array): return False form_answer = form_answer_array[0] if (form_answer == self.secretanswer): return True return False elif step == 3: authenticationService = CdiUtil.bean(AuthenticationService) print "compromised_password (with password update). Authenticate for step 3" userService = CdiUtil.bean(UserService) update_button = requestParameters.get("loginForm:updateButton") new_password_array = requestParameters.get("new_password") if ArrayHelper.isEmpty(new_password_array) or StringHelper.isEmpty( new_password_array[0]): print "compromised_password (with password update). Authenticate for step 3. New password is empty" return False new_password = new_password_array[0] session_attributes = identity.getSessionId().getSessionAttributes() user_name = session_attributes.get("user_name") print "compromised_password (with password update). Authenticate for step 3. Attempting to set new user '" + user_name + "' password" find_user_by_uid = userService.getUser(user_name) if (find_user_by_uid == None): print "compromised_password (with password update). Authenticate for step 3. Failed to find user" return False find_user_by_uid.setAttribute("userPassword", new_password) userService.updateUser(find_user_by_uid) print "compromised_password (with password update). Authenticate for step 3. Password updated successfully" logged_in = authenticationService.authenticate(user_name) return True
def authenticate(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() self.setRequestScopedParameters(identity) if step == 1: print "OTP. Authenticate for step 1" authenticated_user = self.processBasicAuthentication(credentials) if authenticated_user == None: return False otp_auth_method = "authenticate" # Uncomment this block if you need to allow user second OTP registration #enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton") #if StringHelper.isNotEmpty(enrollment_mode): # otp_auth_method = "enroll" if otp_auth_method == "authenticate": user_enrollments = self.findEnrollments( authenticated_user.getUserId()) if len(user_enrollments) == 0: otp_auth_method = "enroll" print "OTP. Authenticate for step 1. There is no OTP enrollment for user '%s'. Changing otp_auth_method to '%s'" % ( authenticated_user.getUserId(), otp_auth_method) if otp_auth_method == "enroll": print "OTP. Authenticate for step 1. Setting count steps: '%s'" % 3 identity.setWorkingParameter("otp_count_login_steps", 3) print "OTP. Authenticate for step 1. otp_auth_method: '%s'" % otp_auth_method identity.setWorkingParameter("otp_auth_method", otp_auth_method) return True elif step == 2: print "OTP. Authenticate for step 2" authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if user == None: print "OTP. Authenticate for step 2. Failed to determine user name" return False session_id_validation = self.validateSessionId(identity) if not session_id_validation: return False # Restore state from session otp_auth_method = identity.getWorkingParameter("otp_auth_method") if otp_auth_method == 'enroll': auth_result = ServerUtil.getFirstValue(requestParameters, "auth_result") if not StringHelper.isEmpty(auth_result): print "OTP. Authenticate for step 2. User not enrolled OTP" return False print "OTP. Authenticate for step 2. Skipping this step during enrollment" return True otp_auth_result = self.processOtpAuthentication( requestParameters, user.getUserId(), identity, otp_auth_method) print "OTP. Authenticate for step 2. OTP authentication result: '%s'" % otp_auth_result return otp_auth_result elif step == 3: print "OTP. Authenticate for step 3" authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if user == None: print "OTP. Authenticate for step 2. Failed to determine user name" return False session_id_validation = self.validateSessionId(identity) if not session_id_validation: return False # Restore state from session otp_auth_method = identity.getWorkingParameter("otp_auth_method") if otp_auth_method != 'enroll': return False otp_auth_result = self.processOtpAuthentication( requestParameters, user.getUserId(), identity, otp_auth_method) print "OTP. Authenticate for step 3. OTP authentication result: '%s'" % otp_auth_result return otp_auth_result else: return False
def prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) session_attributes = identity.getSessionId().getSessionAttributes() client_redirect_uri = self.getClientRedirecUri(session_attributes) if client_redirect_uri == None: print "Super-Gluu. Prepare for step. redirect_uri is not set" return False self.setRequestScopedParameters(identity, step) if step == 1: print "Super-Gluu. Prepare for step 1" if self.oneStep: session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie() if StringHelper.isEmpty(session_id): print "Super-Gluu. Prepare for step 2. Failed to determine session_id" return False issuer = CdiUtil.bean(ConfigurationFactory).getConfiguration().getIssuer() super_gluu_request_dictionary = {'app': client_redirect_uri, 'issuer': issuer, 'state': session_id, 'created': datetime.datetime.now().isoformat()} self.addGeolocationData(session_attributes, super_gluu_request_dictionary) super_gluu_request = json.dumps(super_gluu_request_dictionary, separators=(',',':')) print "Super-Gluu. Prepare for step 1. Prepared super_gluu_request:", super_gluu_request identity.setWorkingParameter("super_gluu_request", super_gluu_request) elif self.twoStep: identity.setWorkingParameter("display_register_action", True) return True elif step == 2: print "Super-Gluu. Prepare for step 2" if self.oneStep: return True authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if user == None: print "Super-Gluu. Prepare for step 2. Failed to determine user name" return False if session_attributes.containsKey("super_gluu_request"): super_gluu_request = session_attributes.get("super_gluu_request") if not StringHelper.equalsIgnoreCase(super_gluu_request, "timeout"): print "Super-Gluu. Prepare for step 2. Request was generated already" return True session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie() if StringHelper.isEmpty(session_id): print "Super-Gluu. Prepare for step 2. Failed to determine session_id" return False auth_method = session_attributes.get("super_gluu_auth_method") if StringHelper.isEmpty(auth_method): print "Super-Gluu. Prepare for step 2. Failed to determine auth_method" return False print "Super-Gluu. Prepare for step 2. auth_method: '%s'" % auth_method issuer = CdiUtil.bean(ConfigurationFactory).getAppConfiguration().getIssuer() super_gluu_request_dictionary = {'username': user.getUserId(), 'app': client_redirect_uri, 'issuer': issuer, 'method': auth_method, 'state': session_id, 'created': datetime.datetime.now().isoformat()} self.addGeolocationData(session_attributes, super_gluu_request_dictionary) super_gluu_request = json.dumps(super_gluu_request_dictionary, separators=(',',':')) print "Super-Gluu. Prepare for step 2. Prepared super_gluu_request:", super_gluu_request identity.setWorkingParameter("super_gluu_request", super_gluu_request) identity.setWorkingParameter("super_gluu_auth_method", auth_method) if auth_method in ['authenticate']: self.sendPushNotification(client_redirect_uri, user, super_gluu_request) return True else: return False
def authenticate(self, configurationAttributes, requestParameters, step): context = Contexts.getEventContext() authenticationService = AuthenticationService.instance() userService = UserService.instance() httpService = HttpService.instance(); stringEncrypter = StringEncrypter.defaultInstance() cas_host = configurationAttributes.get("cas_host").getValue2() cas_extra_opts = configurationAttributes.get("cas_extra_opts").getValue2() cas_map_user = StringHelper.toBoolean(configurationAttributes.get("cas_map_user").getValue2(), False) cas_renew_opt = StringHelper.toBoolean(configurationAttributes.get("cas_renew_opt").getValue2(), False) if (step == 1): print "CAS2 authenticate for step 1" ticket_array = requestParameters.get("ticket") if ArrayHelper.isEmpty(ticket_array): print "CAS2 authenticate for step 1. ticket is empty" return False ticket = ticket_array[0] print "CAS2 authenticate for step 1. ticket: " + ticket if (StringHelper.isEmptyString(ticket)): print "CAS2 authenticate for step 1. ticket is invalid" return False # Validate ticket request = FacesContext.getCurrentInstance().getExternalContext().getRequest() parametersMap = HashMap() parametersMap.put("service", httpService.constructServerUrl(request) + "/postlogin") if (cas_renew_opt): parametersMap.put("renew", "true") parametersMap.put("ticket", ticket) cas_service_request_uri = authenticationService.parametersAsString(parametersMap) cas_service_request_uri = cas_host + "/serviceValidate?" + cas_service_request_uri if StringHelper.isNotEmpty(cas_extra_opts): cas_service_request_uri = cas_service_request_uri + "&" + cas_extra_opts print "CAS2 authenticate for step 1. cas_service_request_uri: " + cas_service_request_uri http_client = httpService.getHttpsClientTrustAll(); http_response = httpService.executeGet(http_client, cas_service_request_uri) validation_content = httpService.convertEntityToString(httpService.getResponseContent(http_response)) print "CAS2 authenticate for step 1. validation_content: " + validation_content if StringHelper.isEmpty(validation_content): print "CAS2 authenticate for step 1. Ticket validation response is invalid" return False cas2_auth_failure = self.parse_tag(validation_content, "cas:authenticationFailure") print "CAS2 authenticate for step 1. cas2_auth_failure: ", cas2_auth_failure cas2_user_uid = self.parse_tag(validation_content, "cas:user") print "CAS2 authenticate for step 1. cas2_user_uid: ", cas2_user_uid if ((cas2_auth_failure != None) or (cas2_user_uid == None)): print "CAS2 authenticate for step 1. Ticket is invalid" return False if (cas_map_user): print "CAS2 authenticate for step 1. Attempting to find user by oxExternalUid: cas2:" + cas2_user_uid # Check if the is user with specified cas2_user_uid find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "cas2:" + cas2_user_uid) if (find_user_by_uid == None): print "CAS2 authenticate for step 1. Failed to find user" print "CAS2 authenticate for step 1. Setting count steps to 2" context.set("cas2_count_login_steps", 2) context.set("cas2_user_uid", stringEncrypter.encrypt(cas2_user_uid)) return True found_user_name = find_user_by_uid.getUserId() print "CAS2 authenticate for step 1. found_user_name: " + found_user_name credentials = Identity.instance().getCredentials() credentials.setUsername(found_user_name) credentials.setUser(find_user_by_uid) print "CAS2 authenticate for step 1. Setting count steps to 1" context.set("cas2_count_login_steps", 1) return True else: print "CAS2 authenticate for step 1. Attempting to find user by uid:" + cas2_user_uid # Check if the is user with specified cas2_user_uid find_user_by_uid = userService.getUser(cas2_user_uid) if (find_user_by_uid == None): print "CAS2 authenticate for step 1. Failed to find user" return False found_user_name = find_user_by_uid.getUserId() print "CAS2 authenticate for step 1. found_user_name: " + found_user_name credentials = Identity.instance().getCredentials() credentials.setUsername(found_user_name) credentials.setUser(find_user_by_uid) print "CAS2 authenticate for step 1. Setting count steps to 1" context.set("cas2_count_login_steps", 1) return True elif (step == 2): print "CAS2 authenticate for step 2" cas2_user_uid_array = requestParameters.get("cas2_user_uid") if ArrayHelper.isEmpty(cas2_user_uid_array): print "CAS2 authenticate for step 2. cas2_user_uid is empty" return False cas2_user_uid = stringEncrypter.decrypt(cas2_user_uid_array[0]) passed_step1 = StringHelper.isNotEmptyString(cas2_user_uid) if (not passed_step1): 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 # Check if there is user which has cas2_user_uid # Avoid mapping CAS2 account to more than one IDP account find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "cas2:" + cas2_user_uid) if (find_user_by_uid == None): # Add cas2_user_uid to user one id UIDs find_user_by_uid = userService.addUserAttribute(user_name, "oxExternalUid", "cas2:" + cas2_user_uid) if (find_user_by_uid == None): print "CAS2 authenticate for step 2. Failed to update current user" return False return True else: found_user_name = find_user_by_uid.getUserId() print "CAS2 authenticate for step 2. found_user_name: " + found_user_name if StringHelper.equals(user_name, found_user_name): return True return False else: return False
def init(self, configurationAttributes): print "Super-Gluu. Initialization" if not configurationAttributes.containsKey("authentication_mode"): print "Super-Gluu. Initialization. Property authentication_mode is mandatory" return False self.registrationUri = None if configurationAttributes.containsKey("registration_uri"): self.registrationUri = configurationAttributes.get("registration_uri").getValue2() authentication_mode = configurationAttributes.get("authentication_mode").getValue2() if StringHelper.isEmpty(authentication_mode): print "Super-Gluu. Initialization. Failed to determine authentication_mode. authentication_mode configuration parameter is empty" return False self.oneStep = StringHelper.equalsIgnoreCase(authentication_mode, "one_step") self.twoStep = StringHelper.equalsIgnoreCase(authentication_mode, "two_step") if not (self.oneStep or self.twoStep): print "Super-Gluu. Initialization. Valid authentication_mode values are one_step and two_step" return False self.enabledPushNotifications = self.initPushNotificationService(configurationAttributes) self.androidUrl = None if configurationAttributes.containsKey("supergluu_android_download_url"): self.androidUrl = configurationAttributes.get("supergluu_android_download_url").getValue2() self.IOSUrl = None if configurationAttributes.containsKey("supergluu_ios_download_url"): self.IOSUrl = configurationAttributes.get("supergluu_ios_download_url").getValue2() self.customLabel = None if configurationAttributes.containsKey("label"): self.customLabel = configurationAttributes.get("label").getValue2() self.customQrOptions = {} if configurationAttributes.containsKey("qr_options"): self.customQrOptions = configurationAttributes.get("qr_options").getValue2() self.use_super_gluu_group = False if configurationAttributes.containsKey("super_gluu_group"): self.super_gluu_group = configurationAttributes.get("super_gluu_group").getValue2() self.use_super_gluu_group = True print "Super-Gluu. Initialization. Using super_gluu only if user belong to group: %s" % self.super_gluu_group self.use_audit_group = False if configurationAttributes.containsKey("audit_group"): self.audit_group = configurationAttributes.get("audit_group").getValue2() if (not configurationAttributes.containsKey("audit_group_email")): print "Super-Gluu. Initialization. Property audit_group_email is not specified" return False self.audit_email = configurationAttributes.get("audit_group_email").getValue2() self.use_audit_group = True print "Super-Gluu. Initialization. Using audit group: %s" % self.audit_group if self.use_super_gluu_group or self.use_audit_group: if not configurationAttributes.containsKey("audit_attribute"): print "Super-Gluu. Initialization. Property audit_attribute is not specified" return False else: self.audit_attribute = configurationAttributes.get("audit_attribute").getValue2() print "Super-Gluu. Initialized successfully. oneStep: '%s', twoStep: '%s', pushNotifications: '%s', customLabel: '%s'" % (self.oneStep, self.twoStep, self.enabledPushNotifications, self.customLabel) return True
def setDefaultUid(self, user, saml_user_uid): if StringHelper.isEmpty(user.getUserId()): user.setUserId(saml_user_uid)
def setDefaultUid(self, user, saml_user_uid): if StringHelper.isEmpty(user.getUserId()): user.setUserId(saml_user_uid)
def init(self, configurationAttributes): print "Saml. Initialization" saml_certificate_file = configurationAttributes.get("saml_certificate_file").getValue2() saml_idp_sso_target_url = configurationAttributes.get("saml_idp_sso_target_url").getValue2() saml_issuer = configurationAttributes.get("saml_issuer").getValue2() saml_use_authn_context = StringHelper.toBoolean(configurationAttributes.get("saml_use_authn_context").getValue2(), True) if (saml_use_authn_context): saml_name_identifier_format = configurationAttributes.get("saml_name_identifier_format").getValue2() else: saml_name_identifier_format = None saml_certificate = self.loadCeritificate(saml_certificate_file) if (StringHelper.isEmpty(saml_certificate)): print "Saml. Initialization. File with x509 certificate should be not empty" return False samlConfiguration = SamlConfiguration() # Set the issuer of the authentication request. This would usually be the URL of the issuing web application samlConfiguration.setIssuer(saml_issuer) # Tells the IdP to return a persistent identifier for the user samlConfiguration.setNameIdentifierFormat(saml_name_identifier_format) # The URL at the Identity Provider where to the authentication request should be sent samlConfiguration.setIdpSsoTargetUrl(saml_idp_sso_target_url) # Enablediable RequestedAuthnContext samlConfiguration.setUseRequestedAuthnContext(saml_use_authn_context) # Load x509 certificate samlConfiguration.loadCertificateFromString(saml_certificate) self.samlConfiguration = samlConfiguration self.attributesMapping = None if (configurationAttributes.containsKey("saml_idp_attributes_list") and configurationAttributes.containsKey("saml_local_attributes_list")): saml_idp_attributes_list = configurationAttributes.get("saml_idp_attributes_list").getValue2() if (StringHelper.isEmpty(saml_idp_attributes_list)): print "Saml. Initialization. The property saml_idp_attributes_list is empty" return False saml_local_attributes_list = configurationAttributes.get("saml_local_attributes_list").getValue2() if (StringHelper.isEmpty(saml_local_attributes_list)): print "Saml. Initialization. The property saml_local_attributes_list is empty" return False self.attributesMapping = self.prepareAttributesMapping(saml_idp_attributes_list, saml_local_attributes_list) if (self.attributesMapping == None): print "Saml. Initialization. The attributes mapping isn't valid" return False self.samlExtensionModule = None if (configurationAttributes.containsKey("saml_extension_module")): saml_extension_module_name = configurationAttributes.get("saml_extension_module").getValue2() try: self.samlExtensionModule = __import__(saml_extension_module_name) saml_extension_module_init_result = self.samlExtensionModule.init(configurationAttributes) if (not saml_extension_module_init_result): return False except ImportError, ex: print "Saml. Initialization. Failed to load saml_extension_module:", saml_extension_module_name print "Saml. Initialization. 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() 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 authenticate(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) userService = CdiUtil.bean(UserService) identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() if step == 1: print "Basic (with password update). Authenticate for step 1" 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 find_user_by_uid = authenticationService.getAuthenticatedUser() user_expDate = find_user_by_uid.getAttribute( "oxPasswordExpirationDate", False) if user_expDate == None: print "Basic (with password update). Authenticate for step 1. User has no oxPasswordExpirationDate date" return False dt = StaticUtils.decodeGeneralizedTime(user_expDate) # Get Current Date calendar = GregorianCalendar(TimeZone.getTimeZone("UTC")) now = calendar.getTime() if now.compareTo(dt) > 0: # Add 90 Days to current date calendar.setTime(now) calendar.add(calendar.DATE, 90) dt_plus_90 = calendar.getTime() expDate = StaticUtils.encodeGeneralizedTime(dt_plus_90) identity.setWorkingParameter("expDate", expDate) return True elif step == 2: print "Basic (with password update). Authenticate for step 2" user = authenticationService.getAuthenticatedUser() if user == None: print "Basic (with password update). Authenticate for step 2. Failed to determine user name" return False user_name = user.getUserId() find_user_by_uid = userService.getUser(user_name) newExpDate = identity.getWorkingParameter("expDate") if find_user_by_uid == None: print "Basic (with password update). Authenticate for step 2. Failed to find user" return False print "Basic (with password update). Authenticate for step 2" update_button = requestParameters.get("loginForm:updateButton") if ArrayHelper.isEmpty(update_button): return True find_user_by_uid.setAttribute("oxPasswordExpirationDate", newExpDate) new_password_array = requestParameters.get("new_password") if ArrayHelper.isEmpty(new_password_array) or StringHelper.isEmpty( new_password_array[0]): print "Basic (with password update). Authenticate for step 2. New password is empty" return False new_password = new_password_array[0] find_user_by_uid.setAttribute("userPassword", new_password) print "Basic (with password update). Authenticate for step 2. Attempting to set new user '%s' password" % user_name 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, 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() 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 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
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): credentials = Identity.instance().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)): userService = UserService.instance() logged_in = userService.authenticate(user_name, user_password) if (not logged_in): return False return True elif (step == 2): userService = UserService.instance() 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 user_expDate = find_user_by_uid.getAttribute("oxPasswordExpirationDate", False) if (user_expDate == None): print "Failed to get Date" return False print "Exp Date is : '" + user_expDate + "' ." now = datetime.datetime.now() myDate = self.parseDate(user_expDate) prevExpDate = self.previousExpDate(myDate) expDate = self.newExpirationDate(myDate) temp = expDate.strftime("%y%m%d") expDate = (expDate + temp + "195000Z") if prevExpDate < now: print "Basic (with password update). Authenticate for step 2" find_user_by_uid.setAttribute("oxPasswordExpirationDate", expDate) update_button = requestParameters.get("loginForm:updateButton") if ArrayHelper.isEmpty(update_button): return True new_password_array = requestParameters.get("new_password") if ArrayHelper.isEmpty(new_password_array) or StringHelper.isEmpty(new_password_array[0]): print "Basic (with password update). Authenticate for step 2. New password is empty" return False new_password = new_password_array[0] print "Basic (with password update). Authenticate for step 2. Attempting to set new user '" + user_name + "' password" userService.updateUser(find_user_by_uid) print "Basic (with password update). Authenticate for step 2. Password updated successfully" return True else: return False