Search in sources :

Example 91 with ErrorInformation

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

the class ConfigEditorServlet method restFinishEditing.

@ActionHandler(action = "finishEditing")
private ProcessStatus restFinishEditing(final PwmRequest pwmRequest) throws IOException, ServletException, PwmUnrecoverableException {
    final ConfigManagerBean configManagerBean = getBean(pwmRequest);
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final List<String> validationErrors = configManagerBean.getStoredConfiguration().validateValues();
    if (!validationErrors.isEmpty()) {
        final String errorString = validationErrors.get(0);
        final ErrorInformation errorInfo = new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, errorString, new String[] { errorString });
        pwmRequest.outputJsonResult(RestResultBean.fromError(errorInfo, pwmRequest));
        LOGGER.error(pwmSession, errorInfo);
        return ProcessStatus.Halt;
    } else {
        try {
            ConfigManagerServlet.saveConfiguration(pwmRequest, configManagerBean.getStoredConfiguration());
            configManagerBean.setConfiguration(null);
            configManagerBean.setConfiguration(null);
            LOGGER.debug(pwmSession, "save configuration operation completed");
            pwmRequest.outputJsonResult(RestResultBean.forSuccessMessage(pwmRequest, Message.Success_Unknown));
        } catch (PwmUnrecoverableException e) {
            final ErrorInformation errorInfo = e.getErrorInformation();
            pwmRequest.outputJsonResult(RestResultBean.fromError(errorInfo, pwmRequest));
            LOGGER.error(pwmSession, errorInfo);
        }
    }
    return ProcessStatus.Halt;
}
Also used : ConfigManagerBean(password.pwm.http.bean.ConfigManagerBean) ErrorInformation(password.pwm.error.ErrorInformation) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmSession(password.pwm.http.PwmSession)

Example 92 with ErrorInformation

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

the class ConfigGuideUtils method writeConfig.

static void writeConfig(final ContextManager contextManager, final StoredConfigurationImpl storedConfiguration) throws PwmOperationalException, PwmUnrecoverableException {
    final ConfigurationReader configReader = contextManager.getConfigReader();
    final PwmApplication pwmApplication = contextManager.getPwmApplication();
    try {
        // add a random security key
        storedConfiguration.initNewRandomSecurityKey();
        configReader.saveConfiguration(storedConfiguration, pwmApplication, null);
        contextManager.requestPwmApplicationRestart();
    } catch (PwmException e) {
        throw new PwmOperationalException(e.getErrorInformation());
    } catch (Exception e) {
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_INVALID_CONFIG, "unable to save configuration: " + e.getLocalizedMessage());
        throw new PwmOperationalException(errorInformation);
    }
}
Also used : PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) PwmApplication(password.pwm.PwmApplication) ConfigurationReader(password.pwm.config.stored.ConfigurationReader) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmException(password.pwm.error.PwmException) PwmOperationalException(password.pwm.error.PwmOperationalException) IOException(java.io.IOException) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 93 with ErrorInformation

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

the class ConfigGuideUtils method restUploadConfig.

public static void restUploadConfig(final PwmRequest pwmRequest) throws PwmUnrecoverableException, IOException, ServletException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final HttpServletRequest req = pwmRequest.getHttpServletRequest();
    if (pwmApplication.getApplicationMode() == PwmApplicationMode.RUNNING) {
        final String errorMsg = "config upload is not permitted when in running mode";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.CONFIG_UPLOAD_FAILURE, errorMsg, new String[] { errorMsg });
        pwmRequest.respondWithError(errorInformation, true);
    }
    if (ServletFileUpload.isMultipartContent(req)) {
        final InputStream uploadedFile = pwmRequest.readFileUploadStream(PwmConstants.PARAM_FILE_UPLOAD);
        if (uploadedFile != null) {
            try {
                final StoredConfigurationImpl storedConfig = StoredConfigurationImpl.fromXml(uploadedFile);
                final List<String> configErrors = storedConfig.validateValues();
                if (configErrors != null && !configErrors.isEmpty()) {
                    throw new PwmOperationalException(new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, configErrors.get(0)));
                }
                ConfigGuideUtils.writeConfig(ContextManager.getContextManager(req.getSession()), storedConfig);
                LOGGER.trace(pwmSession, "read config from file: " + storedConfig.toString());
                final RestResultBean restResultBean = RestResultBean.forSuccessMessage(pwmRequest, Message.Success_Unknown);
                pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
                req.getSession().invalidate();
            } catch (PwmException e) {
                final RestResultBean restResultBean = RestResultBean.fromError(e.getErrorInformation(), pwmRequest);
                pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
                LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr());
            }
        } else {
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.CONFIG_UPLOAD_FAILURE, "error reading config file: no file present in upload");
            final RestResultBean restResultBean = RestResultBean.fromError(errorInformation, pwmRequest);
            pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
            LOGGER.error(pwmSession, errorInformation.toDebugStr());
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) PwmApplication(password.pwm.PwmApplication) StoredConfigurationImpl(password.pwm.config.stored.StoredConfigurationImpl) InputStream(java.io.InputStream) PwmSession(password.pwm.http.PwmSession) PwmOperationalException(password.pwm.error.PwmOperationalException) RestResultBean(password.pwm.ws.server.RestResultBean)

Example 94 with ErrorInformation

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

the class SessionFilter method verifySession.

/**
 * Attempt to determine if user agent is able to track sessions (either via url rewriting or cookies).
 */
private static ProcessStatus verifySession(final PwmRequest pwmRequest, final SessionVerificationMode mode) throws IOException, ServletException, PwmUnrecoverableException {
    final LocalSessionStateBean ssBean = pwmRequest.getPwmSession().getSessionStateBean();
    final HttpServletRequest req = pwmRequest.getHttpServletRequest();
    final PwmResponse pwmResponse = pwmRequest.getPwmResponse();
    if (!pwmRequest.getMethod().isIdempotent() && pwmRequest.hasParameter(PwmConstants.PARAM_FORM_ID)) {
        LOGGER.debug(pwmRequest, "session is unvalidated but can not be validated during a " + pwmRequest.getMethod().toString() + " request, will allow");
        return ProcessStatus.Continue;
    }
    {
        final String acceptEncodingHeader = pwmRequest.getHttpServletRequest().getHeader(HttpHeader.Accept.getHttpName());
        if (acceptEncodingHeader != null && acceptEncodingHeader.contains("json")) {
            LOGGER.debug(pwmRequest, "session is unvalidated but can not be validated during a json request, will allow");
            return ProcessStatus.Continue;
        }
    }
    if (pwmRequest.getURL().isCommandServletURL()) {
        return ProcessStatus.Continue;
    }
    final String verificationParamName = pwmRequest.getConfig().readAppProperty(AppProperty.HTTP_PARAM_SESSION_VERIFICATION);
    final String keyFromRequest = pwmRequest.readParameterAsString(verificationParamName, PwmHttpRequestWrapper.Flag.BypassValidation);
    // request doesn't have key, so make a new one, store it in the session, and redirect back here with the new key.
    if (keyFromRequest == null || keyFromRequest.length() < 1) {
        final String returnURL = figureValidationURL(pwmRequest, ssBean.getSessionVerificationKey());
        LOGGER.trace(pwmRequest, "session has not been validated, redirecting with verification key to " + returnURL);
        // better chance of detecting un-sticky sessions this way
        pwmResponse.setHeader(HttpHeader.Connection, "close");
        if (mode == SessionVerificationMode.VERIFY_AND_CACHE) {
            req.setAttribute("Location", returnURL);
            pwmResponse.forwardToJsp(JspUrl.INIT);
        } else {
            pwmResponse.sendRedirect(returnURL);
        }
        return ProcessStatus.Halt;
    }
    // else, request has a key, so investigate.
    if (keyFromRequest.equals(ssBean.getSessionVerificationKey())) {
        final String returnURL = figureValidationURL(pwmRequest, null);
        // session looks, good, mark it as such and return;
        LOGGER.trace(pwmRequest, "session validated, redirecting to original request url: " + returnURL);
        ssBean.setSessionVerified(true);
        pwmRequest.getPwmResponse().sendRedirect(returnURL);
        return ProcessStatus.Halt;
    }
    // user's session is messed up.  send to error page.
    final String errorMsg = "client unable to reply with session key";
    final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_BAD_SESSION, errorMsg);
    LOGGER.error(pwmRequest, errorInformation);
    pwmRequest.respondWithError(errorInformation, true);
    return ProcessStatus.Halt;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ErrorInformation(password.pwm.error.ErrorInformation) PwmResponse(password.pwm.http.PwmResponse) LocalSessionStateBean(password.pwm.bean.LocalSessionStateBean)

Example 95 with ErrorInformation

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

the class SessionFilter method checkUrlAgainstWhitelist.

private static void checkUrlAgainstWhitelist(final PwmApplication pwmApplication, final SessionLabel sessionLabel, final String inputURL) throws PwmOperationalException {
    LOGGER.trace(sessionLabel, "beginning test of requested redirect URL: " + inputURL);
    if (inputURL == null || inputURL.isEmpty()) {
        return;
    }
    final URI inputURI;
    try {
        inputURI = URI.create(inputURL);
    } catch (IllegalArgumentException e) {
        LOGGER.error(sessionLabel, "unable to parse requested redirect url '" + inputURL + "', error: " + e.getMessage());
        // dont put input uri in error response
        final String errorMsg = "unable to parse url: " + e.getMessage();
        throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL, errorMsg));
    }
    {
        // check to make sure we werent handed a non-http uri.
        final String scheme = inputURI.getScheme();
        if (scheme != null && !scheme.isEmpty() && !"http".equalsIgnoreCase(scheme) && !"https".equals(scheme)) {
            final String errorMsg = "unsupported url scheme";
            throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL, errorMsg));
        }
    }
    if (inputURI.getHost() != null && !inputURI.getHost().isEmpty()) {
        // disallow localhost uri
        try {
            final InetAddress inetAddress = InetAddress.getByName(inputURI.getHost());
            if (inetAddress.isLoopbackAddress()) {
                final String errorMsg = "redirect to loopback host is not permitted";
                throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL, errorMsg));
            }
        } catch (UnknownHostException e) {
        /* noop */
        }
    }
    final StringBuilder sb = new StringBuilder();
    if (inputURI.getScheme() != null) {
        sb.append(inputURI.getScheme());
        sb.append("://");
    }
    if (inputURI.getHost() != null) {
        sb.append(inputURI.getHost());
    }
    if (inputURI.getPort() != -1) {
        sb.append(":");
        sb.append(inputURI.getPort());
    }
    if (inputURI.getPath() != null) {
        sb.append(inputURI.getPath());
    }
    final String testURI = sb.toString();
    LOGGER.trace(sessionLabel, "preparing to whitelist test parsed and decoded URL: " + testURI);
    final String regexPrefix = "regex:";
    final List<String> whiteList = pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.SECURITY_REDIRECT_WHITELIST);
    for (final String loopFragment : whiteList) {
        if (loopFragment.startsWith(regexPrefix)) {
            try {
                final String strPattern = loopFragment.substring(regexPrefix.length(), loopFragment.length());
                final Pattern pattern = Pattern.compile(strPattern);
                if (pattern.matcher(testURI).matches()) {
                    LOGGER.debug(sessionLabel, "positive URL match for regex pattern: " + strPattern);
                    return;
                } else {
                    LOGGER.trace(sessionLabel, "negative URL match for regex pattern: " + strPattern);
                }
            } catch (Exception e) {
                LOGGER.error(sessionLabel, "error while testing URL match for regex pattern: '" + loopFragment + "', error: " + e.getMessage());
            }
        } else {
            if (testURI.startsWith(loopFragment)) {
                LOGGER.debug(sessionLabel, "positive URL match for pattern: " + loopFragment);
                return;
            } else {
                LOGGER.trace(sessionLabel, "negative URL match for pattern: " + loopFragment);
            }
        }
    }
    final String errorMsg = testURI + " is not a match for any configured redirect whitelist, see setting: " + PwmSetting.SECURITY_REDIRECT_WHITELIST.toMenuLocationDebug(null, PwmConstants.DEFAULT_LOCALE);
    throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL, errorMsg));
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) Pattern(java.util.regex.Pattern) UnknownHostException(java.net.UnknownHostException) URI(java.net.URI) InetAddress(java.net.InetAddress) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) PwmOperationalException(password.pwm.error.PwmOperationalException)

Aggregations

ErrorInformation (password.pwm.error.ErrorInformation)325 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)216 PwmOperationalException (password.pwm.error.PwmOperationalException)125 PwmException (password.pwm.error.PwmException)67 UserIdentity (password.pwm.bean.UserIdentity)62 IOException (java.io.IOException)58 PwmApplication (password.pwm.PwmApplication)54 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)53 ChaiUser (com.novell.ldapchai.ChaiUser)38 PwmSession (password.pwm.http.PwmSession)38 LinkedHashMap (java.util.LinkedHashMap)35 Configuration (password.pwm.config.Configuration)33 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)32 Map (java.util.Map)32 Instant (java.time.Instant)30 ArrayList (java.util.ArrayList)30 FormConfiguration (password.pwm.config.value.data.FormConfiguration)29 ServletException (javax.servlet.ServletException)28 RestResultBean (password.pwm.ws.server.RestResultBean)26 UserInfo (password.pwm.ldap.UserInfo)23