Search in sources :

Example 56 with PwmApplication

use of password.pwm.PwmApplication in project pwm by pwm-project.

the class MainClass method loadPwmApplication.

private static PwmApplication loadPwmApplication(final File applicationPath, final Collection<PwmEnvironment.ApplicationFlag> flags, final Configuration config, final File configurationFile, final boolean readonly) throws LocalDBException, PwmUnrecoverableException {
    final PwmApplicationMode mode = readonly ? PwmApplicationMode.READ_ONLY : PwmApplicationMode.RUNNING;
    final Collection<PwmEnvironment.ApplicationFlag> applicationFlags = new HashSet<>();
    if (flags == null) {
        applicationFlags.addAll(PwmEnvironment.ParseHelper.readApplicationFlagsFromSystem(null));
    } else {
        applicationFlags.addAll(flags);
    }
    applicationFlags.add(PwmEnvironment.ApplicationFlag.CommandLineInstance);
    final PwmEnvironment pwmEnvironment = new PwmEnvironment.Builder(config, applicationPath).setApplicationMode(mode).setConfigurationFile(configurationFile).setFlags(applicationFlags).createPwmEnvironment();
    final PwmApplication pwmApplication = new PwmApplication(pwmEnvironment);
    final PwmApplicationMode runningMode = pwmApplication.getApplicationMode();
    if (runningMode != mode) {
        out("unable to start application in required state '" + mode + "', current state: " + runningMode);
        System.exit(-1);
    }
    return pwmApplication;
}
Also used : PwmApplication(password.pwm.PwmApplication) PwmEnvironment(password.pwm.PwmEnvironment) PwmApplicationMode(password.pwm.PwmApplicationMode) HashSet(java.util.HashSet)

Example 57 with PwmApplication

use of password.pwm.PwmApplication in project pwm by pwm-project.

the class ExportAuditCommand method doCommand.

@Override
void doCommand() throws Exception {
    final PwmApplication pwmApplication = cliEnvironment.getPwmApplication();
    final AuditService auditManager = new AuditService();
    auditManager.init(pwmApplication);
    JavaHelper.pause(1000);
    final File outputFile = (File) cliEnvironment.getOptions().get(CliParameters.REQUIRED_NEW_OUTPUT_FILE.getName());
    final Instant startTime = Instant.now();
    out("beginning output to " + outputFile.getAbsolutePath());
    final int counter;
    try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile, true)) {
        counter = auditManager.outputVaultToCsv(fileOutputStream, PwmConstants.DEFAULT_LOCALE, false);
        fileOutputStream.close();
    }
    out("completed writing " + counter + " rows of audit output in " + TimeDuration.fromCurrent(startTime).asLongString());
}
Also used : PwmApplication(password.pwm.PwmApplication) Instant(java.time.Instant) FileOutputStream(java.io.FileOutputStream) AuditService(password.pwm.svc.event.AuditService) File(java.io.File)

Example 58 with PwmApplication

use of password.pwm.PwmApplication in project pwm by pwm-project.

the class CASFilterAuthenticationProvider method authUserUsingCASClearPass.

private static boolean authUserUsingCASClearPass(final PwmRequest pwmRequest) throws UnsupportedEncodingException, PwmUnrecoverableException, ChaiUnavailableException, PwmOperationalException {
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final HttpSession session = pwmRequest.getHttpServletRequest().getSession();
    // make sure user session isn't already authenticated
    if (pwmSession.isAuthenticated()) {
        return false;
    }
    // read CAS assertion out of the header (if it exists);
    final Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
    if (assertion == null) {
        LOGGER.trace(pwmSession, "no CAS assertion header present, skipping CAS authentication attempt");
        return false;
    }
    final String username = assertion.getPrincipal().getName();
    PasswordData password = null;
    final AttributePrincipal attributePrincipal = assertion.getPrincipal();
    final Map<String, Object> casAttributes = attributePrincipal.getAttributes();
    final String encodedPsw = (String) casAttributes.get("credential");
    if (encodedPsw == null) {
        LOGGER.trace("No credential");
    } else {
        final Map<FileInformation, FileContent> privatekey = pwmRequest.getConfig().readSettingAsFile(PwmSetting.CAS_CLEARPASS_KEY);
        final String alg = pwmRequest.getConfig().readSettingAsString(PwmSetting.CAS_CLEARPASS_ALGORITHM);
        password = decryptPassword(alg, privatekey, encodedPsw);
    }
    // If using the old method
    final String clearPassUrl = pwmRequest.getConfig().readSettingAsString(PwmSetting.CAS_CLEAR_PASS_URL);
    if ((clearPassUrl != null && clearPassUrl.length() > 0) && (password == null || password.getStringValue().length() < 1)) {
        LOGGER.trace(pwmSession, "Using CAS clearpass via proxy");
        // read cas proxy ticket
        final String proxyTicket = assertion.getPrincipal().getProxyTicketFor(clearPassUrl);
        if (proxyTicket == null) {
            LOGGER.trace(pwmSession, "no CAS proxy ticket available, skipping CAS authentication attempt");
            return false;
        }
        final String clearPassRequestUrl = clearPassUrl + "?" + "ticket=" + proxyTicket + "&" + "service=" + StringUtil.urlEncode(clearPassUrl);
        try {
            final String response = CommonUtils.getResponseFromServer(new URL(clearPassRequestUrl), new HttpsURLConnectionFactory(), "UTF-8");
            password = new PasswordData(XmlUtils.getTextForElement(response, "credentials"));
        } catch (MalformedURLException e) {
            LOGGER.error(pwmSession, "Invalid CAS clearPassUrl");
        }
    }
    if (password == null || password.getStringValue().length() < 1) {
        final String errorMsg = "CAS server did not return credentials for user '" + username + "'";
        LOGGER.trace(pwmSession, errorMsg);
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_WRONGPASSWORD, errorMsg);
        throw new PwmOperationalException(errorInformation);
    }
    // user isn't already authenticated and has CAS assertion and password, so try to auth them.
    LOGGER.debug(pwmSession, "attempting to authenticate user '" + username + "' using CAS assertion and password");
    final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.CAS);
    sessionAuthenticator.searchAndAuthenticateUser(username, password, null, null);
    return true;
}
Also used : PwmApplication(password.pwm.PwmApplication) MalformedURLException(java.net.MalformedURLException) FileInformation(password.pwm.config.value.FileValue.FileInformation) SessionAuthenticator(password.pwm.ldap.auth.SessionAuthenticator) HttpSession(javax.servlet.http.HttpSession) Assertion(org.jasig.cas.client.validation.Assertion) URL(java.net.URL) PwmOperationalException(password.pwm.error.PwmOperationalException) FileContent(password.pwm.config.value.FileValue.FileContent) HttpsURLConnectionFactory(org.jasig.cas.client.ssl.HttpsURLConnectionFactory) ErrorInformation(password.pwm.error.ErrorInformation) PwmSession(password.pwm.http.PwmSession) AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal)

Example 59 with PwmApplication

use of password.pwm.PwmApplication in project pwm by pwm-project.

the class ExportResponsesCommand method doCommand.

@Override
void doCommand() throws Exception {
    final PwmApplication pwmApplication = cliEnvironment.getPwmApplication();
    final File outputFile = (File) cliEnvironment.getOptions().get(CliParameters.REQUIRED_NEW_OUTPUT_FILE.getName());
    JavaHelper.pause(2000);
    final long startTime = System.currentTimeMillis();
    final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
    final SearchConfiguration searchConfiguration = SearchConfiguration.builder().enableValueEscaping(false).username("*").build();
    final String systemRecordDelimiter = System.getProperty("line.separator");
    final Writer writer = new BufferedWriter(new PrintWriter(outputFile, PwmConstants.DEFAULT_CHARSET.toString()));
    final Map<UserIdentity, Map<String, String>> results = userSearchEngine.performMultiUserSearch(searchConfiguration, Integer.MAX_VALUE, Collections.emptyList(), SessionLabel.SYSTEM_LABEL);
    out("searching " + results.size() + " users for stored responses to write to " + outputFile.getAbsolutePath() + "....");
    int counter = 0;
    for (final UserIdentity identity : results.keySet()) {
        final ChaiUser user = pwmApplication.getProxiedChaiUser(identity);
        final ResponseSet responseSet = pwmApplication.getCrService().readUserResponseSet(null, identity, user);
        if (responseSet != null) {
            counter++;
            out("found responses for '" + user + "', writing to output.");
            final RestChallengesServer.JsonChallengesData outputData = new RestChallengesServer.JsonChallengesData();
            outputData.challenges = responseSet.asChallengeBeans(true);
            outputData.helpdeskChallenges = responseSet.asHelpdeskChallengeBeans(true);
            outputData.minimumRandoms = responseSet.getChallengeSet().minimumResponses();
            outputData.username = identity.toDelimitedKey();
            writer.write(JsonUtil.serialize(outputData));
            writer.write(systemRecordDelimiter);
        } else {
            out("skipping '" + user.toString() + "', no stored responses.");
        }
    }
    writer.close();
    out("output complete, " + counter + " responses exported in " + TimeDuration.fromCurrent(startTime).asCompactString());
}
Also used : PwmApplication(password.pwm.PwmApplication) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserIdentity(password.pwm.bean.UserIdentity) ResponseSet(com.novell.ldapchai.cr.ResponseSet) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) BufferedWriter(java.io.BufferedWriter) ChaiUser(com.novell.ldapchai.ChaiUser) RestChallengesServer(password.pwm.ws.server.rest.RestChallengesServer) File(java.io.File) Map(java.util.Map) PrintWriter(java.io.PrintWriter) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Example 60 with PwmApplication

use of password.pwm.PwmApplication in project pwm by pwm-project.

the class ResourceFileServlet method processAction.

@SuppressWarnings("checkstyle:MethodLength")
protected void processAction(final PwmRequest pwmRequest) throws ServletException, IOException, PwmUnrecoverableException {
    if (pwmRequest.getMethod() != HttpMethod.GET) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_SERVICE_NOT_AVAILABLE, "unable to process resource request for request method " + pwmRequest.getMethod()));
    }
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final ResourceServletService resourceService = pwmApplication.getResourceServletService();
    final ResourceServletConfiguration resourceConfiguration = resourceService.getResourceServletConfiguration();
    final String requestURI = stripNonceFromURI(resourceConfiguration, figureRequestPathMinusContext(pwmRequest.getHttpServletRequest()));
    try {
        if (handleEmbeddedURIs(pwmApplication, requestURI, pwmRequest.getPwmResponse().getHttpServletResponse(), resourceConfiguration)) {
            return;
        }
    } catch (Exception e) {
        LOGGER.error(pwmRequest, "unexpected error detecting/handling special request uri: " + e.getMessage());
    }
    final FileResource file;
    try {
        file = resolveRequestedFile(this.getServletContext(), requestURI, resourceConfiguration);
    } catch (PwmUnrecoverableException e) {
        pwmRequest.getPwmResponse().getHttpServletResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        try {
            pwmRequest.debugHttpRequestToLog("returning HTTP 500 status");
        } catch (PwmUnrecoverableException e2) {
        /* noop */
        }
        return;
    }
    if (file == null || !file.exists()) {
        pwmRequest.getPwmResponse().getHttpServletResponse().sendError(HttpServletResponse.SC_NOT_FOUND);
        try {
            pwmRequest.debugHttpRequestToLog("returning HTTP 404 status");
        } catch (PwmUnrecoverableException e) {
        /* noop */
        }
        return;
    }
    // Get content type by file name and set default GZIP support and content disposition.
    String contentType = getMimeType(file.getName());
    boolean acceptsGzip = false;
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }
    // the browser and expand content type with the one and right character encoding.
    if (resourceConfiguration.isEnableGzip()) {
        if (contentType.startsWith("text") || contentType.contains("javascript")) {
            final String acceptEncoding = pwmRequest.readHeaderValueAsString(HttpHeader.Accept_Encoding);
            acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
            contentType += ";charset=UTF-8";
        }
    }
    final HttpServletResponse response = pwmRequest.getPwmResponse().getHttpServletResponse();
    final String eTagValue = resourceConfiguration.getNonceValue();
    {
        // reply back with etag.
        final String ifNoneMatchValue = pwmRequest.readHeaderValueAsString(HttpHeader.If_None_Match);
        if (ifNoneMatchValue != null && ifNoneMatchValue.equals(eTagValue)) {
            response.reset();
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            try {
                pwmRequest.debugHttpRequestToLog("returning HTTP 304 status");
            } catch (PwmUnrecoverableException e2) {
            /* noop */
            }
            return;
        }
    }
    // Initialize response.
    addExpirationHeaders(resourceConfiguration, response);
    response.setHeader("ETag", resourceConfiguration.getNonceValue());
    response.setContentType(contentType);
    try {
        boolean fromCache = false;
        StringBuilder debugText = new StringBuilder();
        try {
            fromCache = handleCacheableResponse(resourceConfiguration, response, file, acceptsGzip, resourceService.getCacheMap());
            if (fromCache || acceptsGzip) {
                debugText.append("(");
                if (fromCache) {
                    debugText.append("cached");
                }
                if (fromCache && acceptsGzip) {
                    debugText.append(", ");
                }
                if (acceptsGzip) {
                    debugText.append("gzip");
                }
                debugText.append(")");
            } else {
                debugText = new StringBuilder("(not cached)");
            }
            StatisticsManager.incrementStat(pwmApplication, Statistic.HTTP_RESOURCE_REQUESTS);
        } catch (UncacheableResourceException e) {
            handleUncachedResponse(response, file, acceptsGzip);
            debugText = new StringBuilder();
            debugText.append("(uncacheable");
            if (acceptsGzip) {
                debugText.append(", gzip");
            }
            debugText.append(")");
        }
        try {
            pwmRequest.debugHttpRequestToLog(debugText.toString());
        } catch (PwmUnrecoverableException e) {
        /* noop */
        }
        final EventRateMeter.MovingAverage cacheHitRatio = resourceService.getCacheHitRatio();
        cacheHitRatio.update(fromCache ? 1 : 0);
    } catch (Exception e) {
        LOGGER.error(pwmRequest, "error fulfilling response for url '" + requestURI + "', error: " + e.getMessage());
    }
}
Also used : PwmApplication(password.pwm.PwmApplication) HttpServletResponse(javax.servlet.http.HttpServletResponse) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) EventRateMeter(password.pwm.svc.stats.EventRateMeter) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) IOException(java.io.IOException) ErrorInformation(password.pwm.error.ErrorInformation)

Aggregations

PwmApplication (password.pwm.PwmApplication)120 PwmSession (password.pwm.http.PwmSession)55 ErrorInformation (password.pwm.error.ErrorInformation)54 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)49 PwmOperationalException (password.pwm.error.PwmOperationalException)36 Configuration (password.pwm.config.Configuration)33 UserIdentity (password.pwm.bean.UserIdentity)27 FormConfiguration (password.pwm.config.value.data.FormConfiguration)25 PwmException (password.pwm.error.PwmException)25 IOException (java.io.IOException)22 ServletException (javax.servlet.ServletException)18 UserInfo (password.pwm.ldap.UserInfo)18 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)17 ChaiUser (com.novell.ldapchai.ChaiUser)16 Locale (java.util.Locale)13 ActionConfiguration (password.pwm.config.value.data.ActionConfiguration)13 SearchConfiguration (password.pwm.ldap.search.SearchConfiguration)13 MacroMachine (password.pwm.util.macro.MacroMachine)12 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)11 Instant (java.time.Instant)10