Search in sources :

Example 36 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class Populator method populationComplete.

private void populationComplete() throws LocalDBException, PwmUnrecoverableException, IOException {
    flushBuffer();
    LOGGER.info(makeStatString());
    LOGGER.trace("beginning wordlist size query");
    final int wordlistSize = localDB.size(rootWordlist.getWordlistDB());
    if (wordlistSize < 1) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, rootWordlist.debugLabel + " population completed, but no words stored"));
    }
    final StringBuilder sb = new StringBuilder();
    sb.append(rootWordlist.debugLabel);
    sb.append(" population complete, added ").append(wordlistSize);
    sb.append(" total words in ").append(new TimeDuration(overallStats.getElapsedSeconds() * 1000).asCompactString());
    {
        final StoredWordlistDataBean storedWordlistDataBean = StoredWordlistDataBean.builder().sha1hash(JavaHelper.binaryArrayToHex(checksumInputStream.closeAndFinalChecksum())).size(wordlistSize).storeDate(Instant.now()).source(source).completed(!abortFlag).build();
        rootWordlist.writeMetadata(storedWordlistDataBean);
    }
    LOGGER.info(sb.toString());
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) TimeDuration(password.pwm.util.java.TimeDuration)

Example 37 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class SharedHistoryManager method init.

private void init(final PwmApplication pwmApplication, final long maxAgeMs) {
    status = STATUS.OPENING;
    final long startTime = System.currentTimeMillis();
    try {
        checkDbVersion();
    } catch (Exception e) {
        LOGGER.error("error checking db version", e);
        status = STATUS.CLOSED;
        return;
    }
    try {
        final String oldestEntryStr = localDB.get(META_DB, KEY_OLDEST_ENTRY);
        if (oldestEntryStr == null || oldestEntryStr.length() < 1) {
            oldestEntry = 0;
            LOGGER.trace("no oldestEntry timestamp stored, will rescan");
        } else {
            oldestEntry = Long.parseLong(oldestEntryStr);
            LOGGER.trace("oldest timestamp loaded from localDB, age is " + TimeDuration.fromCurrent(oldestEntry).asCompactString());
        }
    } catch (LocalDBException e) {
        LOGGER.error("unexpected error loading oldest-entry meta record, will remain closed: " + e.getMessage(), e);
        status = STATUS.CLOSED;
        return;
    }
    try {
        final int size = localDB.size(WORDS_DB);
        final StringBuilder sb = new StringBuilder();
        sb.append("open with ").append(size).append(" words (");
        sb.append(new TimeDuration(System.currentTimeMillis(), startTime).asCompactString()).append(")");
        sb.append(", maxAgeMs=").append(new TimeDuration(maxAgeMs).asCompactString());
        sb.append(", oldestEntry=").append(new TimeDuration(System.currentTimeMillis(), oldestEntry).asCompactString());
        LOGGER.info(sb.toString());
    } catch (LocalDBException e) {
        LOGGER.error("unexpected error examining size of DB, will remain closed: " + e.getMessage(), e);
        status = STATUS.CLOSED;
        return;
    }
    status = STATUS.OPEN;
    if (pwmApplication.getApplicationMode() == PwmApplicationMode.RUNNING || pwmApplication.getApplicationMode() == PwmApplicationMode.CONFIGURATION) {
        long frequencyMs = maxAgeMs > MAX_CLEANER_FREQUENCY ? MAX_CLEANER_FREQUENCY : maxAgeMs;
        frequencyMs = frequencyMs < MIN_CLEANER_FREQUENCY ? MIN_CLEANER_FREQUENCY : frequencyMs;
        LOGGER.debug("scheduling cleaner task to run once every " + new TimeDuration(frequencyMs).asCompactString());
        final String threadName = JavaHelper.makeThreadName(pwmApplication, this.getClass()) + " timer";
        cleanerTimer = new Timer(threadName, true);
        cleanerTimer.schedule(new CleanerTask(), 1000, frequencyMs);
    }
}
Also used : Timer(java.util.Timer) TimeDuration(password.pwm.util.java.TimeDuration) LocalDBException(password.pwm.util.localdb.LocalDBException) LocalDBException(password.pwm.util.localdb.LocalDBException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) PwmException(password.pwm.error.PwmException)

Example 38 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class ProgressInfo method remainingDuration.

public TimeDuration remainingDuration() {
    final float itemsPerMs = itemsPerMs();
    if (itemsPerMs <= 0) {
        return TimeDuration.ZERO;
    }
    final BigDecimal remainingMs = new BigDecimal(itemsRemaining()).divide(new BigDecimal(itemsPerMs), MathContext.DECIMAL32);
    return new TimeDuration(remainingMs.longValue());
}
Also used : TimeDuration(password.pwm.util.java.TimeDuration) BigDecimal(java.math.BigDecimal)

Example 39 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class RandomPasswordGenerator method createRandomPassword.

/**
 * Creates a new password that satisfies the password rules.  All rules are checked for.  If for some
 * reason the RANDOM algorithm can not generate a valid password, null will be returned.
 * <p/>
 * If there is an identifiable reason the password can not be created (such as mis-configured rules) then
 * an {@link com.novell.ldapchai.exception.ImpossiblePasswordPolicyException} will be thrown.
 *
 * @param sessionLabel          A valid pwmSession
 * @param randomGeneratorConfig Policy to be used during generation
 * @param pwmApplication        Used to read configuration, seedmanager and other services.
 * @return A randomly generated password value that meets the requirements of this {@code PasswordPolicy}
 * @throws com.novell.ldapchai.exception.ImpossiblePasswordPolicyException If there is no way to create a password using the configured rules and
 *                                                                         default seed phrase
 */
public static PasswordData createRandomPassword(final SessionLabel sessionLabel, final RandomGeneratorConfig randomGeneratorConfig, final PwmApplication pwmApplication) throws PwmUnrecoverableException {
    final Instant startTimeMS = Instant.now();
    randomGeneratorConfig.validateSettings(pwmApplication);
    final RandomGeneratorConfig effectiveConfig;
    {
        if (randomGeneratorConfig.getSeedlistPhrases() == null || randomGeneratorConfig.getSeedlistPhrases().isEmpty()) {
            Set<String> seeds = DEFAULT_SEED_PHRASES;
            final SeedlistManager seedlistManager = pwmApplication.getSeedlistManager();
            if (seedlistManager != null && seedlistManager.status() == PwmService.STATUS.OPEN && seedlistManager.size() > 0) {
                seeds = new HashSet<>();
                int safetyCounter = 0;
                while (seeds.size() < 10 && safetyCounter < 100) {
                    safetyCounter++;
                    final String randomWord = seedlistManager.randomSeed();
                    if (randomWord != null) {
                        seeds.add(randomWord);
                    }
                }
            }
            effectiveConfig = randomGeneratorConfig.toBuilder().seedlistPhrases(seeds).build();
        } else {
            effectiveConfig = randomGeneratorConfig;
        }
    }
    final SeedMachine seedMachine = new SeedMachine(normalizeSeeds(effectiveConfig.getSeedlistPhrases()));
    int tryCount = 0;
    final StringBuilder password = new StringBuilder();
    // determine the password policy to use for random generation
    final PwmPasswordPolicy randomGenPolicy;
    {
        final Map<String, String> newPolicyMap = new HashMap<>();
        newPolicyMap.putAll(effectiveConfig.getPasswordPolicy().getPolicyMap());
        final String max = newPolicyMap.put(PwmPasswordRule.MaximumLength.getKey(), String.valueOf(effectiveConfig.getMaximumLength()));
        if (effectiveConfig.getMinimumLength() > effectiveConfig.getPasswordPolicy().getRuleHelper().readIntValue(PwmPasswordRule.MinimumLength)) {
            newPolicyMap.put(PwmPasswordRule.MinimumLength.getKey(), String.valueOf(effectiveConfig.getMinimumLength()));
        }
        if (effectiveConfig.getMaximumLength() < effectiveConfig.getPasswordPolicy().getRuleHelper().readIntValue(PwmPasswordRule.MaximumLength)) {
            newPolicyMap.put(PwmPasswordRule.MaximumLength.getKey(), String.valueOf(effectiveConfig.getMaximumLength()));
        }
        if (effectiveConfig.getMinimumStrength() > effectiveConfig.getPasswordPolicy().getRuleHelper().readIntValue(PwmPasswordRule.MinimumStrength)) {
            newPolicyMap.put(PwmPasswordRule.MinimumStrength.getKey(), String.valueOf(effectiveConfig.getMinimumStrength()));
        }
        randomGenPolicy = PwmPasswordPolicy.createPwmPasswordPolicy(newPolicyMap);
    }
    // initial creation
    password.append(generateNewPassword(seedMachine, effectiveConfig.getMinimumLength()));
    // read a rule validator
    final PwmPasswordRuleValidator pwmPasswordRuleValidator = new PwmPasswordRuleValidator(pwmApplication, randomGenPolicy);
    // modify until it passes all the rules
    final int maxTryCount = Integer.parseInt(pwmApplication.getConfig().readAppProperty(AppProperty.PASSWORD_RANDOMGEN_MAX_ATTEMPTS));
    final int jitterCount = Integer.parseInt(pwmApplication.getConfig().readAppProperty(AppProperty.PASSWORD_RANDOMGEN_JITTER_COUNT));
    boolean validPassword = false;
    while (!validPassword && tryCount < maxTryCount) {
        tryCount++;
        validPassword = true;
        if (tryCount % jitterCount == 0) {
            password.delete(0, password.length());
            password.append(generateNewPassword(seedMachine, effectiveConfig.getMinimumLength()));
        }
        final List<ErrorInformation> errors = pwmPasswordRuleValidator.internalPwmPolicyValidator(password.toString(), null, null, PwmPasswordRuleValidator.Flag.FailFast);
        if (errors != null && !errors.isEmpty()) {
            validPassword = false;
            modifyPasswordBasedOnErrors(password, errors, seedMachine);
        } else if (checkPasswordAgainstDisallowedHttpValues(pwmApplication.getConfig(), password.toString())) {
            validPassword = false;
            password.delete(0, password.length());
            password.append(generateNewPassword(seedMachine, effectiveConfig.getMinimumLength()));
        }
    }
    // report outcome
    {
        final TimeDuration td = TimeDuration.fromCurrent(startTimeMS);
        if (validPassword) {
            LOGGER.trace(sessionLabel, "finished random password generation in " + td.asCompactString() + " after " + tryCount + " tries.");
        } else {
            final List<ErrorInformation> errors = pwmPasswordRuleValidator.internalPwmPolicyValidator(password.toString(), null, null);
            final int judgeLevel = PasswordUtility.judgePasswordStrength(pwmApplication.getConfig(), password.toString());
            final StringBuilder sb = new StringBuilder();
            sb.append("failed random password generation after ").append(td.asCompactString()).append(" after ").append(tryCount).append(" tries. ");
            sb.append("(errors=").append(errors.size()).append(", judgeLevel=").append(judgeLevel);
            LOGGER.error(sessionLabel, sb.toString());
        }
    }
    StatisticsManager.incrementStat(pwmApplication, Statistic.GENERATED_PASSWORDS);
    final String logText = "real-time random password generator called" + " (" + TimeDuration.compactFromCurrent(startTimeMS) + ")";
    LOGGER.trace(sessionLabel, logText);
    return new PasswordData(password.toString());
}
Also used : SeedlistManager(password.pwm.svc.wordlist.SeedlistManager) HashSet(java.util.HashSet) Set(java.util.Set) Instant(java.time.Instant) ErrorInformation(password.pwm.error.ErrorInformation) PwmPasswordPolicy(password.pwm.config.profile.PwmPasswordPolicy) TimeDuration(password.pwm.util.java.TimeDuration) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 40 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class StatisticsManager method close.

public void close() {
    try {
        writeDbValues();
    } catch (Exception e) {
        LOGGER.error("unexpected error closing: " + e.getMessage());
    }
    JavaHelper.closeAndWaitExecutor(executorService, new TimeDuration(3, TimeUnit.SECONDS));
    status = STATUS.CLOSED;
}
Also used : TimeDuration(password.pwm.util.java.TimeDuration) LocalDBException(password.pwm.util.localdb.LocalDBException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException)

Aggregations

TimeDuration (password.pwm.util.java.TimeDuration)75 Instant (java.time.Instant)28 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)22 ErrorInformation (password.pwm.error.ErrorInformation)19 PwmException (password.pwm.error.PwmException)14 ArrayList (java.util.ArrayList)12 LinkedHashMap (java.util.LinkedHashMap)12 IOException (java.io.IOException)9 Configuration (password.pwm.config.Configuration)8 PwmOperationalException (password.pwm.error.PwmOperationalException)8 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)7 Map (java.util.Map)7 UserIdentity (password.pwm.bean.UserIdentity)7 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)6 List (java.util.List)6 MacroMachine (password.pwm.util.macro.MacroMachine)6 BigDecimal (java.math.BigDecimal)5 Date (java.util.Date)5 Locale (java.util.Locale)5