def lockUser(self, user_name): if StringHelper.isEmpty(user_name): return None userService = CdiUtil.bean(UserService) cacheService= CdiUtil.bean(CacheService) facesMessages = CdiUtil.bean(FacesMessages) facesMessages.setKeepMessages() 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, .jans.tatus") 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, .jans.tatus", "inactive") userService.setCustomAttribute(find_user_by_uid, "oxTrustActive", "false") updated_user = userService.updateUser(find_user_by_uid) object_to_store = json.dumps({'locked': True, 'created': LocalDateTime.now().toString()}, separators=(',',':')) cacheService.put(StringHelper.toString(self.lockExpirationTime), "lock_user_"+user_name, object_to_store); facesMessages.add(FacesMessage.SEVERITY_ERROR, "Your account is locked. Please try again after " + StringHelper.toString(self.lockExpirationTime) + " secs") print "Basic (lock account). Lock user. User '%s' locked" % user_name
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 authorize(self, context): # context is reference of org.jans.oxauth.uma.authorization.UmaAuthorizationContext print "RPT Policy. Authorizing ..." client_id=context.getClient().getClientId() print "UmaRptPolicy. client_id = %s" % client_id if (StringHelper.isEmpty(client_id)): return False if (self.clientsSet.contains(client_id)): print "UmaRptPolicy. Authorizing client" return True else: print "UmaRptPolicy. Client isn't authorized" return False
def setUserAttributeValue(self, user_name, attribute_name, attribute_value): if StringHelper.isEmpty(user_name): return None userService = CdiUtil.bean(UserService) 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 = CdiUtil.bean(UserService) 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 unLockUser(self, user_name): if StringHelper.isEmpty(user_name): return None userService = CdiUtil.bean(UserService) cacheService= CdiUtil.bean(CacheService) find_user_by_uid = userService.getUser(user_name) if (find_user_by_uid == None): return None object_to_store = json.dumps({'locked': False, 'created': LocalDateTime.now().toString()}, separators=(',',':')) cacheService.put(StringHelper.toString(self.lockExpirationTime), "lock_user_"+user_name, object_to_store); userService.setCustomAttribute(find_user_by_uid, .jans.tatus", "active") userService.setCustomAttribute(find_user_by_uid, "oxTrustActive", "true") userService.setCustomAttribute(find_user_by_uid, self.invalidLoginCountAttribute, None) updated_user = userService.updateUser(find_user_by_uid) print "Basic (lock account). Lock user. User '%s' unlocked" % user_name
def prepareClientsSet(self, configurationAttributes): clientsSet = HashSet() if (not configurationAttributes.containsKey("allowed_clients")): return clientsSet allowedClientsList = configurationAttributes.get("allowed_clients").getValue2() if (StringHelper.isEmpty(allowedClientsList)): print "UmaRptPolicy. The property allowed_clients is empty" return clientsSet allowedClientsListArray = StringHelper.split(allowedClientsList, ",") if (ArrayHelper.isEmpty(allowedClientsListArray)): print "UmaRptPolicy. No clients specified in allowed_clients property" return clientsSet # Convert to HashSet to quick search i = 0 count = len(allowedClientsListArray) while (i < count): client = allowedClientsListArray[i] clientsSet.add(client) i = i + 1 return clientsSet
def authenticate(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() user_name = credentials.getUsername() userService = CdiUtil.bean(UserService) authenticationService = CdiUtil.bean(AuthenticationService) if step == 1: print "Cert. Authenticate for step 1" login_button = ServerUtil.getFirstValue(requestParameters, "loginForm:loginButton") if StringHelper.isEmpty(login_button): print "Cert. Authenticate for step 1. Form were submitted incorrectly" return False if self.enabled_recaptcha: print "Cert. Authenticate for step 1. Validating recaptcha response" recaptcha_response = ServerUtil.getFirstValue( requestParameters, "g-recaptcha-response") recaptcha_result = self.validateRecaptcha(recaptcha_response) print "Cert. Authenticate for step 1. recaptcha_result: '%s'" % recaptcha_result return recaptcha_result return True elif step == 2: print "Cert. Authenticate for step 2" # Validate if user selected certificate cert_x509 = self.getSessionAttribute("cert_x509") if cert_x509 == None: print "Cert. Authenticate for step 2. User not selected any certs" identity.setWorkingParameter("cert_selected", False) # Return True to inform user how to reset workflow return True else: identity.setWorkingParameter("cert_selected", True) x509Certificate = self.certFromString(cert_x509) subjectX500Principal = x509Certificate.getSubjectX500Principal() print "Cert. Authenticate for step 2. User selected certificate with DN '%s'" % subjectX500Principal # Validate certificates which user selected valid = self.validateCertificate(x509Certificate) if not valid: print "Cert. Authenticate for step 2. Certificate DN '%s' is not valid" % subjectX500Principal identity.setWorkingParameter("cert_valid", False) # Return True to inform user how to reset workflow return True identity.setWorkingParameter("cert_valid", True) # Calculate certificate fingerprint x509CertificateFingerprint = self.calculateCertificateFingerprint( x509Certificate) identity.setWorkingParameter("cert_x509_fingerprint", x509CertificateFingerprint) print "Cert. Authenticate for step 2. Fingerprint is '%s' of certificate with DN '%s'" % ( x509CertificateFingerprint, subjectX500Principal) # Attempt to find user by certificate fingerprint cert_user_external_uid = "cert:%s" % x509CertificateFingerprint print "Cert. Authenticate for step 2. Attempting to find user by oxExternalUid attribute value %s" % cert_user_external_uid find_user_by_external_uid = userService.getUserByAttribute( "oxExternalUid", cert_user_external_uid) if find_user_by_external_uid == None: print "Cert. Authenticate for step 2. Failed to find user" if self.map_user_cert: print "Cert. Authenticate for step 2. Storing cert_user_external_uid for step 3" identity.setWorkingParameter("cert_user_external_uid", cert_user_external_uid) return True else: print "Cert. Authenticate for step 2. Mapping cert to user account is not allowed" identity.setWorkingParameter("cert_count_login_steps", 2) return False foundUserName = find_user_by_external_uid.getUserId() print "Cert. Authenticate for step 2. foundUserName: "******"Cert. Authenticate for step 2. Setting count steps to 2" identity.setWorkingParameter("cert_count_login_steps", 2) return logged_in elif step == 3: print "Cert. Authenticate for step 3" cert_user_external_uid = self.getSessionAttribute( "cert_user_external_uid") if cert_user_external_uid == None: print "Cert. Authenticate for step 3. cert_user_external_uid is empty" return False user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): logged_in = authenticationService.authenticate( user_name, user_password) if (not logged_in): return False # Double check just to make sure. We did checking in previous step # Check if there is user which has cert_user_external_uid # Avoid mapping user cert to more than one IDP account find_user_by_external_uid = userService.getUserByAttribute( "oxExternalUid", cert_user_external_uid) if find_user_by_external_uid == None: # Add cert_user_external_uid to user's external GUID list find_user_by_external_uid = userService.addUserAttribute( user_name, "oxExternalUid", cert_user_external_uid) if find_user_by_external_uid == None: print "Cert. Authenticate for step 3. Failed to update current user" return False return True return True else: return False
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, user_name) 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, user_name) 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): 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 identity.setWorkingParameter("retry_current_step", False) 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): # defect fix #1225 - Retry the step, show QR code again if auth_result == 'timeout': print "OTP. QR-code timeout. Authenticate for step %s. Reinitializing current step" % step identity.setWorkingParameter("retry_current_step", True) return True 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): authenticationService = CdiUtil.bean(AuthenticationService) identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() session_attributes = identity.getSessionId().getSessionAttributes() self.setRequestScopedParameters(identity) if (step == 1): return True elif (step == 2): print "UAF. Prepare for step 2" session = CdiUtil.bean(SessionIdService).getSessionId() if session == None: print "UAF. Prepare for step 2. Failed to determine session_id" return False 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) identity.setWorkingParameter("uaf_obb_auth_method", uaf_obb_auth_method) identity.setWorkingParameter("uaf_obb_server_uri", uaf_obb_server_uri) identity.setWorkingParameter("uaf_obb_start_response", uaf_obb_start_response) identity.setWorkingParameter( "qr_image", uaf_obb_start_response_json["modeResult"]["qrCode"]["qrImage"]) identity.setWorkingParameter("uaf_obb_status_request", uaf_obb_status_request) return True else: return False
def authenticate(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() session_attributes = identity.getSessionId().getSessionAttributes() self.setRequestScopedParameters(identity) if (step == 1): print "UAF. Authenticate for step 1" user_name = credentials.getUsername() authenticated_user = self.processBasicAuthentication(credentials) if authenticated_user == None: return False uaf_auth_method = "authenticate" # Uncomment this block if you need to allow user second device registration #enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton") #if StringHelper.isNotEmpty(enrollment_mode): # uaf_auth_method = "enroll" if uaf_auth_method == "authenticate": user_enrollments = self.findEnrollments(credentials) if len(user_enrollments) == 0: uaf_auth_method = "enroll" print "UAF. Authenticate for step 1. There is no UAF enrollment for user '%s'. Changing uaf_auth_method to '%s'" % ( user_name, uaf_auth_method) print "UAF. Authenticate for step 1. uaf_auth_method: '%s'" % uaf_auth_method identity.setWorkingParameter("uaf_auth_method", uaf_auth_method) return True elif (step == 2): print "UAF. Authenticate for step 2" session = CdiUtil.bean(SessionIdService).getSessionId() if session == None: print "UAF. Prepare for step 2. Failed to determine session_id" return False user = authenticationService.getAuthenticatedUser() if (user == None): print "UAF. Authenticate for step 2. Failed to determine user name" return False user_name = user.getUserId() uaf_auth_result = ServerUtil.getFirstValue(requestParameters, "auth_result") if uaf_auth_result != "success": print "UAF. Authenticate for step 2. auth_result is '%s'" % uaf_auth_result return False # Restore state from session uaf_auth_method = session_attributes.get("uaf_auth_method") if not uaf_auth_method in ['enroll', 'authenticate']: print "UAF. Authenticate for step 2. Failed to authenticate user. uaf_auth_method: '%s'" % uaf_auth_method return False # Request STATUS_OBB if True: #TODO: Remove this condition # It's workaround becuase it's not possible to call STATUS_OBB 2 times. First time on browser and second ime on server uaf_user_device_handle = ServerUtil.getFirstValue( requestParameters, "auth_handle") else: uaf_obb_auth_method = session_attributes.get( "uaf_obb_auth_method") uaf_obb_server_uri = session_attributes.get( "uaf_obb_server_uri") uaf_obb_start_response = session_attributes.get( "uaf_obb_start_response") # Prepare STATUS_OBB uaf_obb_start_response_json = json.loads( uaf_obb_start_response) uaf_obb_status_request_dictionary = { "operation": "STATUS_%s" % uaf_obb_auth_method, "userName": user_name, "needDetails": 1, "oobStatusHandle": uaf_obb_start_response_json["oobStatusHandle"], } uaf_obb_status_request = json.dumps( uaf_obb_status_request_dictionary, separators=(',', ':')) print "UAF. Authenticate for step 2. Prepared STATUS request: '%s' to send to '%s'" % ( uaf_obb_status_request, uaf_obb_server_uri) uaf_status_obb_response = self.executePost( uaf_obb_server_uri, uaf_obb_status_request) if uaf_status_obb_response == None: return False print "UAF. Authenticate for step 2. Get STATUS response: '%s'" % uaf_status_obb_response uaf_status_obb_response_json = json.loads( uaf_status_obb_response) if uaf_status_obb_response_json["statusCode"] != 4000: print "UAF. Authenticate for step 2. UAF operation status is invalid. statusCode: '%s'" % uaf_status_obb_response_json[ "statusCode"] return False uaf_user_device_handle = uaf_status_obb_response_json[ "additionalInfo"]["authenticatorsResult"]["handle"] if StringHelper.isEmpty(uaf_user_device_handle): print "UAF. Prepare for step 2. Failed to get UAF handle" return False uaf_user_external_uid = "uaf:%s" % uaf_user_device_handle print "UAF. Authenticate for step 2. UAF handle: '%s'" % uaf_user_external_uid if uaf_auth_method == "authenticate": # Validate if user used device with same keYHandle user_enrollments = self.findEnrollments(credentials) if len(user_enrollments) == 0: uaf_auth_method = "enroll" print "UAF. Authenticate for step 2. There is no UAF enrollment for user '%s'." % user_name return False for user_enrollment in user_enrollments: if StringHelper.equalsIgnoreCase(user_enrollment, uaf_user_device_handle): print "UAF. Authenticate for step 2. There is UAF enrollment for user '%s'. User authenticated successfully" % user_name return True else: userService = CdiUtil.bean(UserService) # Double check just to make sure. We did checking in previous step # Check if there is user which has uaf_user_external_uid # Avoid mapping user cert to more than one IDP account find_user_by_external_uid = userService.getUserByAttribute( "oxExternalUid", uaf_user_external_uid) if find_user_by_external_uid == None: # Add uaf_user_external_uid to user's external GUID list find_user_by_external_uid = userService.addUserAttribute( user_name, "oxExternalUid", uaf_user_external_uid) if find_user_by_external_uid == None: print "UAF. Authenticate for step 2. Failed to update current user" return False return True return False else: return False