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, "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) 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 prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) authenticationService = CdiUtil.bean(AuthenticationService) duo_host = configurationAttributes.get("duo_host").getValue2() if (step == 1): print "Duo. Prepare for step 1" return True elif (step == 2): print "Duo. Prepare for step 2" user = authenticationService.getAuthenticatedUser() if (user == None): print "Duo. Prepare for step 2. Failed to determine user name" return False user_name = user.getUserId() duo_sig_request = duo_web.sign_request(self.ikey, self.skey, self.akey, user_name) print "Duo. Prepare for step 2. duo_sig_request: " + duo_sig_request identity.setWorkingParameter("duo_host", duo_host) identity.setWorkingParameter("duo_sig_request", duo_sig_request) return True else: return False
def resend_push_notification(self,context): print "Super-Gluu-RO resend_push_notification" sessionIdService = CdiUtil.bean(SessionIdService) session_id = context.getHttpRequest().getParameter(self.sessionIdParamName) if session_id == None: print "Super-Gluu-RO. No session_id was specified for resend_push_notification" context.setUser(None) return False sessionId = sessionIdService.getSessionId(session_id) if sessionId == None: print "Super-Gluu-RO. Session '%s' does not exist or has expired" % session_id context.setUser(None) return False client = CdiUtil.bean(Identity).getSessionClient().getClient() if not self.verify_session_ownership(sessionId,context.getUser(),client): print "Super-Gluu-RO. resend_push_notification_failed due to invalid session ownership" context.setUser(None) return False self.send_push_notification_to_user(sessionId,context) print "Super-Gluu-RO resend_push_notification complete" return True
def sendPushNotificationImpl(self, user, app_id, super_gluu_request): if not self.pushNotificationsEnabled: print "Super-Gluu-Push. Push notifications are disabled" return None user_name = user.getUserId() print "Super-Gluu-Push. Sending push notification to user '%s' devices" % user_name userService = CdiUtil.bean(UserService) deviceRegistrationService = CdiUtil.bean(DeviceRegistrationService) user_inum = userService.getUserInum(user_name) u2f_device_list = deviceRegistrationService.findUserDeviceRegistrations(user_inum, app_id, "oxId","oxDeviceData","oxDeviceNotificationConf") send_ios = 0 send_android = 0 if u2f_device_list.size() > 0: for u2f_device in u2f_device_list: print "Super-Gluu-Push. Send device notification to device" device_push_result = self.sendDevicePushNotification(user, app_id, u2f_device, super_gluu_request) send_ios += device_push_result["send_ios"] send_android += device_push_result["send_android"] else: print "Super-Gluu-Push. No device enrolled for user '%s'" % user_name return 0 msg = """Super-Gluu-Push. Send push notification. send_android: '%s', send_ios: '%s' """ print msg % (send_android, send_ios) return send_android + send_ios
def getPassportRedirectUrl(self, provider): # provider is assumed to exist in self.registeredProviders url = None try: facesContext = CdiUtil.bean(FacesContext) tokenEndpoint = "https://%s/passport/token" % facesContext.getExternalContext().getRequest().getServerName() httpService = CdiUtil.bean(HttpService) httpclient = httpService.getHttpsClient() print "Passport. getPassportRedirectUrl. Obtaining token from passport at %s" % tokenEndpoint resultResponse = httpService.executeGet(httpclient, tokenEndpoint, Collections.singletonMap("Accept", "text/json")) httpResponse = resultResponse.getHttpResponse() bytes = httpService.getResponseContent(httpResponse) response = httpService.convertEntityToString(bytes) print "Passport. getPassportRedirectUrl. Response was %s" % httpResponse.getStatusLine().getStatusCode() tokenObj = json.loads(response) url = "/passport/auth/%s/%s" % (provider, tokenObj["token_"]) except: print "Passport. getPassportRedirectUrl. Error building redirect URL: ", sys.exc_info()[1] return url
def prepareForStep(self, configurationAttributes, requestParameters, step): print "Cert. Prepare for step %d" % step identity = CdiUtil.bean(Identity) if step == 1: if self.enabled_recaptcha: identity.setWorkingParameter("recaptcha_site_key", self.recaptcha_creds['site_key']) elif step == 2: # Store certificate in session facesContext = CdiUtil.bean(FacesContext) externalContext = facesContext.getExternalContext() request = externalContext.getRequest() # Try to get certificate from header X-ClientCert clientCertificate = externalContext.getRequestHeaderMap().get("X-ClientCert") if clientCertificate != None: x509Certificate = self.certFromPemString(clientCertificate) identity.setWorkingParameter("cert_x509", self.certToString(x509Certificate)) print "Cert. Prepare for step 2. Storing user certificate obtained from 'X-ClientCert' header" return True # Try to get certificate from attribute javax.servlet.request.X509Certificate x509Certificates = request.getAttribute('javax.servlet.request.X509Certificate') if (x509Certificates != None) and (len(x509Certificates) > 0): identity.setWorkingParameter("cert_x509", self.certToString(x509Certificates[0])) print "Cert. Prepare for step 2. Storing user certificate obtained from 'javax.servlet.request.X509Certificate' attribute" return True if step < 4: return True else: return False
def prepareForStep(self, configuration_attributes, request_parameters, step): print "ThumbSignIn. Inside prepareForStep. Step %d" % step identity = CdiUtil.bean(Identity) authentication_service = CdiUtil.bean(AuthenticationService) identity.setWorkingParameter("ts_host", ts_host) identity.setWorkingParameter("ts_statusPath", ts_statusPath) self.set_relying_party_login_url(identity) if step == 1 or step == 3: print "ThumbSignIn. Prepare for step 1" self.initialize_thumbsignin(identity, AUTHENTICATE) return True elif step == 2: print "ThumbSignIn. Prepare for step 2" if identity.isSetWorkingParameter(USER_LOGIN_FLOW): user_login_flow = identity.getWorkingParameter(USER_LOGIN_FLOW) print "ThumbSignIn. Value of user_login_flow is %s" % user_login_flow user = authentication_service.getAuthenticatedUser() if user is None: print "ThumbSignIn. Prepare for step 2. Failed to determine user name" return False user_name = user.getUserId() print "ThumbSignIn. Prepare for step 2. user_name: " + user_name if user_name is None: return False identity.setWorkingParameter(USER_ID, user_name) self.initialize_thumbsignin(identity, REGISTER + "/" + user_name) return True else: return False
def prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() self.setRequestScopedParameters(identity) if step == 1: print "OTP. Prepare for step 1" return True elif step == 2: print "OTP. Prepare for step 2" session_id_validation = self.validateSessionId(identity) if not session_id_validation: return False otp_auth_method = identity.getWorkingParameter("otp_auth_method") print "OTP. Prepare for step 2. otp_auth_method: '%s'" % otp_auth_method if otp_auth_method == 'enroll': authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if user == None: print "OTP. Prepare for step 2. Failed to load user enty" return False if self.otpType == "hotp": otp_secret_key = self.generateSecretHotpKey() otp_enrollment_request = self.generateHotpSecretKeyUri(otp_secret_key, self.otpIssuer, user.getAttribute("displayName")) elif self.otpType == "totp": otp_secret_key = self.generateSecretTotpKey() otp_enrollment_request = self.generateTotpSecretKeyUri(otp_secret_key, self.otpIssuer, user.getAttribute("displayName")) else: print "OTP. Prepare for step 2. Unknown OTP type: '%s'" % self.otpType return False print "OTP. Prepare for step 2. Prepared enrollment request for user: '******'" % user.getUserId() identity.setWorkingParameter("otp_secret_key", self.toBase64Url(otp_secret_key)) identity.setWorkingParameter("otp_enrollment_request", otp_enrollment_request) return True elif step == 3: print "OTP. Prepare for step 3" session_id_validation = self.validateSessionId(identity) if not session_id_validation: return False otp_auth_method = identity.getWorkingParameter("otp_auth_method") print "OTP. Prepare for step 3. otp_auth_method: '%s'" % otp_auth_method if otp_auth_method == 'enroll': return True return False
def __init__(self, appId, superGluuRequest): self.appId = appId self.superGluuRequest = superGluuRequest self.debugEnabled = False self.deviceRegistrationService = CdiUtil.bean(DeviceRegistrationService) self.pushSnsService = CdiUtil.bean(PushSnsService) self.user = None self.u2fDevice = None self.devicePlatform = None self.pushToken = None
def getNextStep(self, configurationAttributes, requestParameters, step): print "Casa. getNextStep called %s" % str(step) if step > 1: acr = ServerUtil.getFirstValue(requestParameters, "alternativeMethod") if acr != None: print "Casa. getNextStep. Use alternative method %s" % acr CdiUtil.bean(Identity).setWorkingParameter("ACR", acr) #retry step with different acr return 2 return -1
def authenticate(self, configuration_attributes, request_parameters, step): print "ThumbSignIn. Inside authenticate. Step %d" % step authentication_service = CdiUtil.bean(AuthenticationService) identity = CdiUtil.bean(Identity) identity.setWorkingParameter("ts_host", ts_host) identity.setWorkingParameter("ts_statusPath", ts_statusPath) if step == 1 or step == 3: print "ThumbSignIn. Authenticate for Step %d" % step login_flow = ServerUtil.getFirstValue(request_parameters, "login_flow") print "ThumbSignIn. Value of login_flow parameter is %s" % login_flow # Logic for ThumbSignIn Authentication Flow (Either step 1 or step 3) if login_flow == THUMBSIGNIN_AUTHENTICATION or login_flow == THUMBSIGNIN_LOGIN_POST_REGISTRATION: identity.setWorkingParameter(USER_LOGIN_FLOW, login_flow) print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(USER_LOGIN_FLOW) logged_in_status = authentication_service.authenticate(self.get_user_id_from_thumbsignin(request_parameters)) print "ThumbSignIn. logged_in status : %r" % logged_in_status return logged_in_status # Logic for traditional login flow (step 1) print "ThumbSignIn. User credentials login flow" identity.setWorkingParameter(USER_LOGIN_FLOW, THUMBSIGNIN_REGISTRATION) print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(USER_LOGIN_FLOW) logged_in = self.authenticate_user_credentials(identity, authentication_service) print "ThumbSignIn. Status of User Credentials based Authentication : %r" % logged_in # When the traditional login fails, reinitialize the ThumbSignIn data before sending error response to UI if not logged_in: self.initialize_thumbsignin(identity, AUTHENTICATE) return False print "ThumbSignIn. Authenticate successful for step %d" % step return True elif step == 2: print "ThumbSignIn. Registration flow (step 2)" self.verify_user_login_flow(identity) user = self.get_authenticated_user_from_gluu(authentication_service) if user is None: print "ThumbSignIn. Registration flow (step 2). Failed to determine user name" return False user_name = user.getUserId() print "ThumbSignIn. Registration flow (step 2) successful. user_name: %s" % user_name return True else: return False
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 initiate_authentication(self, context): print "Super-Gluu-RO initiatate_authentication" client = CdiUtil.bean(Identity).getSessionClient().getClient() sessionId = self.new_unauthenticated_session(context.getUser(),client) # set session id in identity object # this will be used by our dynamic scope script identity = CdiUtil.bean(Identity) identity.setSessionId(sessionId) if not self.send_push_notification_to_user(sessionId,context): context.setUser(None) print "Send push notification to user '%s' failed " % context.getUser().getUserId() return False print "Super-Gluu-RO initiate_authentication complete" return True
def getCountAuthenticationSteps(self, configurationAttributes): print "Casa. getCountAuthenticationSteps called" if CdiUtil.bean(Identity).getWorkingParameter("skip2FA"): return 1 acr = CdiUtil.bean(Identity).getWorkingParameter("ACR") if acr in self.authenticators: module = self.authenticators[acr] return module.getCountAuthenticationSteps(module.configAttrs) else: return 2 print "Casa. getCountAuthenticationSteps. Could not determine the step count for acr %s" % acr
def prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) if (step == 1): return True elif (step == 2): print "U2F. Prepare for step 2" session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie() if StringHelper.isEmpty(session_id): print "U2F. Prepare for step 2. Failed to determine session_id" return False authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if (user == None): print "U2F. Prepare for step 2. Failed to determine user name" return False u2f_application_id = configurationAttributes.get("u2f_application_id").getValue2() # Check if user have registered devices deviceRegistrationService = CdiUtil.bean(DeviceRegistrationService) userInum = user.getAttribute("inum") registrationRequest = None authenticationRequest = None deviceRegistrations = deviceRegistrationService.findUserDeviceRegistrations(userInum, u2f_application_id) if (deviceRegistrations.size() > 0): print "U2F. Prepare for step 2. Call FIDO U2F in order to start authentication workflow" try: authenticationRequestService = FidoU2fClientFactory.instance().createAuthenticationRequestService(self.metaDataConfiguration) authenticationRequest = authenticationRequestService.startAuthentication(user.getUserId(), None, u2f_application_id, session_id) except ClientResponseFailure, ex: if (ex.getResponse().getResponseStatus() != Response.Status.NOT_FOUND): print "U2F. Prepare for step 2. Failed to start authentication workflow. Exception:", sys.exc_info()[1] return False else: print "U2F. Prepare for step 2. Call FIDO U2F in order to start registration workflow" registrationRequestService = FidoU2fClientFactory.instance().createRegistrationRequestService(self.metaDataConfiguration) registrationRequest = registrationRequestService.startRegistration(user.getUserId(), u2f_application_id, session_id) identity.setWorkingParameter("fido_u2f_authentication_request", ServerUtil.asJson(authenticationRequest)) identity.setWorkingParameter("fido_u2f_registration_request", ServerUtil.asJson(registrationRequest)) return True
def postRegistration(self, user, requestParameters, configurationAttributes): print "User registration. Post method" appConfiguration = CdiUtil.bean(AppConfiguration) hostName = appConfiguration.getApplianceUrl() externalContext = CdiUtil.bean(ExternalContext) contextPath = externalContext.getRequest().getContextPath() mailService = CdiUtil.bean(MailService) subject = "Confirmation mail for user registration" body = "User Registered for %s. Please Confirm User Registration by clicking url: %s%s/confirm/registration?code=%s" % (user.getMail(), hostName, contextPath, self.guid) print "User registration. Post method. Attempting to send e-mail to '%s' message '%s'" % (user.getMail(), body) mailService.sendMail(user.getMail(), subject, body) return True
def findEnrollments(self, user_name, skipPrefix = True): result = [] userService = CdiUtil.bean(UserService) user = userService.getUser(user_name, "oxExternalUid") if user == None: print "OTP. Find enrollments. Failed to find user" return result user_custom_ext_attribute = userService.getCustomAttribute(user, "oxExternalUid") if user_custom_ext_attribute == None: return result otp_prefix = "%s:" % self.otpType otp_prefix_length = len(otp_prefix) for user_external_uid in user_custom_ext_attribute.getValues(): index = user_external_uid.find(otp_prefix) if index != -1: if skipPrefix: enrollment_uid = user_external_uid[otp_prefix_length:] else: enrollment_uid = user_external_uid result.append(enrollment_uid) return result
def init(self, 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 getNotifyMetadata(self, gluu_server_uri): try: notifyClientFactory = NotifyClientFactory.instance() metadataConfigurationService = notifyClientFactory.createMetaDataConfigurationService(gluu_server_uri) return metadataConfigurationService.getMetadataConfiguration() except: exc_value = sys.exc_info()[1] print "Super-Gluu-Push. Gluu push notification init failed while loading metadata. %s." % exc_value print "Super-Gluu-Push. Retrying loading metadata using httpService..." httpService = CdiUtil.bean(HttpService) http_client = httpService.getHttpsClient() http_client_params = http_client.getParams() http_client_params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,self.httpConnTimeout) notify_service_url = "%s/.well-known/notify-configuration" % gluu_server_uri notify_service_headers = {"Accept": "application/json"} try: http_service_response = httpService.executeGet(http_client,notify_service_url,notify_service_headers) http_response = http_service_response.getHttpResponse() except: print "Super-Gluu-Push. Loading metadata using httpService failed. %s." % sys.exc_info()[1] return None try: if not httpService.isResponseStastusCodeOk(http_response): http_error_str = str(http_response.getStatusLine().getStatusCode()) print "Super-Gluu-Push. Loading metadata using httpService failed with http code %s." % http_error_str httpService.consume(http_response) return None resp_bytes = httpService.getResponseContent(http_response) resp_str = httpService.convertEntityToString(resp_bytes) httpService.consume(http_response) except: print "Super-Gluu-Push. Loading metadata using httpService failed. %s." % sys.exc_info()[1] return None finally: http_service_response.closeConnection() if resp_str == None: print "Super-Gluu-Push. Loading metadata using httpService failed.Empty response from server" return None json_resp = json.loads(resp_str) if ('version' not in json_resp) or ('issuer' not in json_resp): print "Super-Gluu-Push. Loading metadata using httpService failed. Invalid json response %s." % json_resp return None if ('notify_endpoint' not in json_resp) and ('notifyEndpoint' not in json_resp): print "Super-Gluu-Push. Loading metadata using httpService failed. Invalid json response %s." % json_resp return None notifyMeta = NotifyMetadata() notifyMeta.setVersion(json_resp['version']) notifyMeta.setIssuer(json_resp['issuer']) if 'notify_endpoint' in json_resp: notifyMeta.setNotifyEndpoint(json_resp['notify_endpoint']) elif 'notifyEndpoint' in json_resp: notifyMeta.setNotifyEndpoint(json_resp['notifyEndpoint']) print "Super-Gluu-Push. Metadata loaded using httpService successfully" return notifyMeta
def executePost(self, request_uri, request_data): httpService = CdiUtil.bean(HttpService) request_headers = { "Content-type" : "application/json; charset=UTF-8", "Accept" : "application/json" } try: http_service_response = httpService.executePost(self.http_client, request_uri, None, request_headers, request_data) http_response = http_service_response.getHttpResponse() except: print "UAF. Validate POST response. Exception: ", sys.exc_info()[1] return None try: if not httpService.isResponseStastusCodeOk(http_response): print "UAF. Validate POST response. Get invalid response from server: %s" % str(http_response.getStatusLine().getStatusCode()) httpService.consume(http_response) return None response_bytes = httpService.getResponseContent(http_response) response_string = httpService.convertEntityToString(response_bytes) httpService.consume(http_response) return response_string finally: http_service_response.closeConnection() return None
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 confirmRegistration(self, user, requestParameters, configurationAttributes): print "User registration. Confirm method" code_array = requestParameters.get("code") if ArrayHelper.isEmpty(code_array): print "User registration. Confirm method. code is empty" return False confirmation_code = code_array[0] print "User registration. Confirm method. code: '%s'" % confirmation_code if confirmation_code == None: print "User registration. Confirm method. Confirmation code not exist in request" return False personService = CdiUtil.bean(PersonService) user = personService.getPersonByAttribute("oxGuid", confirmation_code) if user == None: print "User registration. Confirm method. There is no user by confirmation code: '%s'" % confirmation_code return False if confirmation_code == user.getGuid(): user.setStatus(GluuStatus.ACTIVE) user.setGuid("") personService.updatePerson(user) print "User registration. Confirm method. User '%s' confirmed his registration" % user.getUid() return True print "User registration. Confirm method. Confirmation code for user '%s' is invalid" % user.getUid() return False
def prepareForStep(self, configurationAttributes, requestParameters, step): extensionResult = self.extensionPrepareForStep(configurationAttributes, requestParameters, step) if extensionResult != None: return extensionResult print "Passport. prepareForStep called %s" % str(step) identity = CdiUtil.bean(Identity) if step == 1: #re-read the strategies config (for instance to know which strategies have enabled the email account linking) self.parseProviderConfigs() identity.setWorkingParameter("externalProviders", json.dumps(self.registeredProviders)) providerParam = self.customAuthzParameter url = None sessionAttributes = identity.getSessionId().getSessionAttributes() self.skipProfileUpdate = StringHelper.equalsIgnoreCase(sessionAttributes.get("skipPassportProfileUpdate"), "true") #this param could have been set previously in authenticate step if current step is being retried provider = identity.getWorkingParameter("selectedProvider") if provider != None: url = self.getPassportRedirectUrl(provider) identity.setWorkingParameter("selectedProvider", None) elif providerParam != None: paramValue = sessionAttributes.get(providerParam) if paramValue != None: print "Passport. prepareForStep. Found value in custom param of authorization request: %s" % paramValue provider = self.getProviderFromJson(paramValue) if provider == None: print "Passport. prepareForStep. A provider value could not be extracted from custom authorization request parameter" elif not provider in self.registeredProviders: print "Passport. prepareForStep. Provider '%s' not part of known configured IDPs/OPs" % provider else: url = self.getPassportRedirectUrl(provider) if url == None: print "Passport. prepareForStep. A page to manually select an identity provider will be shown" else: facesService = CdiUtil.bean(FacesService) facesService.redirectToExternalURL(url) return True
def postRegistration(self, user, requestParameters, configurationAttributes): print "User registration. Post method" appConfiguration = CdiUtil.bean(AppConfiguration) hostName = appConfiguration.getApplianceUrl() externalContext = CdiUtil.bean(ExternalContext) contextPath = externalContext.getRequest().getContextPath() mailService = CdiUtil.bean(MailService) subject = "Registration confirmation" activationLink = "%s%s/confirm/registration?code=%s" %(hostName, contextPath, self.guid) body = "<h2 style='margin-left:10%%;color: #337ab7;'>Welcome</h2><hr style='width:80%%;border: 1px solid #337ab7;'></hr><div style='text-align:center;'><p>Dear <span style='color: #337ab7;'>%s</span>,</p><p>Your Account has been created, welcome to <span style='color: #337ab7;'>%s</span>.</p><p>You are just one step way from activating your account on <span style='color: #337ab7;'>%s</span>.</p><p>Click the button and start using your account.</p></div><a class='btn' href='%s'><button style='background: #337ab7; color: white; margin-left: 30%%; border-radius: 5px; border: 0px; padding: 5px;' type='button'>Activate your account now!</button></a>" % (user.getUid(), hostName, hostName, activationLink) print "User registration. Post method. Attempting to send e-mail to '%s' message '%s'" % (user.getMail(), body) mailService.sendMail(user.getMail(), None, subject, body, body); return True
def getNextStep(self, configurationAttributes, requestParameters, step): if step == 1: identity = CdiUtil.bean(Identity) provider = identity.getWorkingParameter("selectedProvider") if provider != None: return 1 return -1
def getLocalPrimaryKey(self): #Pick (one) attribute where user id is stored (e.g. uid/mail) oxAuthInitializer = CdiUtil.bean(AppInitializer) #This call does not create anything, it's like a getter (see oxAuth's AppInitializer) ldapAuthConfigs = oxAuthInitializer.createPersistenceAuthConfigs() uid_attr = ldapAuthConfigs.get(0).getLocalPrimaryKey() print "Casa. init. uid attribute is '%s'" % uid_attr return uid_attr
def validateRecaptcha(self, recaptcha_response): print "Cert. Validate recaptcha response" facesContext = CdiUtil.bean(FacesContext) request = facesContext.getExternalContext().getRequest() remoteip = ServerUtil.getIpAddress(request) print "Cert. Validate recaptcha response. remoteip: '%s'" % remoteip httpService = CdiUtil.bean(HttpService) http_client = httpService.getHttpsClient() http_client_params = http_client.getParams() http_client_params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000) recaptcha_validation_url = "https://www.google.com/recaptcha/api/siteverify" recaptcha_validation_request = urllib.urlencode({ "secret" : self.recaptcha_creds['secret_key'], "response" : recaptcha_response, "remoteip" : remoteip }) recaptcha_validation_headers = { "Content-type" : "application/x-www-form-urlencoded", "Accept" : "application/json" } try: http_service_response = httpService.executePost(http_client, recaptcha_validation_url, None, recaptcha_validation_headers, recaptcha_validation_request) http_response = http_service_response.getHttpResponse() except: print "Cert. Validate recaptcha response. Exception: ", sys.exc_info()[1] return False try: if not httpService.isResponseStastusCodeOk(http_response): print "Cert. Validate recaptcha response. Get invalid response from validation server: ", str(http_response.getStatusLine().getStatusCode()) httpService.consume(http_response) return False response_bytes = httpService.getResponseContent(http_response) response_string = httpService.convertEntityToString(response_bytes) httpService.consume(http_response) finally: http_service_response.closeConnection() if response_string == None: print "Cert. Validate recaptcha response. Get empty response from validation server" return False response = json.loads(response_string) return response["success"]
def initSnsPushNotifications(self, creds): print "Super-Gluu-Push. SNS push notifications init ..." self.pushSnsMode = True try: sns_creds = creds["sns"] android_creds = creds["android"]["sns"] ios_creds = creds["ios"]["sns"] except: print "Super-Gluu-Push. Invalid SNS credentials format" return None self.pushAndroidService = None self.pushAppleService = None if not (android_creds["enabled"] or ios_creds["enabled"]): print "Super-Gluu-Push. SNS disabled for all platforms" return None sns_access_key = sns_creds["access_key"] sns_secret_access_key = sns_creds["secret_access_key"] sns_region = sns_creds["region"] encryptionService = CdiUtil.bean(EncryptionService) try: sns_secret_access_key = encryptionService.decrypt(sns_secret_access_key) except: # Ignore exception. Password is not encrypted print "Super-Gluu-Push. Assuming 'sns_access_key' is not encrypted" pushSnsService = CdiUtil.bean(PushSnsService) pushClient = pushSnsService.createSnsClient(sns_access_key,sns_secret_access_key,sns_region) if android_creds["enabled"]: self.pushAndroidService = pushClient self.pushAndroidPlatformArn = android_creds["platform_arn"] print "Super-Gluu-Push. Created SNS android notification service" if ios_creds["enabled"]: self.pushAppleService = pushClient self.pushApplePlatformArn = ios_creds["platform_arn"] self.pushAppleServiceProduction = ios_creds["production"] self.pushNotificationsEnabled = self.pushAndroidService != None or self.pushAppleService != None
def new_unauthenticated_session(self,user,client): sessionIdService = CdiUtil.bean(SessionIdService) authDate = Date() sid_attrs = HashMap() sid_attrs.put(Constants.AUTHENTICATED_USER,user.getUserId()) sid_attrs.put(self.clientIdSessionParamName,client.getClientId()) sessionId = sessionIdService.generateUnauthenticatedSessionId(user.getDn(),authDate,SessionIdState.UNAUTHENTICATED,sid_attrs,True) print "Super-Gluu-RO. Generated session id. DN: '%s'" % sessionId.getDn() return sessionId
def initGluuPushNotifications(self, creds): print "Super-Gluu-Push. Gluu push notifications init ... " self.pushGluuMode = True try: gluu_conf = creds["gluu"] android_creds = creds["android"]["gluu"] ios_creds = creds["ios"]["gluu"] except: print "Super-Gluu-Push. Invalid Gluu credentials format" return None self.pushAndroidService = None self.pushAppleService = None if not(android_creds["enabled"] or ios_creds["enabled"]): print "Super-Gluu-Push. Gluu disabled for all platforms" return None gluu_server_uri = gluu_conf["server_uri"] notifyClientFactory = NotifyClientFactory.instance() metadataConfiguration = self.getNotifyMetadata(gluu_server_uri) if metadataConfiguration == None: return None gluuClient = notifyClientFactory.createNotifyService(metadataConfiguration) encryptionService = CdiUtil.bean(EncryptionService) if android_creds["enabled"]: gluu_access_key = android_creds["access_key"] gluu_secret_access_key = android_creds["secret_access_key"] try: gluu_secret_access_key = encryptionService.decrypt(gluu_secret_access_key) except: # Ignore exception. Password is not encrypted print "Super-Gluu-Push. Assuming 'gluu_secret_access_key' is not encrypted" self.pushAndroidService = gluuClient self.pushAndroidServiceAuth = notifyClientFactory.getAuthorization(gluu_access_key,gluu_secret_access_key) print "Super-Gluu-Push. Created Gluu Android notification service" if ios_creds["enabled"]: gluu_access_key = ios_creds["access_key"] gluu_secret_access_key = ios_creds["secret_access_key"] try: gluu_secret_access_key = encryptionService.decrypt(gluu_secret_access_key) except: # Ignore exception. Password is not encrypted print "Super-Gluu-Push. Assuming 'gluu_secret_access_key' is not encrypted" self.pushAppleService = gluuClient self.pushAppleServiceAuth = notifyClientFactory.getAuthorization(gluu_access_key,gluu_secret_access_key) print "Super-Gluu-Push. Created Gluu iOS notification service" self.pushNotificationsEnabled = self.pushAndroidService != None or self.pushAppleService != None
def prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) authenticationService = CdiUtil.bean(AuthenticationService) if (step == 1): print "Google+ Prepare for step 1" currentClientSecrets = self.getCurrentClientSecrets(self.clientSecrets, configurationAttributes, requestParameters) if (currentClientSecrets == None): print "Google+ Prepare for step 1. Google+ client configuration is invalid" return False identity.setWorkingParameter("gplus_client_id", currentClientSecrets["web"]["client_id"]) identity.setWorkingParameter("gplus_client_secret", currentClientSecrets["web"]["client_secret"]) return True elif (step == 2): print "Google+ Prepare for step 2" return True else: return False
def perform_preliminary_user_authentication(self, context): username = context.getHttpRequest().getParameter( self.usernameParamName) if self.authWithoutPassword: userService = CdiUtil.bean(UserService) user = userService.getUser(username, "uid") if user == None: print "Super-Gluu-RO. User '%s' not found" % username return False context.setUser(user) print "Super-Gluu-RO. User '%s' authenticated without password" % username return True password = context.getHttpRequest().getParameter( self.passwordParamName) authService = CdiUtil.bean(AuthenticationService) if authService.authenticate(username, password) == False: print "Super-Gluu-RO. Could not authenticate user '%s' " % username return False context.setUser(authService.getAuthenticatedUser()) return True
def startSession(self, httpRequest, sessionId, configurationAttributes): print "Application session. Starting external session" user_name = sessionId.getSessionAttributes().get(Constants.AUTHENTICATED_USER) first_session = self.isFirstSession(user_name) if not first_session: facesMessages = CdiUtil.bean(FacesMessages) facesMessages.add(FacesMessage.SEVERITY_ERROR, "Please, end active session first!") return False print "Application session. External session started successfully" return True
def authenticate(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) session_attributes = identity.getSessionId().getSessionAttributes() authenticationService = CdiUtil.bean(AuthenticationService) allowedCountriesListArray = StringHelper.split(self.allowedCountries, ",") if (len(allowedCountriesListArray) > 0 and session_attributes.containsKey("remote_ip")): remote_ip = session_attributes.get("remote_ip") remote_loc_dic = self.determineGeolocationData(remote_ip) if remote_loc_dic == None: print "Super-Gluu. Prepare for step 2. Failed to determine remote location by remote IP '%s'" % remote_ip return remote_loc = "%s" % (remote_loc_dic['countryCode']) print "Your remote location is " + remote_loc if remote_loc in allowedCountriesListArray: print "you are allowed to access" else: return False 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 getPageForStep(self, configurationAttributes, step): # Get the locale/language from the browser locale = CdiUtil.bean(LanguageBean).getLocaleCode()[:2] print "MFA Chooser. getPageForStep called for step '%s' and locale '%s'" % ( step, locale) # Make sure it matches "en" or "fr" if (locale != "en" and locale != "fr"): locale = "en" # determine what page to display if locale == "en": return "/en/register/new.xhtml" if locale == "fr": return "/fr/enregistrer/nouveau.xhtml"
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 prepareForStep(self, configurationAttributes, requestParameters, step): print "Cert. Prepare for step %d" % step identity = CdiUtil.bean(Identity) if step == 1: if self.enabled_recaptcha: identity.setWorkingParameter("recaptcha_site_key", self.recaptcha_creds['site_key']) return True elif step == 2: # Store certificate in session facesContext = CdiUtil.bean(FacesContext) externalContext = facesContext.getExternalContext() request = externalContext.getRequest() # Try to get certificate from header X-ClientCert clientCertificate = externalContext.getRequestHeaderMap().get( "X-ClientCert") if clientCertificate != None: x509Certificate = self.certFromPemString(clientCertificate) identity.setWorkingParameter( "cert_x509", self.certToString(x509Certificate)) print "Cert. Prepare for step 2. Storing user certificate obtained from 'X-ClientCert' header" return True # Try to get certificate from attribute javax.servlet.request.X509Certificate x509Certificates = request.getAttribute( 'javax.servlet.request.X509Certificate') if (x509Certificates != None) and (len(x509Certificates) > 0): identity.setWorkingParameter( "cert_x509", self.certToString(x509Certificates[0])) print "Cert. Prepare for step 2. Storing user certificate obtained from 'javax.servlet.request.X509Certificate' attribute" return True if step < 4: return True else: return False
def authenticate(self, configurationAttributes, requestParameters, step): print "MFA Enroll Recovery. authenticate called for step '%s'" % step # if it's the confirmation page then just get on with it and finish if (step == 2): return True identity = CdiUtil.bean(Identity) # For authentication then check if someone enrolling clicked CANCEL button alternateAction = self.alternateActionRequested(requestParameters) if ( alternateAction == 'cancel'): identity.getSessionId().getSessionAttributes().put("authenticationFlow", "RESTART_ENROLLMENT") CdiUtil.bean(SessionIdService).updateSessionId( identity.getSessionId() ) return True ######################################################################################## # 1. Make sure we have a session and a user with no existing codes in the profile session_id_validation = self.validateSessionId(identity) if not session_id_validation: print "MFA Enroll Recovery. prepareForStep for step %s. Failed to validate session state" % step return False authenticationService = CdiUtil.bean(AuthenticationService) authenticated_user = authenticationService.getAuthenticatedUser() if authenticated_user == None: print "MFA Enroll Recovery. prepareForStep. Failed to determine authenticated user from previous module" return False ######################################################################################## # 2. Get the confirmation checkbox value confirmCodeBox = None try: toBeFeatched = "loginForm:confirmCodeBox" print "MFA Enroll Recovery. authenticate: fetching '%s'" % toBeFeatched confirmCodeBox = ServerUtil.getFirstValue(requestParameters, toBeFeatched) except Exception, err: print("MFA Enroll Recovery. authenticate Exception getting form checkbox: " + str(err))
def getPassportRedirectUrl(self, provider, issuerSpNameQualifier): # provider is assumed to exist in self.registeredProviders url = None try: facesContext = CdiUtil.bean(FacesContext) tokenEndpoint = "https://%s/passport/token" % facesContext.getExternalContext().getRequest().getServerName() httpService = CdiUtil.bean(HttpService) httpclient = httpService.getHttpsClient() print "Passport-saml. getPassportRedirectUrl. Obtaining token from passport at %s" % tokenEndpoint resultResponse = httpService.executeGet(httpclient, tokenEndpoint, Collections.singletonMap("Accept", "text/json")) httpResponse = resultResponse.getHttpResponse() bytes = httpService.getResponseContent(httpResponse) response = httpService.convertEntityToString(bytes) print "Passport-saml. getPassportRedirectUrl. Response was %s" % httpResponse.getStatusLine().getStatusCode() print "Passport-saml. getPassportRedirectUrl. Loading response %s" % response tokenObj = json.loads(response) print "Passport-saml. getPassportRedirectUrl. Building URL: provider: %s" % provider print "Passport-saml. getPassportRedirectUrl. Building URL: token: %s" % tokenObj["token_"] print "Passport-saml. getPassportRedirectUrl. Building URL: spNameQfr: %s" % issuerSpNameQualifier locale = CdiUtil.bean(LanguageBean).getLocaleCode()[:2] if (locale != "en" and locale != "fr"): locale = "en" # Check if the samlissuer is there so to use the old endpoint if no collection needed if ( issuerSpNameQualifier != None ): url = "/passport/auth/%s/%s/locale/%s/saml/%s" % (provider, tokenObj["token_"], locale, Base64Util.base64urlencode(issuerSpNameQualifier)) else: url = "/passport/auth/%s/%s/locale/%s" % ( provider, tokenObj["token_"], locale ) except: print "Passport-saml. getPassportRedirectUrl. Error building redirect URL: ", sys.exc_info()[1] return url
def getUser(self, pairwiseId): print "MFA. getUser() called" userService = CdiUtil.bean(UserService) clientService = CdiUtil.bean(ClientService) pairwiseIdentifierService = CdiUtil.bean(PairwiseIdentifierService) facesResources = CdiUtil.bean(FacesResources) # Get the user service and fetch the user # Normally we would fetch by pairwise ID ... however because there is no API for that we save MFA PAI in oxExternalUid externalUid = "sic-mfa:" + pairwiseId print "MFA: getUser(). Looking up user with externalUid = '%s'" % externalUid user = userService.getUserByAttribute("oxExternalUid", externalUid) if (user is None): # Create a new account print "MFA: getUser(). Creating new user with externalUid = '%s'" % (externalUid) newUser = User() userId = uuid.uuid4().hex newUser.setUserId(userId) newUser.setAttribute("oxExternalUid", externalUid) user = userService.addUser(newUser, True) # add a Pairwise Subject Identifier for the OIDC Client facesContext = facesResources.getFacesContext() httpRequest = facesContext.getCurrentInstance().getExternalContext().getRequest() clientId = httpRequest.getParameter("client_id") client = clientService.getClient(clientId) sectorIdentifierUri = client.getRedirectUris()[0] userInum = user.getAttribute("inum") pairwiseSubject = PairwiseIdentifier(sectorIdentifierUri, clientId) pairwiseSubject.setId(pairwiseId) pairwiseSubject.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier(pairwiseSubject.getId(), userInum)) pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseSubject) return user
def getNextStep(self, configurationAttributes, requestParameters, step): print "Basic (demo reset step). Get next step for step '%s'" % step identity = CdiUtil.bean(Identity) # If user not pass current step authenticaton change step to previous pass_authentication = identity.getWorkingParameter( "pass_authentication") if not pass_authentication: if step > 1: resultStep = step - 1 print "Basic (demo reset step). Get next step. Changing step to '%s'" % resultStep return resultStep return -1
def isValidAuthenticationMethod(self, usageType, configurationAttributes): print "MFA Recovery. isValidAuthenticationMethod called" identity = CdiUtil.bean(Identity) # check if cancel was requested and go back to original validator authenticationFlow = identity.getSessionId().getSessionAttributes( ).get("authenticationFlow") if (authenticationFlow == "MFA_VALIDATION"): return False # check if the flow has completed successfully if (identity.getWorkingParameter("user_code_success")): print "MFA Recovery. isValidAuthenticationMethod return False, recovery complete" return False return True
def deleteTOTP(self, username, identity): # Inject dependencies userService = CdiUtil.bean(UserService) user = userService.getUser(username, "oxExternalUid") if (user is None): print "MFA. authenticateTOTP. Failed to find user" identity.setWorkingParameter("flow", "Error") # Error page else: externalUids = userService.getCustomAttribute(user, "oxExternalUid") if (externalUids is not None): for externalUid in externalUids.getValues(): if (externalUid.startswith("totp:")): userService.removeUserAttribute(username, "oxExternalUid", externalUid)
def isValidAuthenticationMethod(self, usageType, configurationAttributes): print "SPNEGO. isValidAuthenticationMethod()" identity = CdiUtil.bean(Identity) spnego_fatal_error = identity.getWorkingParameter('spnego_fatal_error') if spnego_fatal_error is True and self.alternativeAcr is not None: print "SPNEGO. Invalid authentication method" return False if (self.parseSpnegoAlternateAcr() is not None) and (self.alternativeAcr is not None): print "SPNEGO. Invalid authentication method. Determined from request params" return False print "SPNEGO. This is a valid authentication method" return True
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 getAlternativeAuthenticationMethod(self, usageType, configurationAttributes): print "SPNEGO. getAlternativeAuthenticationMethod()" identity = CdiUtil.bean(Identity) spnego_fatal_error = identity.getWorkingParameter('spnego_fatal_error') if spnego_fatal_error is True and self.alternativeAcr is not None: print "SPNEGO. Alternative acr %s" % (self.alternativeAcr) return self.alternativeAcr if (self.parseSpnegoAlternateAcr() is not None) and (self.alternativeAcr is not None): print "SPNEGO. Alternative acr from query string %s" % (self.alternativeAcr) return self.alternativeAcr print "SPNEGO. No alternative acr" return None
def init(self, configurationAttributes): print "Super-Gluu-RO Init" if not configurationAttributes.containsKey("application_id"): print "Super-Gluu-Radius RO PW Init Failed. application_id property is required" return False if not configurationAttributes.containsKey("credentials_file"): print "Super-Gluu-RO Init Failed. credentials_file is required" return False notificationServiceMode = None if configurationAttributes.containsKey("notification_service_mode"): notificationServiceMode = configurationAttributes.get( "notification_service_mode").getValue2() self.applicationId = "*" # wildcard. Selects all devices irrespective of the application if configurationAttributes.containsKey("application_id"): self.applicationId = configurationAttributes.get( "application_id").getValue2() credentialsFile = configurationAttributes.get( "credentials_file").getValue2() if configurationAttributes.containsKey("push_notification_title"): self.pushNotificationManager.titleTemplate = configurationAttributes.get( "push_notification_title").getValue2() if configurationAttributes.containsKey("push_notification_message"): self.pushNotificationManager.messageTemplate = configurationAttributes.get( "push_notification_message").getValue2() self.authWithoutPassword = False if configurationAttributes.containsKey("auth_without_password"): auth_without_password = configurationAttributes.get( "auth_without_password").getValue2() if StringHelper.equalsIgnoreCase(auth_without_password, "yes"): self.authWithoutPassword = True self.issuerId = CdiUtil.bean( ConfigurationFactory).getAppConfiguration().getIssuer() if configurationAttributes.containsKey("issuer_id"): self.issuerId = configurationAttributes.get( "issuer_id").getValue2() self.pushNotificationManager = PushNotificationManager( notificationServiceMode, credentialsFile) self.networkApi = NetworkApi() return True
def update(self, dynamicScopeContext, configurationAttributes): print "Permission dynamic scope scope. Update method" authorizationGrant = dynamicScopeContext.getAuthorizationGrant() user = dynamicScopeContext.getUser() jsonWebResponse = dynamicScopeContext.getJsonWebResponse() claims = jsonWebResponse.getClaims() userService = CdiUtil.bean(UserService) roles = userService.getCustomAttribute(user, "role") if roles != None: claims.setClaim("role", roles.getValues()) return True
def parseAllProviders(self): registeredProviders = {} print "Passport. parseAllProviders. Adding providers" passportDN = CdiUtil.bean(ConfigurationFactory).getPersistenceConfiguration().getConfiguration().getString("oxpassport_ConfigurationEntryDN") entryManager = CdiUtil.bean(AppInitializer).createPersistenceEntryManager() config = LdapOxPassportConfiguration() config = entryManager.find(config.getClass(), passportDN).getPassportConfiguration() config = config.getProviders() if config != None else config if config != None and len(config) > 0: for prvdetails in config: if prvdetails.isEnabled(): registeredProviders[prvdetails.getId()] = { "emailLinkingSafe": prvdetails.isEmailLinkingSafe(), "requestForEmail" : prvdetails.isRequestForEmail(), "logo_img": prvdetails.getLogoImg(), "displayName": prvdetails.getDisplayName(), "type": prvdetails.getType() } return registeredProviders
def getPageForStep(self, configurationAttributes, step): print "Casa. getPageForStep called %s" % str(step) if step > 1: acr = CdiUtil.bean(Identity).getWorkingParameter("ACR") if acr in self.authenticators: module = self.authenticators[acr] page = module.getPageForStep(module.configAttrs, step) else: page = None return page return "/casa/login.xhtml"
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 "Asimba. GetClientConfiguration. Using client attribute: '%s'" % 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: identity = CdiUtil.bean(Identity) if identity.getSessionId() != None: client_id = identity.getSessionId().getSessionAttributes().get("client_id") if client_id == None: print "Asimba. GetClientConfiguration. client_id is empty" return None clientService = CdiUtil.bean(ClientService) client = clientService.getClient(client_id) if client == None: print "Asimba. GetClientConfiguration. Failed to find client '%s' in local LDAP" % client_id 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 "Asimba. GetClientConfiguration. Client '%s' attribute '%s' is empty" % ( client_id, saml_client_configuration_attribute ) else: print "Asimba. GetClientConfiguration. Client '%s' attribute '%s' is '%s'" % ( client_id, saml_client_configuration_attribute, saml_client_configuration ) return saml_client_configuration return None
def prepareForStep(self, configurationAttributes, requestParameters, step): print "MFA Enroll Recovery. prepareForStep called for step '%s'" % step if (step == 1): identity = CdiUtil.bean(Identity) ######################################################################################## # 1. Make sure we have a session session_id_validation = self.validateSessionId(identity) if not session_id_validation: print "MFA Enroll Recovery. prepareForStep for step %s. Failed to validate session state" % step return False authenticationService = CdiUtil.bean(AuthenticationService) authenticated_user = authenticationService.getAuthenticatedUser() if authenticated_user == None: print "MFA Enroll Recovery. prepareForStep. Failed to determine authenticated user from previous module" return False ######################################################################################## # 2. Generate a recovery code with 128 bit strength # - use Alphanumeric (A-Z,0-9) # - use size of 12 (to achieve around 61 bits of entropy) # - save it in "new_code" if (identity.getWorkingParameter("new_code") == None): alphanumeric = string.ascii_lowercase + string.digits code1 = ''.join(random.SystemRandom().choice(alphanumeric) for _ in range( 4 )) code2 = ''.join(random.SystemRandom().choice(alphanumeric) for _ in range( 4 )) code3 = ''.join(random.SystemRandom().choice(alphanumeric) for _ in range( 4 )) code = "%s-%s-%s" % (code1, code2, code3) identity.setWorkingParameter("new_code", code) else: print "MFA Enroll Recovery. prepareForStep. A code has already been generated and not confirmed" print "MFA Enroll Recovery. prepareForStep. got session '%s'" % identity.getSessionId().toString() return True
def prepareForStep(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) if (step == 1): print "Asimba. Prepare for step 1" httpService = CdiUtil.bean(HttpService) facesContext = CdiUtil.bean(FacesContext) request = facesContext.getExternalContext().getRequest() assertionConsumerServiceUrl = httpService.constructServerUrl( request) + "/postlogin.htm" print "Asimba. Prepare for step 1. Prepared assertionConsumerServiceUrl: '%s'" % assertionConsumerServiceUrl currentSamlConfiguration = self.getCurrentSamlConfiguration( self.samlConfiguration, configurationAttributes, requestParameters) if currentSamlConfiguration == None: print "Asimba. Prepare for step 1. Client saml configuration is invalid" return False # Generate an AuthRequest and send it to the identity provider samlAuthRequest = AuthRequest(currentSamlConfiguration) external_auth_request_uri = currentSamlConfiguration.getIdpSsoTargetUrl( ) + "?SAMLRequest=" + samlAuthRequest.getRequest( True, assertionConsumerServiceUrl) print "Asimba. Prepare for step 1. external_auth_request_uri: '%s'" % external_auth_request_uri facesService = CdiUtil.bean(FacesService) facesService.redirectToExternalURL(external_auth_request_uri) return True elif (step == 2): print "Asimba. Prepare for step 2" return True else: return False
def createLdapExtendedConfigurations(self, authConfiguration): ldapExtendedConfigurations = [] for connectionConfiguration in authConfiguration["ldap_configuration"]: configId = connectionConfiguration["configId"] servers = connectionConfiguration["servers"] bindDN = None bindPassword = None useAnonymousBind = True if (self.containsAttributeString(connectionConfiguration, "bindDN")): useAnonymousBind = False bindDN = connectionConfiguration["bindDN"] bindPassword = CdiUtil.bean(EncryptionService).decrypt( connectionConfiguration["bindPassword"]) useSSL = connectionConfiguration["useSSL"] maxConnections = connectionConfiguration["maxConnections"] baseDNs = connectionConfiguration["baseDNs"] loginAttributes = connectionConfiguration["loginAttributes"] localLoginAttributes = connectionConfiguration[ "localLoginAttributes"] ldapConfiguration = GluuLdapConfiguration() ldapConfiguration.setConfigId(configId) ldapConfiguration.setBindDN(bindDN) ldapConfiguration.setBindPassword(bindPassword) ldapConfiguration.setServers(Arrays.asList(servers)) ldapConfiguration.setMaxConnections(maxConnections) ldapConfiguration.setUseSSL(useSSL) ldapConfiguration.setBaseDNs(Arrays.asList(baseDNs)) ldapConfiguration.setPrimaryKey(loginAttributes[0]) ldapConfiguration.setLocalPrimaryKey(localLoginAttributes[0]) ldapConfiguration.setUseAnonymousBind(useAnonymousBind) ldapExtendedConfigurations.append({ "ldapConfiguration": ldapConfiguration, "connectionConfiguration": connectionConfiguration, "loginAttributes": loginAttributes, "localLoginAttributes": localLoginAttributes }) return ldapExtendedConfigurations
def hasEnrollments(self, configurationAttributes, user): inum = user.getAttribute("inum") devRegService = CdiUtil.bean(DeviceRegistrationService) app_id = configurationAttributes.get("u2f_application_id").getValue2() userDevices = devRegService.findUserDeviceRegistrations( inum, app_id, "oxStatus") hasDevices = False for device in userDevices: if device.getStatus().getValue() == "active": hasDevices = True break return hasDevices
def update(self, dynamicScopeContext, configurationAttributes): # Todo implement this print "Super-Gluu-DynScope update" updated = False identity = CdiUtil.bean(Identity) if (identity is not None) and (identity.getSessionId() is not None): session_id = identity.getSessionId().getId() jsonWebResponse = dynamicScopeContext.getJsonWebResponse() claims = jsonWebResponse.getClaims() claims.setClaim(self.sessionIdClaimName, session_id) updated = True else: print "Super-Gluu-DynScope. No session id found. Skipping" print "Super-Gluu-DynScope update complete" return updated
def isInboundFlow(self, identity): sessionId = identity.getSessionId() if sessionId == None: # Detect mode if there is no session yet. It's needed for getPageForStep method facesContext = CdiUtil.bean(FacesContext) requestParameters = facesContext.getExternalContext().getRequestParameterMap() authz_state = requestParameters.get(AuthorizeRequestParam.STATE) else: authz_state = identity.getSessionId().getSessionAttributes().get(AuthorizeRequestParam.STATE) if self.isInboundJwt(authz_state): return True return False
def prepareForStep(self, configurationAttributes, requestParameters, step): print "Casa. prepareForStep %s" % str(step) if step == 1: return True else: identity = CdiUtil.bean(Identity) session_attributes = identity.getSessionId().getSessionAttributes() authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if user == None: print "Casa. prepareForStep. Cannot retrieve logged user" return False acr = session_attributes.get("ACR") print "Casa. prepareForStep. ACR = %s" % acr identity.setWorkingParameter("methods", ArrayList(self.getAvailMethodsUser(user, acr))) if acr in self.authenticators: module = self.authenticators[acr] return module.prepareForStep(module.configAttrs, requestParameters, step) else: return False
def authenticate(self, configurationAttributes, requestParameters, step): print("WWPass. Authenticate for step %d" % step) authenticationService = CdiUtil.bean(AuthenticationService) userService = CdiUtil.bean(UserService) ticket = requestParameters.get( 'wwp_ticket')[0] if 'wwp_ticket' in requestParameters else None identity = CdiUtil.bean(Identity) identity.setWorkingParameter("errors", "") result = self.doAuthenticate(step, requestParameters, userService, authenticationService, identity, ticket) if result and self.sso_cookie_tags: externalContext = CdiUtil.bean(FacesContext).getExternalContext() for tag in self.sso_cookie_tags: externalContext.addResponseCookie( "sso_magic_%s" % tag, "auth", { "path": "/", "domain": self.sso_cookie_domain, "maxAge": CdiUtil.bean( AppConfiguration).getSessionIdUnusedLifetime() }) return result
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