public UserCacheRecord next() { try { UserCacheRecord returnBean = null; while (returnBean == null && this.storageKeyIterator.hasNext()) { UserCacheService.StorageKey key = this.storageKeyIterator.next(); returnBean = userCacheService.readStorageKey(key); if (returnBean != null) { if (returnBean.getCacheTimestamp() == null) { LOGGER.debug( PwmConstants.REPORTING_SESSION_LABEL, "purging record due to missing cache timestamp: " + JsonUtil.serialize(returnBean)); userCacheService.removeStorageKey(key); } else if (TimeDuration.fromCurrent(returnBean.getCacheTimestamp()) .isLongerThan(settings.getMaxCacheAge())) { LOGGER.debug( PwmConstants.REPORTING_SESSION_LABEL, "purging record due to old age timestamp: " + JsonUtil.serialize(returnBean)); userCacheService.removeStorageKey(key); } else { return returnBean; } } } } catch (LocalDBException e) { throw new IllegalStateException( "unexpected iterator traversal error while reading LocalDB: " + e.getMessage()); } return null; }
private void restBrowseLdap(final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean) throws IOException, ServletException, PwmUnrecoverableException { final StoredConfigurationImpl storedConfiguration = StoredConfigurationImpl.copy(configGuideBean.getStoredConfiguration()); if (configGuideBean.getStep() == STEP.LDAP_ADMIN) { storedConfiguration.resetSetting(PwmSetting.LDAP_PROXY_USER_DN, LDAP_PROFILE_KEY, null); storedConfiguration.resetSetting(PwmSetting.LDAP_PROXY_USER_PASSWORD, LDAP_PROFILE_KEY, null); } final Date startTime = new Date(); final Map<String, String> inputMap = pwmRequest.readBodyAsJsonStringMap(PwmHttpRequestWrapper.Flag.BypassValidation); final String profile = inputMap.get("profile"); final String dn = inputMap.containsKey("dn") ? inputMap.get("dn") : ""; final LdapBrowser ldapBrowser = new LdapBrowser(storedConfiguration); final LdapBrowser.LdapBrowseResult result = ldapBrowser.doBrowse(profile, dn); ldapBrowser.close(); LOGGER.trace( pwmRequest, "performed ldapBrowse operation in " + TimeDuration.fromCurrent(startTime).asCompactString() + ", result=" + JsonUtil.serialize(result)); pwmRequest.outputJsonResult(new RestResultBean(result)); }
private static List<UserIdentity> readAllUsersFromLdap( final PwmApplication pwmApplication, final String searchFilter, final int maxResults) throws ChaiUnavailableException, ChaiOperationException, PwmUnrecoverableException, PwmOperationalException { final UserSearchEngine userSearchEngine = new UserSearchEngine(pwmApplication, null); final UserSearchEngine.SearchConfiguration searchConfiguration = new UserSearchEngine.SearchConfiguration(); searchConfiguration.setEnableValueEscaping(false); searchConfiguration.setSearchTimeout( Long.parseLong( pwmApplication.getConfig().readAppProperty(AppProperty.REPORTING_LDAP_SEARCH_TIMEOUT))); if (searchFilter == null) { searchConfiguration.setUsername("*"); } else { searchConfiguration.setFilter(searchFilter); } LOGGER.debug( PwmConstants.REPORTING_SESSION_LABEL, "beginning UserReportService user search using parameters: " + (JsonUtil.serialize(searchConfiguration))); final Map<UserIdentity, Map<String, String>> searchResults = userSearchEngine.performMultiUserSearch( searchConfiguration, maxResults, Collections.<String>emptyList()); LOGGER.debug( PwmConstants.REPORTING_SESSION_LABEL, "user search found " + searchResults.size() + " users for reporting"); final List<UserIdentity> returnList = new ArrayList<>(searchResults.keySet()); Collections.shuffle(returnList); return returnList; }
private void updateCacheFromLdap() throws ChaiUnavailableException, ChaiOperationException, PwmOperationalException, PwmUnrecoverableException { LOGGER.debug( PwmConstants.REPORTING_SESSION_LABEL, "beginning process to updating user cache records from ldap"); if (status != STATUS.OPEN) { return; } cancelFlag = false; reportStatus = new ReportStatusInfo(settings.getSettingsHash()); reportStatus.setInProgress(true); reportStatus.setStartDate(new Date()); try { final Queue<UserIdentity> allUsers = new LinkedList<>(getListOfUsers()); reportStatus.setTotal(allUsers.size()); while (status == STATUS.OPEN && !allUsers.isEmpty() && !cancelFlag) { final Date startUpdateTime = new Date(); final UserIdentity userIdentity = allUsers.poll(); try { if (updateCachedRecordFromLdap(userIdentity)) { reportStatus.setUpdated(reportStatus.getUpdated() + 1); } } catch (Exception e) { String errorMsg = "error while updating report cache for " + userIdentity.toString() + ", cause: "; errorMsg += e instanceof PwmException ? ((PwmException) e).getErrorInformation().toDebugStr() : e.getMessage(); final ErrorInformation errorInformation; errorInformation = new ErrorInformation(PwmError.ERROR_REPORTING_ERROR, errorMsg); LOGGER.error(PwmConstants.REPORTING_SESSION_LABEL, errorInformation.toDebugStr()); reportStatus.setLastError(errorInformation); reportStatus.setErrors(reportStatus.getErrors() + 1); } reportStatus.setCount(reportStatus.getCount() + 1); reportStatus.getEventRateMeter().markEvents(1); final TimeDuration totalUpdateTime = TimeDuration.fromCurrent(startUpdateTime); if (settings.isAutoCalcRest()) { avgTracker.addSample(totalUpdateTime.getTotalMilliseconds()); Helper.pause(avgTracker.avgAsLong()); } else { Helper.pause(settings.getRestTime().getTotalMilliseconds()); } } if (cancelFlag) { reportStatus.setLastError( new ErrorInformation( PwmError.ERROR_SERVICE_NOT_AVAILABLE, "report cancelled by operator")); } } finally { reportStatus.setFinishDate(new Date()); reportStatus.setInProgress(false); } LOGGER.debug( PwmConstants.REPORTING_SESSION_LABEL, "update user cache process completed: " + JsonUtil.serialize(reportStatus)); }
public static String serialize(Object obj) throws ApiException { try { if (obj != null) return JsonUtil.serialize(obj); else return null; } catch (Exception e) { throw new ApiException(500, e.getMessage()); } }
private void saveTempData() { try { final String jsonInfo = JsonUtil.serialize(reportStatus); pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.REPORT_STATUS, jsonInfo); } catch (Exception e) { LOGGER.error( PwmConstants.REPORTING_SESSION_LABEL, "error writing cached report dredge info into memory: " + e.getMessage()); } }
public BulkResponse bulk(BulkRequest bulkRequest) throws Exception { StringBuffer sbf = new StringBuffer(); for (SingleBulkRequest request : bulkRequest.getRequests()) { sbf.append("{"); String header = JsonUtil.serialize(request); if (request instanceof DeleteRequest) { sbf.append("\"delete\":").append(header).append("}\n"); } if (request instanceof IndexRequest) { sbf.append("\"index\":").append(header).append("}\n"); // Index Request: header line + body sbf.append(((IndexRequest) request).content().replaceAll("\n", "")).append("\n"); } } logger.trace("going to send a bulk"); logger.trace("{}", sbf); StringEntity entity = new StringEntity(sbf.toString(), Charset.defaultCharset()); Response restResponse = client.performRequest("POST", "/_bulk", Collections.emptyMap(), entity); BulkResponse response = JsonUtil.deserialize(restResponse, BulkResponse.class); logger.debug("bulk response: {}", response); return response; }
public static PasswordCheckInfo checkEnteredPassword( final PwmApplication pwmApplication, final Locale locale, final ChaiUser user, final UserInfoBean userInfoBean, final LoginInfoBean loginInfoBean, final PasswordData password, final PasswordData confirmPassword) throws PwmUnrecoverableException, ChaiUnavailableException { if (userInfoBean == null) { throw new NullPointerException("userInfoBean cannot be null"); } boolean pass = false; String userMessage = ""; int errorCode = 0; final boolean passwordIsCaseSensitive = userInfoBean.getPasswordPolicy() == null || userInfoBean .getPasswordPolicy() .getRuleHelper() .readBooleanValue(PwmPasswordRule.CaseSensitive); final CachePolicy cachePolicy; { final long cacheLifetimeMS = Long.parseLong( pwmApplication .getConfig() .readAppProperty(AppProperty.CACHE_PWRULECHECK_LIFETIME_MS)); cachePolicy = CachePolicy.makePolicyWithExpirationMS(cacheLifetimeMS); } if (password == null) { userMessage = new ErrorInformation(PwmError.PASSWORD_MISSING) .toUserStr(locale, pwmApplication.getConfig()); } else { final CacheService cacheService = pwmApplication.getCacheService(); final CacheKey cacheKey = user != null && userInfoBean.getUserIdentity() != null ? CacheKey.makeCacheKey( PasswordUtility.class, userInfoBean.getUserIdentity(), user.getEntryDN() + ":" + password.hash()) : null; if (pwmApplication.getConfig().isDevDebugMode()) { LOGGER.trace("generated cacheKey for password check request: " + cacheKey); } try { if (cacheService != null && cacheKey != null) { final String cachedValue = cacheService.get(cacheKey); if (cachedValue != null) { if (NEGATIVE_CACHE_HIT.equals(cachedValue)) { pass = true; } else { LOGGER.trace("cache hit!"); final ErrorInformation errorInformation = JsonUtil.deserialize(cachedValue, ErrorInformation.class); throw new PwmDataValidationException(errorInformation); } } } if (!pass) { final PwmPasswordRuleValidator pwmPasswordRuleValidator = new PwmPasswordRuleValidator( pwmApplication, userInfoBean.getPasswordPolicy(), locale); final PasswordData oldPassword = loginInfoBean == null ? null : loginInfoBean.getUserCurrentPassword(); pwmPasswordRuleValidator.testPassword(password, oldPassword, userInfoBean, user); pass = true; if (cacheService != null && cacheKey != null) { cacheService.put(cacheKey, cachePolicy, NEGATIVE_CACHE_HIT); } } } catch (PwmDataValidationException e) { errorCode = e.getError().getErrorCode(); userMessage = e.getErrorInformation().toUserStr(locale, pwmApplication.getConfig()); pass = false; if (cacheService != null && cacheKey != null) { final String jsonPayload = JsonUtil.serialize(e.getErrorInformation()); cacheService.put(cacheKey, cachePolicy, jsonPayload); } } } final PasswordCheckInfo.MATCH_STATUS matchStatus = figureMatchStatus(passwordIsCaseSensitive, password, confirmPassword); if (pass) { switch (matchStatus) { case EMPTY: userMessage = new ErrorInformation(PwmError.PASSWORD_MISSING_CONFIRM) .toUserStr(locale, pwmApplication.getConfig()); break; case MATCH: userMessage = new ErrorInformation(PwmError.PASSWORD_MEETS_RULES) .toUserStr(locale, pwmApplication.getConfig()); break; case NO_MATCH: userMessage = new ErrorInformation(PwmError.PASSWORD_DOESNOTMATCH) .toUserStr(locale, pwmApplication.getConfig()); break; default: userMessage = ""; } } final int strength = judgePasswordStrength(password == null ? null : password.getStringValue()); return new PasswordCheckInfo(userMessage, pass, strength, matchStatus, errorCode); }