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): 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 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 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 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): 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 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 "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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 getPageForStep(self, configurationAttributes, step): # Get the locale/language from the browser locale = CdiUtil.bean(LanguageBean).getLocaleCode()[:2] print "U2F. 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 identity = CdiUtil.bean(Identity) authenticationFlow = identity.getSessionId().getSessionAttributes( ).get("authenticationFlow") # choose appropriate page if authenticationFlow == 'MFA_VALIDATION': if locale == "en": return "/en/verify/token.xhtml" if locale == "fr": return "/fr/verifier/jeton.xhtml" else: if locale == "en": return "/en/register/token.xhtml" if locale == "fr": return "/fr/enregistrer/jeton.xhtml"
def verify_authentication(self, context): print "Super-Gluu-RO verify_authentication" session_id = context.getHttpRequest().getParameter( self.sessionIdParamName) sessionId = CdiUtil.bean(SessionIdService).getSessionId(session_id) if sessionId == None: print "Super-Gluu-RO.verify_authentication failed. 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. verify_authentication failed due to invalid session ownership" context.setUser(None) return False if not self.is_session_authenticated(sessionId): print "Super-Gluu-Ro. verify_authentication failed. Session is not authenticated" context.setUser(None) return False print "Super-Gluu-RO verify_authentication complete" return True
def getAuthenticatorType(self, configurationAttributes, user): print "MFA Chooser. getAuthenticatorType called" userService = CdiUtil.bean(UserService) # First, check the user for OTP registrations externalUids = userService.getCustomAttribute(user, "oxExternalUid") if (externalUids != None): # scan through the values to see if any match for externalUid in externalUids.getValues(): index = externalUid.find("totp:") if index != -1: print "MFA Chooser. getAuthenticatorType: Found a TOTP authenticator" return "TOTP" # Second, check if user has registered U2F devices userInum = user.getAttribute("inum") u2fApplicationId = configurationAttributes.get( "u2f_application_id").getValue2() deviceRegistrationService = CdiUtil.bean(DeviceRegistrationService) u2fRegistrations = deviceRegistrationService.findUserDeviceRegistrations( userInum, u2fApplicationId) if (u2fRegistrations.size() > 0): print "MFA Chooser. getAuthenticatorType: Found a U2F authenticator" return "UTF" # Third, check if the user has a recovery code recoveryCode = userService.getCustomAttribute(user, "secretAnswer") if (recoveryCode != None): print "MFA Chooser. getAuthenticatorType: Found a Recovery Code" return "RecoveryCode" # No authenticators were found print "MFA Chooser. getAuthenticatorType: No authenticators found" return None
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 getCountAuthenticationSteps(self, configurationAttributes): if REMOTE_DEBUG: pydevd.settrace('localhost', port=5678, stdoutToServer=True, stderrToServer=True) identity = CdiUtil.bean(Identity) stepCount = identity.getWorkingParameter("stepCount") if stepCount is None: return 255 # not done yet else: return stepCount
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 authenticateFIDO(self, requestParameters, username, identity): facesMessages = CdiUtil.bean(FacesMessages) languageBean = CdiUtil.bean(LanguageBean) authenticationProtectionService = CdiUtil.bean(AuthenticationProtectionService) facesMessages.setKeepMessages() if (authenticationProtectionService.isEnabled()): authenticationProtectionService.doDelayIfNeeded(username) token_response = ServerUtil.getFirstValue(requestParameters, "tokenResponse") authenticationRequestService = FidoU2fClientFactory.instance().createAuthenticationRequestService(self.metaDataConfiguration) authenticationStatus = authenticationRequestService.finishAuthentication(username, token_response) if (authenticationStatus.getStatus() != Constants.RESULT_SUCCESS): print "MFA. Authenticate FIDO. Failed to authenticate U2F device" facesMessages.add(FacesMessage.SEVERITY_ERROR, languageBean.getMessage("mfa.FIDOInvalid")) if (authenticationProtectionService.isEnabled()): authenticationProtectionService.storeAttempt(username, False) return False if (authenticationProtectionService.isEnabled()): authenticationProtectionService.storeAttempt(username, True) return True
def parseLoginHint(self): # Inject dependencies facesResources = CdiUtil.bean(FacesResources) facesContext = facesResources.getFacesContext() httpRequest = facesContext.getCurrentInstance().getExternalContext().getRequest() loginHint = httpRequest.getParameter("login_hint") if (loginHint == None): raise MFAError("ERROR: login_hint is not set, no user context for authentication") decryptedLoginHint = self.decryptAES(self.aesKey , Base64Util.base64urldecodeToString(loginHint)) pairwiseId = decryptedLoginHint.split('|')[0] relyingParty = decryptedLoginHint.split('|')[1] return pairwiseId, relyingParty
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 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 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 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 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 getPageForStep(self, configurationAttributes, step): if step == 2: identity = CdiUtil.bean(Identity) otp_auth_method = identity.getWorkingParameter("otp_auth_method") print "OTP (with lockout). Gep page for step 2. otp_auth_method: '%s'" % otp_auth_method if otp_auth_method == 'enroll': return "/admin/enroll.xhtml" else: return "/admin/otplogin.xhtml" elif step == 3: return "/admin/otplogin.xhtml" return "/admin/login.xhtml"
def authorize( self, context ): # context is reference of org.gluu.oxauth.uma.authorization.UmaAuthorizationContext print "Authenticated RPT Policy. Authorizing ..." authenticationService = CdiUtil.bean(AuthenticationService) userService = CdiUtil.bean(UserService) try: claim_token = context.getClaimToken() payload = str(claim_token).split(".")[1] paddedPayload = payload + '=' * (4 - len(payload) % 4) decoded = base64.b64decode(paddedPayload) userInum = json.loads(decoded)["sub"] tokenExp = int(json.loads(decoded)["exp"]) user = userService.getUserByInum(userInum) logged_in = authenticationService.authenticate(user.getUserId()) except: print "Authenticated RPT Policy. No claim token passed!" return False if tokenExp < int(time.time()): print "Authenticated RPT Policy. Claim token has expired!" return False print "Authenticated RPT Policy. Logged in: " + str(logged_in) if not logged_in: print "Authenticated RPT Policy. User is not authenticated!" #clientId = context.getConfigurationAttributes().get("client_id").getValue2() #redirectUri = context.getClaimsGatheringEndpoint() + "?authentication=true" #authorizationUrl = context.getAuthorizationEndpoint() + "?client_id=" + clientId + "&redirect_uri=" + redirectUri + "&scope=openid&response_type=code" #context.redirectToExternalUrl(authorizationUrl) return False else: print "Authenticated RPT Policy. User is authenticated." return True
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 modifyIdToken(self, jsonWebResponse, context): jwrService = CdiUtil.bean(JwrService) client = context.getClient() signedJWT = jwrService.encode(jsonWebResponse, client) eventProperties = { "client": client.getClientName(), "header": signedJWT.getHeader().toJsonString(), "payload": signedJWT.getClaims().toJsonString(), "signature": signedJWT.getEncodedSignature() } self.telemetryClient.trackEvent("ID Token", eventProperties, None) return False
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 init(self, customScript, configurationAttributes): print "inWebo. Initialization" iw_cert_store_type = configurationAttributes.get( "iw_cert_store_type").getValue2() iw_cert_path = configurationAttributes.get("iw_cert_path").getValue2() iw_creds_file = configurationAttributes.get( "iw_creds_file").getValue2() self.push_withoutpin = "false" self.push_fail = "false" #permissible values = true , false self.push_withoutpin = 1 if StringHelper.equalsIgnoreCase( "false", configurationAttributes.get("iw_push_withoutpin").getValue2()): self.push_withoutpin = 0 self.api_uri = configurationAttributes.get("iw_api_uri").getValue2() self.service_id = configurationAttributes.get( "iw_service_id").getValue2() # Load credentials from file f = open(iw_creds_file, 'r') try: creds = json.loads(f.read()) except: print "unexpected error - " + sys.exc_info()[0] return False finally: f.close() iw_cert_password = creds["CERT_PASSWORD"] #TODO: the password should not be in plaintext #try: # encryptionService = CdiUtil.bean(EncryptionService) # iw_cert_password = encryptionService.decrypt(iw_cert_password) #except: # print("oops!",sys.exc_info()[0],"occured.") # return False httpService = CdiUtil.bean(HttpService) self.client = httpService.getHttpsClient(None, None, None, iw_cert_store_type, iw_cert_path, iw_cert_password) print "inWebo. Initialized successfully" return True
def get_geolocation_data(self, remote_ip): print "NetApi. Determining remote location for ip address '%s'" % remote_ip httpService = CdiUtil.bean(HttpService) http_client = httpService.getHttpsClient() http_client_params = http_client.getParams() http_client_params.setIntParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, self.conn_timeout) geolocation_service_url = "http://ip-api.com/json/%s?fields=49177" % 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 "NetApi. Could not determine remote location: ", sys.exc_info( )[1] return None try: if not httpService.isResponseStastusCodeOk(http_response): http_error_str = str( http_response.getStatusLine().getStatusCode()) print "NetApi. Could not determine remote location: ", http_error_str httpService.consume(http_response) return None 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 "NetApi. Could not determine remote location. Empty respone from server" return None response = json.loads(response_string) if not StringHelper.equalsIgnoreCase(response['status'], "success"): print "NetApi. Could not determine remote location. ip-api status: '%s'" % response[ 'status'] return None return GeolocationData(response)
def findExistingCode(self, user): # get the user by user ID if user == None: print "MFA Enroll Recovery. findExistingCode. Failed to find user" return None # get the values from the user profile userService = CdiUtil.bean(UserService) user_secret_answers = userService.getCustomAttribute(user, "secretAnswer") if user_secret_answers == None: return None for user_secret_answer in user_secret_answers.getValues(): return user_secret_answer return None
def getPageForStep(self, configurationAttributes, step): print "Passport. getPageForStep called" extensionResult = self.extensionGetPageForStep(configurationAttributes, step) if extensionResult != None: return extensionResult if step == 1: identity = CdiUtil.bean(Identity) if self.isInboundFlow(identity): print "Passport. getPageForStep for step 1. Detected inbound Saml flow" return "/postlogin.xhtml" return "/auth/passport/passportlogin.xhtml" return "/auth/passport/passportpostlogin.xhtml"
def update(self, dynamicScopeContext, configurationAttributes): print "Dynamic scope. Update method" dynamicScopes = dynamicScopeContext.getDynamicScopes() authorizationGrant = dynamicScopeContext.getAuthorizationGrant() user = dynamicScopeContext.getUser() jsonWebResponse = dynamicScopeContext.getJsonWebResponse() claims = jsonWebResponse.getClaims() # Add work phone if there is scope = work_phone userService = CdiUtil.bean(UserService) workPhone = userService.getCustomAttribute(user, "telephoneNumber") if workPhone != None: claims.setClaim("work_phone", workPhone.getValues()) return True
def registerRecoveryCode(self,requestParameters, username, identity): # Inject dependencies userService = CdiUtil.bean(UserService) code1 = ''.join(random.SystemRandom().choice(self.recoveryChars) for _ in range( 4 )) code2 = ''.join(random.SystemRandom().choice(self.recoveryChars) for _ in range( 4 )) code3 = ''.join(random.SystemRandom().choice(self.recoveryChars) for _ in range( 4 )) code = "%s-%s-%s" % (code1, code2, code3) identity.setWorkingParameter("recoveryCode", code) encryptedCode = self.encryptAES(self.aesKey, code) user = userService.getUser(username, "uid", "secretAnswer") userService.setCustomAttribute(user, "secretAnswer", encryptedCode) user = userService.updateUser(user) return user is not None
def getUserProfile(self, jwt): # getClaims method located at org.gluu.oxauth.model.token.JsonWebResponse.java as a org.gluu.oxauth.model.jwt.JwtClaims object jwt_claims = jwt.getClaims() user_profile_json = None try: # public String getClaimAsString(String key) user_profile_json = CdiUtil.bean(EncryptionService).decrypt(jwt_claims.getClaimAsString("data")) user_profile = json.loads(user_profile_json) except: print "Passport. getUserProfile. Problem obtaining user profile json representation" return (user_profile, user_profile_json)
def getPageForStep(self, configurationAttributes, step): if step == 2: identity = CdiUtil.bean(Identity) otp_auth_method = identity.getWorkingParameter("otp_auth_method") print "OTP. Get page for step 2. otp_auth_method: '%s'" % otp_auth_method if otp_auth_method == 'enroll': return "/auth/otp/enroll.xhtml" else: #Modified for Casa compliance return "/casa/otplogin.xhtml" elif step == 3: return "/auth/otp/otplogin.xhtml" return ""
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 prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) self.setRequestScopedParameters(identity) session_attributes = identity.getSessionId().getSessionAttributes() pwdcompromised = session_attributes.get("pwd_compromised") if (pwdcompromised != None): if step == 1: print "compromised_password. Prepare for step 1" return True elif step == 2: print "compromised_password. Prepare for step 2" return True return False else: print "compromised_password. Prepare for step 1" return True
def enroll_azure_user_in_gluu_ldap(self, azure_auth_response_json): user_service = CdiUtil.bean(UserService) azure_user_uuid_value = azure_auth_response_json[azure_user_uuid] found_user = self.find_user_from_gluu_ldap_by_attribute(user_service, gluu_ldap_uuid, azure_user_uuid_value) print "AzureAD. Value of found_user is %s" % found_user if found_user is None: new_user = User() self.populate_user_obj_with_azure_user_data(new_user, azure_auth_response_json) try: # Add azure user in Gluu LDAP found_user = user_service.addUser(new_user, True) found_user_id = found_user.getUserId() print("AzureAD: Azure User added successfully in Gluu LDAP " + found_user_id) except Exception, err: print("AzureAD: Error in adding azure user to Gluu LDAP:" + str(err)) return None
def processAuditGroup(self, user): if (self.use_audit_group): is_member = self.isUserMemberOfGroup(user, self.audit_attribute, self.audit_group) if (is_member): print "Duo. Authenticate for processAuditGroup. User '" + user.getUserId( ) + "' member of audit group" print "Duo. Authenticate for processAuditGroup. Sending e-mail about user '" + user.getUserId( ) + "' login to", self.audit_email # Send e-mail to administrator user_id = user.getUserId() mailService = CdiUtil.bean(MailService) subject = "User log in: " + user_id body = "User log in: " + user_id mailService.sendMail(self.audit_email, subject, body)