Search in sources :

Example 31 with PwmException

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

the class UserSearchEngine method executeSearchJobs.

private Map<UserIdentity, Map<String, String>> executeSearchJobs(final Collection<UserSearchJob> userSearchJobs, final SessionLabel sessionLabel, final int searchID) throws PwmUnrecoverableException {
    // create jobs
    final List<JobInfo> jobs = new ArrayList<>();
    {
        int jobID = 0;
        for (UserSearchJob userSearchJob : userSearchJobs) {
            final int loopJobID = jobID++;
            final FutureTask<Map<UserIdentity, Map<String, String>>> futureTask = new FutureTask<>(() -> executeSearch(userSearchJob, sessionLabel, searchID, loopJobID));
            final JobInfo jobInfo = new JobInfo(searchID, loopJobID, userSearchJob, futureTask);
            jobs.add(jobInfo);
        }
    }
    final Instant startTime = Instant.now();
    {
        final String filterText = jobs.isEmpty() ? "" : ", filter: " + jobs.iterator().next().getUserSearchJob().getSearchFilter();
        log(PwmLogLevel.DEBUG, sessionLabel, searchID, -1, "beginning user search process with " + jobs.size() + " search jobs" + filterText);
    }
    // execute jobs
    for (Iterator<JobInfo> iterator = jobs.iterator(); iterator.hasNext(); ) {
        final JobInfo jobInfo = iterator.next();
        boolean submittedToExecutor = false;
        // use current thread to execute one (the last in the loop) task.
        if (executor != null && iterator.hasNext()) {
            try {
                executor.submit(jobInfo.getFutureTask());
                submittedToExecutor = true;
                backgroundJobCounter.incrementAndGet();
            } catch (RejectedExecutionException e) {
                // executor is full, so revert to running locally
                rejectionJobCounter.incrementAndGet();
            }
        }
        if (!submittedToExecutor) {
            try {
                jobInfo.getFutureTask().run();
                foregroundJobCounter.incrementAndGet();
            } catch (Throwable t) {
                log(PwmLogLevel.ERROR, sessionLabel, searchID, jobInfo.getJobID(), "unexpected error running job in local thread: " + t.getMessage());
            }
        }
    }
    // aggregate results
    final Map<UserIdentity, Map<String, String>> results = new LinkedHashMap<>();
    for (final JobInfo jobInfo : jobs) {
        if (results.size() > jobInfo.getUserSearchJob().getMaxResults()) {
            final FutureTask futureTask = jobInfo.getFutureTask();
            if (!futureTask.isDone()) {
                canceledJobCounter.incrementAndGet();
            }
            jobInfo.getFutureTask().cancel(false);
        } else {
            final long maxWaitTime = jobInfo.getUserSearchJob().getTimeoutMs() * 3;
            try {
                results.putAll(jobInfo.getFutureTask().get(maxWaitTime, TimeUnit.MILLISECONDS));
            } catch (InterruptedException e) {
                final String errorMsg = "unexpected interruption during search job execution: " + e.getMessage();
                log(PwmLogLevel.WARN, sessionLabel, searchID, jobInfo.getJobID(), errorMsg);
                LOGGER.error(sessionLabel, errorMsg, e);
                throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg));
            } catch (ExecutionException e) {
                final Throwable t = e.getCause();
                final ErrorInformation errorInformation;
                final String errorMsg = "unexpected error during ldap search (" + "profile=" + jobInfo.getUserSearchJob().getLdapProfile().getIdentifier() + ")" + ", error: " + (t instanceof PwmException ? t.getMessage() : JavaHelper.readHostileExceptionMessage(t));
                if (t instanceof PwmException) {
                    errorInformation = new ErrorInformation(((PwmException) t).getError(), errorMsg);
                } else {
                    errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
                }
                log(PwmLogLevel.WARN, sessionLabel, searchID, jobInfo.getJobID(), "error during user search: " + errorInformation.toDebugStr());
                throw new PwmUnrecoverableException(errorInformation);
            } catch (TimeoutException e) {
                final String errorMsg = "background search job timeout after " + jobInfo.getUserSearchJob().getTimeoutMs() + "ms, to ldapProfile '" + jobInfo.getUserSearchJob().getLdapProfile() + "'";
                log(PwmLogLevel.WARN, sessionLabel, searchID, jobInfo.getJobID(), "error during user search: " + errorMsg);
                jobTimeoutCounter.incrementAndGet();
            }
        }
    }
    log(PwmLogLevel.DEBUG, sessionLabel, searchID, -1, "completed user search process in " + TimeDuration.fromCurrent(startTime).asCompactString() + ", intermediate result size=" + results.size());
    return Collections.unmodifiableMap(results);
}
Also used : UserIdentity(password.pwm.bean.UserIdentity) Instant(java.time.Instant) ArrayList(java.util.ArrayList) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) LinkedHashMap(java.util.LinkedHashMap) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) FutureTask(java.util.concurrent.FutureTask) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) TimeoutException(java.util.concurrent.TimeoutException)

Example 32 with PwmException

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

the class UserSearchEngine method resolveUsername.

public UserIdentity resolveUsername(final String username, final String context, final String profile, final SessionLabel sessionLabel) throws PwmUnrecoverableException, PwmOperationalException {
    // check if username is a key
    {
        UserIdentity inputIdentity = null;
        try {
            inputIdentity = UserIdentity.fromKey(username, pwmApplication);
        } catch (PwmException e) {
        /* input is not a userIdentity */
        }
        if (inputIdentity != null) {
            try {
                final ChaiUser theUser = pwmApplication.getProxiedChaiUser(inputIdentity);
                if (theUser.exists()) {
                    final String canonicalDN;
                    canonicalDN = theUser.readCanonicalDN();
                    return new UserIdentity(canonicalDN, inputIdentity.getLdapProfileID());
                }
            } catch (ChaiOperationException e) {
                throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_CANT_MATCH_USER, e.getMessage()));
            } catch (ChaiUnavailableException e) {
                throw PwmUnrecoverableException.fromChaiException(e);
            }
        }
    }
    try {
        // see if we need to do a contextless search.
        if (checkIfStringIsDN(username, sessionLabel)) {
            return resolveUserDN(username);
        } else {
            final SearchConfiguration.SearchConfigurationBuilder builder = SearchConfiguration.builder();
            builder.username(username);
            if (context != null) {
                builder.contexts(Collections.singletonList(context));
            }
            if (profile != null) {
                builder.ldapProfile(profile);
            }
            final SearchConfiguration searchConfiguration = builder.build();
            return performSingleUserSearch(searchConfiguration, sessionLabel);
        }
    } catch (PwmOperationalException e) {
        throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_CANT_MATCH_USER, e.getErrorInformation().getDetailedErrorMsg(), e.getErrorInformation().getFieldValues()));
    } catch (ChaiUnavailableException e) {
        throw PwmUnrecoverableException.fromChaiException(e);
    }
}
Also used : PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) ChaiUser(com.novell.ldapchai.ChaiUser) UserIdentity(password.pwm.bean.UserIdentity) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 33 with PwmException

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

the class AuditService method init.

public void init(final PwmApplication pwmApplication) throws PwmException {
    this.status = STATUS.OPENING;
    this.pwmApplication = pwmApplication;
    settings = new AuditSettings(pwmApplication.getConfig());
    if (pwmApplication.getApplicationMode() == null || pwmApplication.getApplicationMode() == PwmApplicationMode.READ_ONLY) {
        this.status = STATUS.CLOSED;
        LOGGER.warn("unable to start - Application is in read-only mode");
        return;
    }
    if (pwmApplication.getLocalDB() == null || pwmApplication.getLocalDB().status() != LocalDB.Status.OPEN) {
        this.status = STATUS.CLOSED;
        LOGGER.warn("unable to start - LocalDB is not available");
        return;
    }
    final List<String> syslogConfigString = pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.AUDIT_SYSLOG_SERVERS);
    if (syslogConfigString != null && !syslogConfigString.isEmpty()) {
        try {
            syslogManager = new SyslogAuditService(pwmApplication);
        } catch (Exception e) {
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SYSLOG_WRITE_ERROR, "startup error: " + e.getMessage());
            LOGGER.error(errorInformation.toDebugStr());
        }
    }
    {
        final UserEventStorageMethod userEventStorageMethod = pwmApplication.getConfig().readSettingAsEnum(PwmSetting.EVENTS_USER_STORAGE_METHOD, UserEventStorageMethod.class);
        final String debugMsg;
        final DataStorageMethod storageMethodUsed;
        switch(userEventStorageMethod) {
            case AUTO:
                if (pwmApplication.getConfig().hasDbConfigured()) {
                    debugMsg = "starting using auto-configured data store, Remote Database selected";
                    this.userHistoryStore = new DatabaseUserHistory(pwmApplication);
                    storageMethodUsed = DataStorageMethod.DB;
                } else {
                    debugMsg = "starting using auto-configured data store, LDAP selected";
                    this.userHistoryStore = new LdapXmlUserHistory(pwmApplication);
                    storageMethodUsed = DataStorageMethod.LDAP;
                }
                break;
            case DATABASE:
                this.userHistoryStore = new DatabaseUserHistory(pwmApplication);
                debugMsg = "starting using Remote Database data store";
                storageMethodUsed = DataStorageMethod.DB;
                break;
            case LDAP:
                this.userHistoryStore = new LdapXmlUserHistory(pwmApplication);
                debugMsg = "starting using LocalDB data store";
                storageMethodUsed = DataStorageMethod.LDAP;
                break;
            default:
                lastError = new ErrorInformation(PwmError.ERROR_UNKNOWN, "unknown storageMethod selected: " + userEventStorageMethod);
                status = STATUS.CLOSED;
                return;
        }
        LOGGER.info(debugMsg);
        serviceInfo = new ServiceInfoBean(Collections.singletonList(storageMethodUsed));
    }
    {
        final TimeDuration maxRecordAge = new TimeDuration(pwmApplication.getConfig().readSettingAsLong(PwmSetting.EVENTS_AUDIT_MAX_AGE) * 1000);
        final long maxRecords = pwmApplication.getConfig().readSettingAsLong(PwmSetting.EVENTS_AUDIT_MAX_EVENTS);
        final AuditVault.Settings settings = new AuditVault.Settings(maxRecords, maxRecordAge);
        if (pwmApplication.getLocalDB() != null && pwmApplication.getApplicationMode() != PwmApplicationMode.READ_ONLY) {
            if (maxRecords < 1) {
                LOGGER.debug("localDB audit vault will remain closed due to max records setting");
                pwmApplication.getLocalDB().truncate(LocalDB.DB.AUDIT_EVENTS);
            } else {
                auditVault = new LocalDbAuditVault();
                auditVault.init(pwmApplication, pwmApplication.getLocalDB(), settings);
            }
        } else {
            LOGGER.debug("localDB audit vault will remain closed due to application mode");
        }
    }
    this.status = STATUS.OPEN;
}
Also used : UserEventStorageMethod(password.pwm.config.option.UserEventStorageMethod) DataStorageMethod(password.pwm.config.option.DataStorageMethod) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmException(password.pwm.error.PwmException) PwmOperationalException(password.pwm.error.PwmOperationalException) IOException(java.io.IOException) ErrorInformation(password.pwm.error.ErrorInformation) TimeDuration(password.pwm.util.java.TimeDuration)

Example 34 with PwmException

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

the class EmailService method sendItem.

private WorkQueueProcessor.ProcessResult sendItem(final EmailItemBean emailItemBean) {
    EmailConnection serverTransport = null;
    // create a new MimeMessage object (using the Session created above)
    try {
        if (threadLocalTransport.get() == null) {
            LOGGER.trace("initializing new threadLocal transport, stats: " + stats());
            threadLocalTransport.set(getSmtpTransport());
            newThreadLocalTransport.getAndIncrement();
        } else {
            LOGGER.trace("using existing threadLocal transport, stats: " + stats());
            useExistingTransport.getAndIncrement();
        }
        serverTransport = threadLocalTransport.get();
        if (!serverTransport.getTransport().isConnected()) {
            LOGGER.trace("connecting threadLocal transport, stats: " + stats());
            threadLocalTransport.set(getSmtpTransport());
            serverTransport = threadLocalTransport.get();
            newConnectionCounter.getAndIncrement();
        } else {
            LOGGER.trace("using existing threadLocal: stats: " + stats());
            useExistingConnection.getAndIncrement();
        }
        final List<Message> messages = EmailServerUtil.convertEmailItemToMessages(emailItemBean, this.pwmApplication.getConfig(), serverTransport.getEmailServer());
        for (final Message message : messages) {
            message.saveChanges();
            serverTransport.getTransport().sendMessage(message, message.getAllRecipients());
        }
        serverErrors.put(serverTransport.getEmailServer(), Optional.empty());
        LOGGER.debug("sent email: " + emailItemBean.toDebugString());
        StatisticsManager.incrementStat(pwmApplication, Statistic.EMAIL_SEND_SUCCESSES);
        return WorkQueueProcessor.ProcessResult.SUCCESS;
    } catch (MessagingException | PwmException e) {
        final ErrorInformation errorInformation;
        if (e instanceof PwmException) {
            errorInformation = ((PwmException) e).getErrorInformation();
        } else {
            final String errorMsg = "error sending email: " + e.getMessage();
            errorInformation = new ErrorInformation(PwmError.ERROR_EMAIL_SEND_FAILURE, errorMsg, new String[] { emailItemBean.toDebugString(), JavaHelper.readHostileExceptionMessage(e) });
        }
        if (serverTransport != null) {
            serverErrors.put(serverTransport.getEmailServer(), Optional.of(errorInformation));
        }
        LOGGER.error(errorInformation);
        if (EmailServerUtil.sendIsRetryable(e)) {
            LOGGER.error("error sending email (" + e.getMessage() + ") " + emailItemBean.toDebugString() + ", will retry");
            StatisticsManager.incrementStat(pwmApplication, Statistic.EMAIL_SEND_FAILURES);
            return WorkQueueProcessor.ProcessResult.RETRY;
        } else {
            LOGGER.error("error sending email (" + e.getMessage() + ") " + emailItemBean.toDebugString() + ", permanent failure, discarding message");
            StatisticsManager.incrementStat(pwmApplication, Statistic.EMAIL_SEND_DISCARDS);
            return WorkQueueProcessor.ProcessResult.FAILED;
        }
    }
}
Also used : PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) Message(javax.mail.Message) HealthMessage(password.pwm.health.HealthMessage) MessagingException(javax.mail.MessagingException)

Example 35 with PwmException

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

the class TokenService method processUserEnteredCode.

public TokenPayload processUserEnteredCode(final PwmSession pwmSession, final UserIdentity sessionUserIdentity, final TokenType tokenType, final String userEnteredCode, final TokenEntryType tokenEntryType) throws PwmOperationalException, PwmUnrecoverableException {
    try {
        final TokenPayload tokenPayload = processUserEnteredCodeImpl(pwmSession, sessionUserIdentity, tokenType, userEnteredCode);
        if (tokenPayload.getDestination() != null && !StringUtil.isEmpty(tokenPayload.getDestination().getValue())) {
            pwmApplication.getIntruderManager().clear(RecordType.TOKEN_DEST, tokenPayload.getDestination().getValue());
        }
        markTokenAsClaimed(tokenMachine.keyFromKey(userEnteredCode), pwmSession, tokenPayload);
        return tokenPayload;
    } catch (Exception e) {
        final ErrorInformation errorInformation;
        if (e instanceof PwmException) {
            errorInformation = ((PwmException) e).getErrorInformation();
        } else {
            errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, e.getMessage());
        }
        LOGGER.debug(pwmSession, errorInformation.toDebugStr());
        if (sessionUserIdentity != null && tokenEntryType == TokenEntryType.unauthenticated) {
            final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, null);
            sessionAuthenticator.simulateBadPassword(sessionUserIdentity);
            pwmApplication.getIntruderManager().convenience().markUserIdentity(sessionUserIdentity, pwmSession);
        }
        pwmApplication.getIntruderManager().convenience().markAddressAndSession(pwmSession);
        pwmApplication.getStatisticsManager().incrementValue(Statistic.RECOVERY_FAILURES);
        throw new PwmOperationalException(errorInformation);
    }
}
Also used : PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) SessionAuthenticator(password.pwm.ldap.auth.SessionAuthenticator) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) PwmException(password.pwm.error.PwmException) PwmOperationalException(password.pwm.error.PwmOperationalException)

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