Search in sources :

Example 21 with PwmException

use of password.pwm.error.PwmException in project pwm by pwm-project.

the class TokenService method init.

public void init(final PwmApplication pwmApplication) throws PwmException {
    LOGGER.trace("opening");
    status = STATUS.OPENING;
    this.pwmApplication = pwmApplication;
    this.configuration = pwmApplication.getConfig();
    storageMethod = configuration.getTokenStorageMethod();
    if (storageMethod == null) {
        final String errorMsg = "no storage method specified";
        errorInformation = new ErrorInformation(PwmError.ERROR_INVALID_CONFIG, errorMsg);
        status = STATUS.CLOSED;
        throw new PwmOperationalException(errorInformation);
    }
    try {
        DataStorageMethod usedStorageMethod = null;
        switch(storageMethod) {
            case STORE_LOCALDB:
                {
                    final DataStore dataStore = new LocalDBDataStore(pwmApplication.getLocalDB(), LocalDB.DB.TOKENS);
                    tokenMachine = new DataStoreTokenMachine(pwmApplication, this, dataStore);
                    usedStorageMethod = DataStorageMethod.LOCALDB;
                    break;
                }
            case STORE_DB:
                {
                    final DataStore dataStore = new DatabaseDataStore(pwmApplication.getDatabaseService(), DatabaseTable.TOKENS);
                    tokenMachine = new DataStoreTokenMachine(pwmApplication, this, dataStore);
                    usedStorageMethod = DataStorageMethod.DB;
                    break;
                }
            case STORE_CRYPTO:
                tokenMachine = new CryptoTokenMachine(this);
                usedStorageMethod = DataStorageMethod.CRYPTO;
                break;
            case STORE_LDAP:
                tokenMachine = new LdapTokenMachine(this, pwmApplication);
                usedStorageMethod = DataStorageMethod.LDAP;
                break;
            default:
                JavaHelper.unhandledSwitchStatement(storageMethod);
        }
        serviceInfo = new ServiceInfoBean(Collections.singletonList(usedStorageMethod));
    } catch (PwmException e) {
        final String errorMsg = "unable to start token manager: " + e.getErrorInformation().getDetailedErrorMsg();
        final ErrorInformation newErrorInformation = new ErrorInformation(e.getError(), errorMsg);
        errorInformation = newErrorInformation;
        LOGGER.error(newErrorInformation.toDebugStr());
        status = STATUS.CLOSED;
        return;
    }
    executorService = Executors.newSingleThreadScheduledExecutor(JavaHelper.makePwmThreadFactory(JavaHelper.makeThreadName(pwmApplication, this.getClass()) + "-", true));
    final TimerTask cleanerTask = new CleanerTask();
    {
        final int cleanerFrequencySeconds = Integer.parseInt(configuration.readAppProperty(AppProperty.TOKEN_CLEANER_INTERVAL_SECONDS));
        final TimeDuration cleanerFrequency = new TimeDuration(cleanerFrequencySeconds, TimeUnit.SECONDS);
        executorService.scheduleAtFixedRate(cleanerTask, 10, cleanerFrequencySeconds, TimeUnit.SECONDS);
        LOGGER.trace("token cleanup will occur every " + cleanerFrequency.asCompactString());
    }
    verifyPwModifyTime = Boolean.parseBoolean(configuration.readAppProperty(AppProperty.TOKEN_VERIFY_PW_MODIFY_TIME));
    status = STATUS.OPEN;
    LOGGER.debug("open");
}
Also used : DataStorageMethod(password.pwm.config.option.DataStorageMethod) PwmOperationalException(password.pwm.error.PwmOperationalException) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) LocalDBDataStore(password.pwm.util.localdb.LocalDBDataStore) DatabaseDataStore(password.pwm.util.db.DatabaseDataStore) TimerTask(java.util.TimerTask) DataStore(password.pwm.util.DataStore) LocalDBDataStore(password.pwm.util.localdb.LocalDBDataStore) DatabaseDataStore(password.pwm.util.db.DatabaseDataStore) TimeDuration(password.pwm.util.java.TimeDuration)

Example 22 with PwmException

use of password.pwm.error.PwmException in project pwm by pwm-project.

the class TokenService method generateNewToken.

public String generateNewToken(final TokenPayload tokenPayload, final SessionLabel sessionLabel) throws PwmUnrecoverableException, PwmOperationalException {
    checkStatus();
    final String tokenKey;
    try {
        tokenKey = tokenMachine.generateToken(sessionLabel, tokenPayload);
        tokenMachine.storeToken(tokenMachine.keyFromKey(tokenKey), tokenPayload);
    } catch (PwmException e) {
        final String errorMsg = "unexpected error trying to store token in datastore: " + e.getMessage();
        final ErrorInformation errorInformation = new ErrorInformation(e.getError(), errorMsg);
        throw new PwmOperationalException(errorInformation);
    }
    LOGGER.trace(sessionLabel, "generated token with payload: " + tokenPayload.toDebugString());
    final AuditRecord auditRecord = new AuditRecordFactory(pwmApplication).createUserAuditRecord(AuditEvent.TOKEN_ISSUED, tokenPayload.getUserIdentity(), sessionLabel, JsonUtil.serialize(tokenPayload));
    pwmApplication.getAuditManager().submit(auditRecord);
    return tokenKey;
}
Also used : PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) AuditRecordFactory(password.pwm.svc.event.AuditRecordFactory) AuditRecord(password.pwm.svc.event.AuditRecord) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 23 with PwmException

use of password.pwm.error.PwmException in project pwm by pwm-project.

the class StatisticsManager method init.

public void init(final PwmApplication pwmApplication) throws PwmException {
    for (final EpsStatistic type : EpsStatistic.values()) {
        for (final Statistic.EpsDuration duration : Statistic.EpsDuration.values()) {
            epsMeterMap.put(type.toString() + duration.toString(), new EventRateMeter(duration.getTimeDuration()));
        }
    }
    status = STATUS.OPENING;
    this.localDB = pwmApplication.getLocalDB();
    this.pwmApplication = pwmApplication;
    if (localDB == null) {
        LOGGER.error("LocalDB is not available, will remain closed");
        status = STATUS.CLOSED;
        return;
    }
    {
        final String storedCummulativeBundleStr = localDB.get(LocalDB.DB.PWM_STATS, DB_KEY_CUMULATIVE);
        if (storedCummulativeBundleStr != null && storedCummulativeBundleStr.length() > 0) {
            try {
                statsCummulative = StatisticsBundle.input(storedCummulativeBundleStr);
            } catch (Exception e) {
                LOGGER.warn("error loading saved stored statistics: " + e.getMessage());
            }
        }
    }
    {
        for (final EpsStatistic loopEpsType : EpsStatistic.values()) {
            for (final EpsStatistic loopEpsDuration : EpsStatistic.values()) {
                final String key = "EPS-" + loopEpsType.toString() + loopEpsDuration.toString();
                final String storedValue = localDB.get(LocalDB.DB.PWM_STATS, key);
                if (storedValue != null && storedValue.length() > 0) {
                    try {
                        final EventRateMeter eventRateMeter = JsonUtil.deserialize(storedValue, EventRateMeter.class);
                        epsMeterMap.put(loopEpsType.toString() + loopEpsDuration.toString(), eventRateMeter);
                    } catch (Exception e) {
                        LOGGER.error("unexpected error reading last EPS rate for " + loopEpsType + " from LocalDB: " + e.getMessage());
                    }
                }
            }
        }
    }
    {
        final String storedInitialString = localDB.get(LocalDB.DB.PWM_STATS, DB_KEY_INITIAL_DAILY_KEY);
        if (storedInitialString != null && storedInitialString.length() > 0) {
            initialDailyKey = new DailyKey(storedInitialString);
        }
    }
    {
        currentDailyKey = new DailyKey(new Date());
        final String storedDailyStr = localDB.get(LocalDB.DB.PWM_STATS, currentDailyKey.toString());
        if (storedDailyStr != null && storedDailyStr.length() > 0) {
            statsDaily = StatisticsBundle.input(storedDailyStr);
        }
    }
    try {
        localDB.put(LocalDB.DB.PWM_STATS, DB_KEY_TEMP, JavaHelper.toIsoDate(new Date()));
    } catch (IllegalStateException e) {
        LOGGER.error("unable to write to localDB, will remain closed, error: " + e.getMessage());
        status = STATUS.CLOSED;
        return;
    }
    localDB.put(LocalDB.DB.PWM_STATS, DB_KEY_VERSION, DB_VALUE_VERSION);
    localDB.put(LocalDB.DB.PWM_STATS, DB_KEY_INITIAL_DAILY_KEY, initialDailyKey.toString());
    {
        // setup a timer to roll over at 0 Zula and one to write current stats every 10 seconds
        executorService = JavaHelper.makeSingleThreadExecutorService(pwmApplication, this.getClass());
        executorService.scheduleAtFixedRate(new FlushTask(), 10 * 1000, DB_WRITE_FREQUENCY.getTotalMilliseconds(), TimeUnit.MILLISECONDS);
        final TimeDuration delayTillNextZulu = TimeDuration.fromCurrent(JavaHelper.nextZuluZeroTime());
        executorService.scheduleAtFixedRate(new NightlyTask(), delayTillNextZulu.getTotalMilliseconds(), TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS);
    }
    status = STATUS.OPEN;
}
Also used : TimeDuration(password.pwm.util.java.TimeDuration) LocalDBException(password.pwm.util.localdb.LocalDBException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException) Date(java.util.Date)

Example 24 with PwmException

use of password.pwm.error.PwmException in project pwm by pwm-project.

the class TelemetryService method executePublishJob.

private void executePublishJob() throws PwmUnrecoverableException, IOException, URISyntaxException {
    final String authValue = pwmApplication.getStatisticsManager().getStatBundleForKey(StatisticsManager.KEY_CUMULATIVE).getStatistic(Statistic.AUTHENTICATIONS);
    if (StringUtil.isEmpty(authValue) || Integer.parseInt(authValue) < settings.getMinimumAuthentications()) {
        LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "skipping telemetry send, authentication count is too low");
    } else {
        try {
            final TelemetryPublishBean telemetryPublishBean = generatePublishableBean();
            sender.publish(telemetryPublishBean);
            LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "sent telemetry data: " + JsonUtil.serialize(telemetryPublishBean));
        } catch (PwmException e) {
            lastError = e.getErrorInformation();
            LOGGER.error(SessionLabel.TELEMETRY_SESSION_LABEL, "error sending telemetry data: " + e.getMessage());
        }
    }
    lastPublishTime = Instant.now();
    pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.TELEMETRY_LAST_PUBLISH_TIMESTAMP, lastPublishTime);
    scheduleNextJob();
}
Also used : PwmException(password.pwm.error.PwmException) TelemetryPublishBean(password.pwm.bean.TelemetryPublishBean)

Example 25 with PwmException

use of password.pwm.error.PwmException in project pwm by pwm-project.

the class OAuthMachine method makeHttpRequest.

private static PwmHttpClientResponse makeHttpRequest(final PwmRequest pwmRequest, final String debugText, final OAuthSettings settings, final String requestUrl, final Map<String, String> requestParams) throws PwmUnrecoverableException {
    final String requestBody = PwmURL.appendAndEncodeUrlParameters("", requestParams);
    final List<X509Certificate> certs = settings.getCertificates();
    final PwmHttpClientRequest pwmHttpClientRequest;
    {
        final Map<String, String> headers = new HashMap<>();
        headers.put(HttpHeader.Authorization.getHttpName(), new BasicAuthInfo(settings.getClientID(), settings.getSecret()).toAuthHeader());
        headers.put(HttpHeader.Content_Type.getHttpName(), HttpContentType.form.getHeaderValue());
        pwmHttpClientRequest = new PwmHttpClientRequest(HttpMethod.POST, requestUrl, requestBody, headers);
    }
    final PwmHttpClientResponse pwmHttpClientResponse;
    try {
        final PwmHttpClientConfiguration config = PwmHttpClientConfiguration.builder().certificates(JavaHelper.isEmpty(certs) ? null : certs).maskBodyDebugOutput(true).build();
        final PwmHttpClient pwmHttpClient = new PwmHttpClient(pwmRequest.getPwmApplication(), pwmRequest.getSessionLabel(), config);
        pwmHttpClientResponse = pwmHttpClient.makeRequest(pwmHttpClientRequest);
    } catch (PwmException e) {
        final String errorMsg = "error during " + debugText + " http request to oauth server, remote error: " + e.getErrorInformation().toDebugStr();
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg));
    }
    if (pwmHttpClientResponse.getStatusCode() != HttpStatus.SC_OK) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "unexpected HTTP status code (" + pwmHttpClientResponse.getStatusCode() + ") during " + debugText + " request to " + requestUrl));
    }
    return pwmHttpClientResponse;
}
Also used : PwmHttpClientRequest(password.pwm.http.client.PwmHttpClientRequest) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmHttpClientResponse(password.pwm.http.client.PwmHttpClientResponse) X509Certificate(java.security.cert.X509Certificate) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) PwmHttpClient(password.pwm.http.client.PwmHttpClient) PwmHttpClientConfiguration(password.pwm.http.client.PwmHttpClientConfiguration) BasicAuthInfo(password.pwm.util.BasicAuthInfo) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

PwmException (password.pwm.error.PwmException)63 ErrorInformation (password.pwm.error.ErrorInformation)42 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)38 IOException (java.io.IOException)19 PwmOperationalException (password.pwm.error.PwmOperationalException)19 PwmApplication (password.pwm.PwmApplication)16 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)13 UserIdentity (password.pwm.bean.UserIdentity)13 RestResultBean (password.pwm.ws.server.RestResultBean)13 ServletException (javax.servlet.ServletException)12 LinkedHashMap (java.util.LinkedHashMap)9 PwmSession (password.pwm.http.PwmSession)9 Instant (java.time.Instant)8 TimeDuration (password.pwm.util.java.TimeDuration)8 MacroMachine (password.pwm.util.macro.MacroMachine)8 Configuration (password.pwm.config.Configuration)7 PwmRequest (password.pwm.http.PwmRequest)7 UserInfo (password.pwm.ldap.UserInfo)7 PasswordData (password.pwm.util.PasswordData)7 ArrayList (java.util.ArrayList)6