def init(self, customScript, configurationAttributes): print "Basic (lock account). Initialization" self.invalidLoginCountAttribute = "oxCountInvalidLogin" if configurationAttributes.containsKey("invalid_login_count_attribute"): self.invalidLoginCountAttribute = configurationAttributes.get("invalid_login_count_attribute").getValue2() else: print "Basic (lock account). Initialization. Using default attribute" self.maximumInvalidLoginAttemps = 3 if configurationAttributes.containsKey("maximum_invalid_login_attemps"): self.maximumInvalidLoginAttemps = StringHelper.toInteger(configurationAttributes.get("maximum_invalid_login_attemps").getValue2()) else: print "Basic (lock account). Initialization. Using default number attempts" self.lockExpirationTime = 180 if configurationAttributes.containsKey("lock_expiration_time"): self.lockExpirationTime = StringHelper.toInteger(configurationAttributes.get("lock_expiration_time").getValue2()) else: print "Basic (lock account). Initialization. Using default lock expiration time" print "Basic (lock account). Initialized successfully. invalid_login_count_attribute: '%s', maximum_invalid_login_attemps: '%s', lock_expiration_time: '%s'" % (self.invalidLoginCountAttribute, self.maximumInvalidLoginAttemps, self.lockExpirationTime) return True
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 authenticate_user_credentials(self, identity, authentication_service): credentials = identity.getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() print "ThumbSignIn. user_name: " + user_name logged_in = False if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password): logged_in = self.authenticate_user_in.jans.ldap(authentication_service, user_name, user_password) return logged_in
def getGeolocation(self, identity): session_attributes = identity.getSessionId().getSessionAttributes() if session_attributes.containsKey("remote_ip"): remote_ip = session_attributes.get("remote_ip") if StringHelper.isNotEmpty(remote_ip): httpService = CdiUtil.bean(HttpService) http_client = httpService.getHttpsClient() http_client_params = http_client.getParams() http_client_params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 4 * 1000) geolocation_service_url = "http://ip-api.com/json/%s?fields=country,city,status,message" % remote_ip geolocation_service_headers = { "Accept" : "application/json" } try: http_service_response = httpService.executeGet(http_client, geolocation_service_url, geolocation_service_headers) http_response = http_service_response.getHttpResponse() except: print "Casa. Determine remote location. Exception: ", sys.exc_info()[1] return None try: if not httpService.isResponseStastusCodeOk(http_response): print "Casa. Determine remote location. Get non 200 OK response from server:", str(http_response.getStatusLine().getStatusCode()) httpService.consume(http_response) return None response_bytes = httpService.getResponseContent(http_response) response_string = httpService.convertEntityToString(response_bytes, Charset.forName("UTF-8")) httpService.consume(http_response) finally: http_service_response.closeConnection() if response_string == None: print "Casa. Determine remote location. Get empty response from location server" return None response = json.loads(response_string) if not StringHelper.equalsIgnoreCase(response['status'], "success"): print "Casa. Determine remote location. Get response with status: '%s'" % response['status'] return None return response return None
def createNewAuthenticatedSession(self, context, customParameters={}): sessionIdService = CdiUtil.bean(SessionIdService) user = context.getUser() client = CdiUtil.bean(Identity).getSessionClient().getClient() # Add mandatory session parameters sessionAttributes = HashMap() sessionAttributes.put(Constants.AUTHENTICATED_USER, user.getUserId()) sessionAttributes.put(AuthorizeRequestParam.CLIENT_ID, client.getClientId()) sessionAttributes.put(AuthorizeRequestParam.PROMPT, "") # Add custom session parameters for key, value in customParameters.iteritems(): if StringHelper.isNotEmpty(value): sessionAttributes.put(key, value) # Generate authenticated session sessionId = sessionIdService.generateAuthenticatedSessionId( context.getHttpRequest(), user.getDn(), sessionAttributes) print "ROPC script. Generated session id. DN: '%s'" % sessionId.getDn() return sessionId
def getCountAuthenticationSteps(self, configurationAttributes): identity = CdiUtil.bean(Identity) if identity.isSetWorkingParameter("otp_count_login_steps"): return StringHelper.toInteger( "%s" % identity.getWorkingParameter("otp_count_login_steps")) else: return 2
def validateTotpKey(self, secretKey, totpKey, user_name): localTotpKey = self.generateTotpKey(secretKey) cachedOTP = self.getCachedOTP(user_name) if StringHelper.equals( localTotpKey, totpKey) and not StringHelper.equals(localTotpKey, cachedOTP): userService = CdiUtil.bean(UserService) if cachedOTP is None: userService.addUserAttribute(user_name, "oxOTPCache", localTotpKey) else: userService.replaceUserAttribute(user_name, "oxOTPCache", cachedOTP, localTotpKey) print "OTP. Caching OTP: '%s'" % localTotpKey return {"result": True} return {"result": False}
def init(self, customScript, configurationAttributes): print "User registration. Initialization" self.enable_user = StringHelper.toBoolean( configurationAttributes.get("enable_user").getValue2(), False) print "User registration. Initialized successfully" return True
def preRegistration(self, user, requestParameters, configurationAttributes): print "User Confirm registration. Pre method" userStatus = "inactive" # Disable/Enable registered user user.setStatus(userStatus) self.guid = StringHelper.getRandomString(16) user.setGuid(self.guid) return True
def loadOtpConfiguration(self, configurationAttributes): print "OTP. Load OTP configuration" if not configurationAttributes.containsKey("otp_conf_file"): return False otp_conf_file = configurationAttributes.get( "otp_conf_file").getValue2() # Load configuration from file f = open(otp_conf_file, 'r') try: otpConfiguration = json.loads(f.read()) except: print "OTP. Load OTP configuration. Failed to load configuration from file:", otp_conf_file return False finally: f.close() # Check configuration file settings try: self.hotpConfiguration = otpConfiguration["hotp"] self.totpConfiguration = otpConfiguration["totp"] hmacShaAlgorithm = self.totpConfiguration["hmacShaAlgorithm"] hmacShaAlgorithmType = None if StringHelper.equalsIgnoreCase(hmacShaAlgorithm, "sha1"): hmacShaAlgorithmType = HmacShaAlgorithm.HMAC_SHA_1 elif StringHelper.equalsIgnoreCase(hmacShaAlgorithm, "sha256"): hmacShaAlgorithmType = HmacShaAlgorithm.HMAC_SHA_256 elif StringHelper.equalsIgnoreCase(hmacShaAlgorithm, "sha512"): hmacShaAlgorithmType = HmacShaAlgorithm.HMAC_SHA_512 else: print "OTP. Load OTP configuration. Invalid TOTP HMAC SHA algorithm: '%s'" % hmacShaAlgorithm self.totpConfiguration[ "hmacShaAlgorithmType"] = hmacShaAlgorithmType except: print "OTP. Load OTP configuration. Invalid configuration file '%s' format. Exception: '%s'" % ( otp_conf_file, sys.exc_info()[1]) return False return True
def isUserMemberOfGroup(self, user, attribute, group): is_member = False member_of_list = user.getAttributeValues(attribute) if (member_of_list != None): for member_of in member_of_list: if StringHelper.equalsIgnoreCase( group, member_of) or member_of.endswith(group): is_member = True break return is_member
def updateUser(self, user, configurationAttributes): print "Cache refresh. UpdateUser method" attributes = user.getCustomAttributes() # Add new attribute preferredLanguage attrPrefferedLanguage = JanssenCustomAttribute("preferredLanguage", "en-us") attributes.add(attrPrefferedLanguage) # Add new attribute userPassword attrUserPassword = JanssenCustomAttribute("userPassword", "test") attributes.add(attrUserPassword) # Update givenName attribute for attribute in attributes: attrName = attribute.getName() if (("givenname" == StringHelper.toLowerCase(attrName)) and StringHelper.isNotEmpty(attribute.getValue())): attribute.setValue(StringHelper.removeMultipleSpaces(attribute.getValue()) + " (updated)") return True
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 processBasicAuthentication(self, credentials): userService = CdiUtil.bean(UserService) authenticationService = CdiUtil.bean(AuthenticationService) 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 None find_user_by_uid = authenticationService.getAuthenticatedUser() if (find_user_by_uid == None): print "Cert. Process basic authentication. Failed to find user '%s'" % user_name return None return find_user_by_uid
def authenticate(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) if (step == 1): print "Basic. Authenticate for step 1" identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): logged_in = authenticationService.authenticate(user_name, user_password) if (not logged_in): return False return True else: return False
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 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 init(self, customScript, configurationAttributes): print "UAF. Initialization" if not configurationAttributes.containsKey("uaf_server_uri"): print "UAF. Initialization. Property uaf_server_uri is mandatory" return False self.uaf_server_uri = configurationAttributes.get( "uaf_server_uri").getValue2() self.uaf_policy_name = "default" if configurationAttributes.containsKey("uaf_policy_name"): self.uaf_policy_name = configurationAttributes.get( "uaf_policy_name").getValue2() self.send_push_notifaction = False if configurationAttributes.containsKey("send_push_notifaction"): self.send_push_notifaction = StringHelper.toBoolean( configurationAttributes.get( "send_push_notifaction").getValue2(), False) self.registration_uri = None if configurationAttributes.containsKey("registration_uri"): self.registration_uri = configurationAttributes.get( "registration_uri").getValue2() self.customQrOptions = {} if configurationAttributes.containsKey("qr_options"): self.customQrOptions = configurationAttributes.get( "qr_options").getValue2() print "UAF. Initializing HTTP client" httpService = CdiUtil.bean(HttpService) self.http_client = httpService.getHttpsClient() http_client_params = self.http_client.getParams() http_client_params.setIntParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000) print "UAF. Initialized successfully. uaf_server_uri: '%s', uaf_policy_name: '%s', send_push_notifaction: '%s', registration_uri: '%s', qr_options: '%s'" % ( self.uaf_server_uri, self.uaf_policy_name, self.send_push_notifaction, self.registration_uri, self.customQrOptions) print "UAF. Initialized successfully" return True
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 init(self, customScript, configurationAttributes): print "Casa. init called" self.authenticators = {} self.uid_attr = self.getLocalPrimaryKey() custScriptService = CdiUtil.bean(CustomScriptService) self.scriptsList = custScriptService.findCustomScripts(Collections.singletonList(CustomScriptType.PERSON_AUTHENTICATION), "oxConfigurationProperty", "displayName", "oxEnabled", "oxLevel") dynamicMethods = self.computeMethods(self.scriptsList) if len(dynamicMethods) > 0: print "Casa. init. Loading scripts for dynamic modules: %s" % dynamicMethods for acr in dynamicMethods: moduleName = self.modulePrefix + acr try: external = __import__(moduleName, globals(), locals(), ["PersonAuthentication"], -1) module = external.PersonAuthentication(self.currentTimeMillis) print "Casa. init. Got dynamic module for acr %s" % acr configAttrs = self.getConfigurationAttributes(acr, self.scriptsList) if acr == self.ACR_U2F: u2f_application_id = configurationAttributes.get("u2f_app_id").getValue2() configAttrs.put("u2f_application_id", SimpleCustomProperty("u2f_application_id", u2f_application_id)) elif acr == self.ACR_SG: application_id = configurationAttributes.get("supe.jans.app_id").getValue2() configAttrs.put("application_id", SimpleCustomProperty("application_id", application_id)) if module.init(None, configAttrs): module.configAttrs = configAttrs self.authenticators[acr] = module else: print "Casa. init. Call to init in module '%s' returned False" % moduleName except: print "Casa. init. Failed to load module %s" % moduleName print "Exception: ", sys.exc_info()[1] mobile_methods = configurationAttributes.get("mobile_methods") self.mobile_methods = [] if mobile_methods == None else StringHelper.split(mobile_methods.getValue2(), ",") print "Casa. init. Initialized successfully" return True
def setClientScopes(self, client, requiredScopes): if requiredScopes == None: print "Casa client registration. No list of scopes was passed in script parameters" return requiredScopes = StringHelper.split(requiredScopes.getValue2(), ",") newScopes = client.getScopes() scopeService = CdiUtil.bean(ScopeService) for scopeName in requiredScopes: scope = scopeService.getScopeById(scopeName) if not scope.isDefaultScope(): print "Casa client registration. Adding scope '%s'" % scopeName newScopes = ArrayHelper.addItemToStringArray( newScopes, scope.getDn()) print "Casa client registration. Result scopes are: %s" % newScopes client.setScopes(newScopes)
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 authenticate(self, configurationAttributes, requestParameters, step): print "==============================================" print "====TWILIO SMS AUTHENCATION===================" print "==============================================" userService = CdiUtil.bean(UserService) authenticationService = CdiUtil.bean(AuthenticationService) sessionIdService = CdiUtil.bean(SessionIdService) facesMessages = CdiUtil.bean(FacesMessages) facesMessages.setKeepMessages() session_attributes = self.identity.getSessionId().getSessionAttributes() form_passcode = ServerUtil.getFirstValue(requestParameters, "passcode") form_name = ServerUtil.getFirstValue(requestParameters, "TwilioSmsloginForm") print "TwilioSMS. form_response_passcode: %s" % str(form_passcode) if step == 1: print "==============================================" print "=TWILIO SMS STEP 1 | Password Authentication==" print "==============================================" credentials = self.identity.getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() logged_in = False if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password): logged_in = authenticationService.authenticate(user_name, user_password) if not logged_in: return False # Get the Person's number and generate a code foundUser = None try: foundUser = authenticationService.getAuthenticatedUser() except: print 'TwilioSMS, Error retrieving user %s from LDAP' % (user_name) return False try: isVerified = foundUser.getAttribute("phoneNumberVerified") if isVerified: self.mobile_number = foundUser.getAttribute("employeeNumber") if self.mobile_number == None: self.mobile_number = foundUser.getAttribute("mobile") if self.mobile_number == None: self.mobile_number = foundUser.getAttribute("telephoneNumber") if self.mobile_number == None: print "TwilioSMS, Error finding mobile number for user '%s'" % user_name except: facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to determine mobile phone number") print 'TwilioSMS, Error finding mobile number for "%s". Exception: %s` % (user_name, sys.exc_info()[1])`' return False # Generate Random six digit code and store it in array code = random.randint(100000, 999999) # Get code and save it in LDAP temporarily with special session entry self.identity.setWorkingParameter("code", code) sessionId = sessionIdService.getSessionId() # fetch from persistence sessionId.getSessionAttributes().put("code", code) try: Twilio.init(self.ACCOUNT_SID, self.AUTH_TOKEN); message = Message.creator(PhoneNumber(self.mobile_number), PhoneNumber(self.FROM_NUMBER), str(code)).create(); print "++++++++++++++++++++++++++++++++++++++++++++++" print 'TwilioSMs, Message Sid: %s' % (message.getSid()) print 'TwilioSMs, User phone: %s' % (self.mobile_number) print "++++++++++++++++++++++++++++++++++++++++++++++" sessionId.getSessionAttributes().put("mobile_number", self.mobile_number) sessionId.getSessionAttributes().put("mobile", self.mobile_number) sessionIdService.updateSessionId(sessionId) self.identity.setWorkingParameter("mobile_number", self.mobile_number) self.identity.getSessionId().getSessionAttributes().put("mobile_number",self.mobile_number) self.identity.setWorkingParameter("mobile", self.mobile_number) self.identity.getSessionId().getSessionAttributes().put("mobile",self.mobile_number) print "++++++++++++++++++++++++++++++++++++++++++++++" print "Number: %s" % (self.identity.getWorkingParameter("mobile_number")) print "Mobile: %s" % (self.identity.getWorkingParameter("mobile")) print "++++++++++++++++++++++++++++++++++++++++++++++" print "========================================" print "===TWILIO SMS FIRST STEP DONE PROPERLY==" print "========================================" return True except Exception, ex: facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to send message to mobile phone") print "TwilioSMS. Error sending message to Twilio" print "TwilioSMS. Unexpected error:", ex return False
def authenticate(self, configurationAttributes, requestParameters, step): print "Casa. authenticate for step %s" % str(step) userService = CdiUtil.bean(UserService) authenticationService = CdiUtil.bean(AuthenticationService) identity = CdiUtil.bean(Identity) if step == 1: credentials = identity.getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password): foundUser = userService.getUserByAttribute(self.uid_attr, user_name) #foundUser = userService.getUser(user_name) if foundUser == None: print "Casa. authenticate for step 1. Unknown username" else: platform_data = self.parsePlatformData(requestParameters) mfaOff = foundUser.getAttribute("oxPreferredMethod") == None logged_in = False if mfaOff: logged_in = authenticationService.authenticate(user_name, user_password) else: acr = self.getSuitableAcr(foundUser, platform_data) if acr != None: module = self.authenticators[acr] logged_in = module.authenticate(module.configAttrs, requestParameters, step) if logged_in: foundUser = authenticationService.getAuthenticatedUser() if foundUser == None: print "Casa. authenticate for step 1. Cannot retrieve logged user" else: if mfaOff: identity.setWorkingParameter("skip2FA", True) else: #Determine whether to skip 2FA based on policy defined (global or user custom) skip2FA = self.determineSkip2FA(userService, identity, foundUser, platform_data) identity.setWorkingParameter("skip2FA", skip2FA) identity.setWorkingParameter("ACR", acr) return True else: print "Casa. authenticate for step 1 was not successful" return False else: user = authenticationService.getAuthenticatedUser() if user == None: print "Casa. authenticate for step 2. Cannot retrieve logged user" return False #see casa.xhtml alter = ServerUtil.getFirstValue(requestParameters, "alternativeMethod") if alter != None: #bypass the rest of this step if an alternative method was provided. Current step will be retried (see getNextStep) self.simulateFirstStep(requestParameters, alter) return True session_attributes = identity.getSessionId().getSessionAttributes() acr = session_attributes.get("ACR") #this working parameter is used in casa.xhtml identity.setWorkingParameter("methods", ArrayList(self.getAvailMethodsUser(user, acr))) success = False if acr in self.authenticators: module = self.authenticators[acr] success = module.authenticate(module.configAttrs, requestParameters, step) #Update the list of trusted devices if 2fa passed if success: print "Casa. authenticate. 2FA authentication was successful" tdi = session_attributes.get("trustedDevicesInfo") if tdi == None: print "Casa. authenticate. List of user's trusted devices was not updated" else: user.setAttribute("oxTrustedDevicesInfo", tdi) userService.updateUser(user) else: print "Casa. authenticate. 2FA authentication failed" return success return False
def init(self, customScript, configurationAttributes): print "Cert. Initialization" if not (configurationAttributes.containsKey("chain_cert_file_path")): print "Cert. Initialization. Property chain_cert_file_path is mandatory" return False if not (configurationAttributes.containsKey("map_user_cert")): print "Cert. Initialization. Property map_user_cert is mandatory" return False chain_cert_file_path = configurationAttributes.get( "chain_cert_file_path").getValue2() self.chain_certs = CertUtil.loadX509CertificateFromFile( chain_cert_file_path) if self.chain_certs == None: print "Cert. Initialization. Failed to load chain certificates from '%s'" % chain_cert_file_path return False print "Cert. Initialization. Loaded '%d' chain certificates" % self.chain_certs.size( ) crl_max_response_size = 5 * 1024 * 1024 # 10Mb if configurationAttributes.containsKey("crl_max_response_size"): crl_max_response_size = StringHelper.toInteger( configurationAttributes.get( "crl_max_response_size").getValue2(), crl_max_response_size) print "Cert. Initialization. CRL max response size is '%d'" % crl_max_response_size # Define array to order methods correctly self.validator_types = ['generic', 'path', 'ocsp', 'crl'] self.validators = { 'generic': [GenericCertificateVerifier(), False], 'path': [PathCertificateVerifier(False), False], 'ocsp': [OCSPCertificateVerifier(), False], 'crl': [CRLCertificateVerifier(crl_max_response_size), False] } for type in self.validator_types: validator_param_name = "use_%s_validator" % type if configurationAttributes.containsKey(validator_param_name): validator_status = StringHelper.toBoolean( configurationAttributes.get( validator_param_name).getValue2(), False) self.validators[type][1] = validator_status print "Cert. Initialization. Validation method '%s' status: '%s'" % ( type, self.validators[type][1]) self.map_user_cert = StringHelper.toBoolean( configurationAttributes.get("map_user_cert").getValue2(), False) print "Cert. Initialization. map_user_cert: '%s'" % self.map_user_cert self.enabled_recaptcha = self.initRecaptcha(configurationAttributes) print "Cert. Initialization. enabled_recaptcha: '%s'" % self.enabled_recaptcha print "Cert. Initialized successfully" return True
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() user_name = credentials.getUsername() if (step == 1): print "U2F. Authenticate for step 1" user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): userService = CdiUtil.bean(UserService) logged_in = authenticationService.authenticate(user_name, user_password) if (not logged_in): return False return True elif (step == 2): print "U2F. Authenticate for step 2" token_response = ServerUtil.getFirstValue(requestParameters, "tokenResponse") if token_response == None: print "U2F. Authenticate for step 2. tokenResponse is empty" return False auth_method = ServerUtil.getFirstValue(requestParameters, "authMethod") if auth_method == None: print "U2F. Authenticate for step 2. authMethod is empty" return False authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if (user == None): print "U2F. Prepare for step 2. Failed to determine user name" return False if (auth_method == 'authenticate'): print "U2F. Prepare for step 2. Call FIDO U2F in order to finish authentication workflow" authenticationRequestService = FidoU2fClientFactory.instance().createAuthenticationRequestService(self.metaDataConfiguration) authenticationStatus = authenticationRequestService.finishAuthentication(user.getUserId(), token_response) if (authenticationStatus.getStatus() != Constants.RESULT_SUCCESS): print "U2F. Authenticate for step 2. Get invalid authentication status from FIDO U2F server" return False return True elif (auth_method == 'enroll'): print "U2F. Prepare for step 2. Call FIDO U2F in order to finish registration workflow" registrationRequestService = FidoU2fClientFactory.instance().createRegistrationRequestService(self.metaDataConfiguration) registrationStatus = registrationRequestService.finishRegistration(user.getUserId(), token_response) if (registrationStatus.getStatus() != Constants.RESULT_SUCCESS): print "U2F. Authenticate for step 2. Get invalid registration status from FIDO U2F server" return False return True else: print "U2F. Prepare for step 2. Authenticatiod method is invalid" return False return False else: return False
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