void restUploadWordlist(final PwmRequest pwmRequest) throws IOException, ServletException, PwmUnrecoverableException { final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final HttpServletRequest req = pwmRequest.getHttpServletRequest(); if (!ServletFileUpload.isMultipartContent(req)) { final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, "no file found in upload"); pwmRequest.outputJsonResult(RestResultBean.fromError(errorInformation, pwmRequest)); LOGGER.error(pwmRequest, "error during import: " + errorInformation.toDebugStr()); return; } final InputStream inputStream = ServletHelper.readFileUpload(pwmRequest.getHttpServletRequest(), "uploadFile"); try { pwmApplication.getWordlistManager().populate(inputStream); } catch (PwmUnrecoverableException e) { final ErrorInformation errorInfo = new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage()); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmRequest, errorInfo.toDebugStr()); pwmRequest.outputJsonResult(restResultBean); return; } pwmRequest.outputJsonResult( RestResultBean.forSuccessMessage(pwmRequest, Message.Success_Unknown)); }
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() == PwmApplication.MODE.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); return; } if (ServletFileUpload.isMultipartContent(req)) { final InputStream uploadedFile = ServletHelper.readFileUpload(req, "uploadFile"); 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))); } writeConfig(ContextManager.getContextManager(req.getSession()), storedConfig); LOGGER.trace(pwmSession, "read config from file: " + storedConfig.toString()); final RestResultBean restResultBean = new RestResultBean(); restResultBean.setSuccessMessage("read message"); 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()); } } }
@GET @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Path("/client") public Response doGetAppClientData( @QueryParam("pageUrl") String pageUrl, @PathParam(value = "eTagUri") final String eTagUri, @Context HttpServletRequest request, @Context HttpServletResponse response) throws PwmUnrecoverableException, IOException, ChaiUnavailableException { final int maxCacheAgeSeconds = 60 * 5; final RestRequestBean restRequestBean; try { restRequestBean = RestServerHelper.initializeRestRequest( request, response, ServicePermissions.PUBLIC, null); } catch (PwmUnrecoverableException e) { return RestResultBean.fromError(e.getErrorInformation()).asJsonResponse(); } final String eTagValue = makeClientEtag( restRequestBean.getPwmApplication(), restRequestBean.getPwmSession(), request); // check the incoming header; final String ifNoneMatchValue = request.getHeader("If-None-Match"); if (ifNoneMatchValue != null && ifNoneMatchValue.equals(eTagValue) && eTagValue.equals(eTagUri)) { return Response.notModified().build(); } response.setHeader("ETag", eTagValue); response.setDateHeader("Expires", System.currentTimeMillis() + (maxCacheAgeSeconds * 1000)); response.setHeader("Cache-Control", "public, max-age=" + maxCacheAgeSeconds); final AppData appData = makeAppData( restRequestBean.getPwmApplication(), restRequestBean.getPwmSession(), request, response, pageUrl); final RestResultBean restResultBean = new RestResultBean(); restResultBean.setData(appData); return restResultBean.asJsonResponse(); }
@GET @Path("/audit") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public Response doGetAppAuditData(@QueryParam("maximum") int maximum) throws ChaiUnavailableException, PwmUnrecoverableException { maximum = maximum > 0 ? maximum : 10 * 1000; final RestRequestBean restRequestBean; try { final ServicePermissions servicePermissions = new ServicePermissions(); servicePermissions.setAdminOnly(true); servicePermissions.setAuthRequired(true); servicePermissions.setBlockExternal(true); restRequestBean = RestServerHelper.initializeRestRequest(request, response, servicePermissions, null); } catch (PwmUnrecoverableException e) { return RestResultBean.fromError(e.getErrorInformation()).asJsonResponse(); } final ArrayList<UserAuditRecord> userRecords = new ArrayList<>(); final ArrayList<HelpdeskAuditRecord> helpdeskRecords = new ArrayList<>(); final ArrayList<SystemAuditRecord> systemRecords = new ArrayList<>(); final Iterator<AuditRecord> iterator = restRequestBean.getPwmApplication().getAuditManager().readVault(); int counter = 0; while (iterator.hasNext() && counter <= maximum) { final AuditRecord loopRecord = iterator.next(); counter++; if (loopRecord instanceof SystemAuditRecord) { systemRecords.add((SystemAuditRecord) loopRecord); } else if (loopRecord instanceof HelpdeskAuditRecord) { helpdeskRecords.add((HelpdeskAuditRecord) loopRecord); } else if (loopRecord instanceof UserAuditRecord) { userRecords.add((UserAuditRecord) loopRecord); } } final HashMap<String, List> outputMap = new HashMap<>(); outputMap.put("user", userRecords); outputMap.put("helpdesk", helpdeskRecords); outputMap.put("system", systemRecords); final RestResultBean restResultBean = new RestResultBean(); restResultBean.setData(outputMap); LOGGER.debug(restRequestBean.getPwmSession(), "output " + counter + " audit records."); return restResultBean.asJsonResponse(); }
private void restExtendSchema(final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean) throws IOException { try { SchemaOperationResult schemaOperationResult = extendSchema(configGuideBean, true); pwmRequest.outputJsonResult(new RestResultBean(schemaOperationResult.getOperationLog())); } catch (Exception e) { ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage()); pwmRequest.outputJsonResult(RestResultBean.fromError(errorInformation, pwmRequest)); LOGGER.error(pwmRequest, e.getMessage(), e); } }
@GET @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Path("/strings/{bundle}") public Response doGetStringData(@PathParam(value = "bundle") final String bundleName) throws PwmUnrecoverableException, IOException, ChaiUnavailableException { final int maxCacheAgeSeconds = 60 * 5; final RestRequestBean restRequestBean; try { restRequestBean = RestServerHelper.initializeRestRequest( request, response, ServicePermissions.PUBLIC, null); } catch (PwmUnrecoverableException e) { return RestResultBean.fromError(e.getErrorInformation()).asJsonResponse(); } final String eTagValue = makeClientEtag( restRequestBean.getPwmApplication(), restRequestBean.getPwmSession(), request); response.setHeader("ETag", eTagValue); response.setDateHeader("Expires", System.currentTimeMillis() + (maxCacheAgeSeconds * 1000)); response.setHeader("Cache-Control", "public, max-age=" + maxCacheAgeSeconds); try { final LinkedHashMap<String, String> displayData = new LinkedHashMap<>( makeDisplayData( restRequestBean.getPwmApplication(), restRequestBean.getPwmSession(), bundleName)); final RestResultBean restResultBean = new RestResultBean(); restResultBean.setData(displayData); return restResultBean.asJsonResponse(); } catch (Exception e) { final String errorMSg = "error during rest /strings call for bundle " + bundleName + ", error: " + e.getMessage(); final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMSg); return RestResultBean.fromError(errorInformation).asJsonResponse(); } }
@GET @Path("/session") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public Response doGetAppSessionData(@QueryParam("maximum") int maximum) throws ChaiUnavailableException, PwmUnrecoverableException { maximum = maximum > 0 ? maximum : 10 * 1000; final RestRequestBean restRequestBean; try { final ServicePermissions servicePermissions = new ServicePermissions(); servicePermissions.setAdminOnly(true); servicePermissions.setAuthRequired(true); servicePermissions.setBlockExternal(true); restRequestBean = RestServerHelper.initializeRestRequest(request, response, servicePermissions, null); } catch (PwmUnrecoverableException e) { return RestResultBean.fromError(e.getErrorInformation()).asJsonResponse(); } if (!restRequestBean .getPwmSession() .getSessionManager() .checkPermission(restRequestBean.getPwmApplication(), Permission.PWMADMIN)) { final ErrorInformation errorInfo = PwmError.ERROR_UNAUTHORIZED.toInfo(); return RestResultBean.fromError(errorInfo, restRequestBean).asJsonResponse(); } final ArrayList<SessionStateInfoBean> gridData = new ArrayList<>(); int counter = 0; final Iterator<SessionStateInfoBean> infos = restRequestBean.getPwmApplication().getSessionTrackService().getSessionInfoIterator(); while (counter < maximum && infos.hasNext()) { gridData.add(infos.next()); counter++; } final RestResultBean restResultBean = new RestResultBean(); restResultBean.setData(gridData); return restResultBean.asJsonResponse(); }
@GET @Path("/intruder") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public Response doGetAppIntruderData(@QueryParam("maximum") int maximum) throws ChaiUnavailableException, PwmUnrecoverableException { maximum = maximum > 0 ? maximum : 10 * 1000; final RestRequestBean restRequestBean; try { final ServicePermissions servicePermissions = new ServicePermissions(); servicePermissions.setAdminOnly(true); servicePermissions.setAuthRequired(true); servicePermissions.setBlockExternal(true); restRequestBean = RestServerHelper.initializeRestRequest(request, response, servicePermissions, null); } catch (PwmUnrecoverableException e) { return RestResultBean.fromError(e.getErrorInformation()).asJsonResponse(); } if (!restRequestBean .getPwmSession() .getSessionManager() .checkPermission(restRequestBean.getPwmApplication(), Permission.PWMADMIN)) { final ErrorInformation errorInfo = PwmError.ERROR_UNAUTHORIZED.toInfo(); return RestResultBean.fromError(errorInfo, restRequestBean).asJsonResponse(); } final TreeMap<String, Object> returnData = new TreeMap<>(); try { for (final RecordType recordType : RecordType.values()) { returnData.put( recordType.toString(), restRequestBean .getPwmApplication() .getIntruderManager() .getRecords(recordType, maximum)); } } catch (PwmOperationalException e) { final ErrorInformation errorInfo = new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage()); return RestResultBean.fromError(errorInfo, restRequestBean).asJsonResponse(); } final RestResultBean restResultBean = new RestResultBean(); restResultBean.setData(returnData); return restResultBean.asJsonResponse(); }
private void restGotoStep(final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean) throws PwmUnrecoverableException, IOException, ServletException { final String requestedStep = pwmRequest.readParameterAsString("step"); STEP step = null; if (requestedStep != null && requestedStep.length() > 0) { try { step = STEP.valueOf(requestedStep); } catch (IllegalArgumentException e) { /* */ } } final boolean ldapSchemaPermitted = "LDAP".equals(configGuideBean.getFormData().get(PARAM_CR_STORAGE_PREF)) && configGuideBean.getSelectedTemplate() == PwmSettingTemplate.NOVL; if ("NEXT".equals(requestedStep)) { step = configGuideBean.getStep().next(); if (step == STEP.LDAP_SCHEMA && !ldapSchemaPermitted) { step = step.next(); } } else if ("PREVIOUS".equals(requestedStep)) { step = configGuideBean.getStep().previous(); if (step == STEP.LDAP_SCHEMA && !ldapSchemaPermitted) { step = step.previous(); } } if (step == null) { final String errorMsg = "unknown goto step request: " + requestedStep; final ErrorInformation errorInformation = new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, errorMsg); final RestResultBean restResultBean = RestResultBean.fromError(errorInformation, pwmRequest); LOGGER.error(pwmRequest, errorInformation.toDebugStr()); pwmRequest.outputJsonResult(restResultBean); return; } if (step == STEP.FINISH) { final ContextManager contextManager = ContextManager.getContextManager(pwmRequest); try { writeConfig(contextManager, configGuideBean); } catch (PwmException e) { final RestResultBean restResultBean = RestResultBean.fromError(e.getErrorInformation(), pwmRequest); pwmRequest.outputJsonResult(restResultBean); return; } catch (Exception e) { final RestResultBean restResultBean = RestResultBean.fromError( new ErrorInformation( PwmError.ERROR_UNKNOWN, "error during save: " + e.getMessage()), pwmRequest); pwmRequest.outputJsonResult(restResultBean); return; } final HashMap<String, String> resultData = new HashMap<>(); resultData.put("serverRestart", "true"); pwmRequest.outputJsonResult(new RestResultBean(resultData)); pwmRequest.invalidateSession(); } else { configGuideBean.setStep(step); pwmRequest.outputJsonResult(new RestResultBean()); LOGGER.trace("setting current step to: " + step); } }
private void restLdapHealth(final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean) throws IOException, PwmUnrecoverableException { final Configuration tempConfiguration = new Configuration(configGuideBean.getStoredConfiguration()); final PwmApplication tempApplication = new PwmApplication.PwmEnvironment( tempConfiguration, pwmRequest.getPwmApplication().getApplicationPath()) .setApplicationMode(PwmApplication.MODE.NEW) .setInternalRuntimeInstance(true) .setWebInfPath(pwmRequest.getPwmApplication().getWebInfPath()) .createPwmApplication(); final LDAPStatusChecker ldapStatusChecker = new LDAPStatusChecker(); final List<HealthRecord> records = new ArrayList<>(); final LdapProfile ldapProfile = tempConfiguration.getDefaultLdapProfile(); switch (configGuideBean.getStep()) { case LDAP_SERVER: { try { checkLdapServer(configGuideBean); records.add(password.pwm.health.HealthRecord.forMessage(HealthMessage.LDAP_OK)); } catch (Exception e) { records.add( new HealthRecord( HealthStatus.WARN, HealthTopic.LDAP, "Can not connect to remote server: " + e.getMessage())); } } break; case LDAP_ADMIN: { records.addAll( ldapStatusChecker.checkBasicLdapConnectivity( tempApplication, tempConfiguration, ldapProfile, false)); if (records.isEmpty()) { records.add(password.pwm.health.HealthRecord.forMessage(HealthMessage.LDAP_OK)); } } break; case LDAP_CONTEXT: { records.addAll( ldapStatusChecker.checkBasicLdapConnectivity( tempApplication, tempConfiguration, ldapProfile, true)); if (records.isEmpty()) { records.add( new HealthRecord( HealthStatus.GOOD, HealthTopic.LDAP, "LDAP Contextless Login Root validated")); } try { final UserMatchViewerFunction userMatchViewerFunction = new UserMatchViewerFunction(); final Collection<UserIdentity> results = userMatchViewerFunction.discoverMatchingUsers( pwmRequest.getPwmApplication(), 2, configGuideBean.getStoredConfiguration(), PwmSetting.QUERY_MATCH_PWM_ADMIN, null); if (results.isEmpty()) { records.add( new HealthRecord(HealthStatus.WARN, HealthTopic.LDAP, "No matching admin users")); } else { records.add( new HealthRecord(HealthStatus.GOOD, HealthTopic.LDAP, "Admin group validated")); } } catch (PwmException e) { records.add( new HealthRecord( HealthStatus.WARN, HealthTopic.LDAP, "Error during admin group validation: " + e.getErrorInformation().toDebugStr())); } catch (Exception e) { records.add( new HealthRecord( HealthStatus.WARN, HealthTopic.LDAP, "Error during admin group validation: " + e.getMessage())); } } break; case LDAP_TESTUSER: { final String testUserValue = configGuideBean.getFormData().get(PARAM_LDAP_TEST_USER); if (testUserValue != null && !testUserValue.isEmpty()) { records.addAll( ldapStatusChecker.checkBasicLdapConnectivity( tempApplication, tempConfiguration, ldapProfile, false)); records.addAll( ldapStatusChecker.doLdapTestUserCheck( tempConfiguration, ldapProfile, tempApplication)); } else { records.add( new HealthRecord(HealthStatus.CAUTION, HealthTopic.LDAP, "No test user specified")); } } break; } HealthData jsonOutput = new HealthData(); jsonOutput.records = password.pwm.ws.server.rest.bean.HealthRecord.fromHealthRecords( records, pwmRequest.getLocale(), tempConfiguration); jsonOutput.timestamp = new Date(); jsonOutput.overall = HealthMonitor.getMostSevereHealthStatus(records).toString(); final RestResultBean restResultBean = new RestResultBean(); restResultBean.setData(jsonOutput); pwmRequest.outputJsonResult(restResultBean); }
private void restLockConfiguration(final PwmRequest pwmRequest) throws IOException, ServletException, PwmUnrecoverableException, ChaiUnavailableException { final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final PwmSession pwmSession = pwmRequest.getPwmSession(); if (PwmConstants.TRIAL_MODE) { final ErrorInformation errorInfo = new ErrorInformation( PwmError.ERROR_TRIAL_VIOLATION, "configuration lock not available in trial"); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo); pwmRequest.outputJsonResult(restResultBean); return; } if (!pwmSession.isAuthenticated()) { final ErrorInformation errorInfo = new ErrorInformation( PwmError.ERROR_AUTHENTICATION_REQUIRED, "You must be authenticated before restricting the configuration"); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo); pwmRequest.outputJsonResult(restResultBean); return; } if (!pwmSession.getSessionManager().checkPermission(pwmApplication, Permission.PWMADMIN)) { final ErrorInformation errorInfo = new ErrorInformation( PwmError.ERROR_UNAUTHORIZED, "You must be authenticated with admin privileges before restricting the configuration"); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo); pwmRequest.outputJsonResult(restResultBean); return; } try { final StoredConfigurationImpl storedConfiguration = readCurrentConfiguration(pwmRequest); if (!storedConfiguration.hasPassword()) { final ErrorInformation errorInfo = new ErrorInformation( PwmError.CONFIG_FORMAT_ERROR, null, new String[] { "Please set a configuration password before restricting the configuration" }); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo); pwmRequest.outputJsonResult(restResultBean); return; } storedConfiguration.writeConfigProperty(ConfigurationProperty.CONFIG_IS_EDITABLE, "false"); saveConfiguration(pwmRequest, storedConfiguration); final ConfigManagerBean configManagerBean = pwmRequest .getPwmApplication() .getSessionStateService() .getBean(pwmRequest, ConfigManagerBean.class); configManagerBean.setConfiguration(null); } catch (PwmException e) { final ErrorInformation errorInfo = e.getErrorInformation(); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo.toDebugStr()); pwmRequest.outputJsonResult(restResultBean); return; } catch (Exception e) { final ErrorInformation errorInfo = new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage()); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo.toDebugStr()); pwmRequest.outputJsonResult(restResultBean); return; } final HashMap<String, String> resultData = new HashMap<>(); LOGGER.info(pwmSession, "Configuration Locked"); pwmRequest.outputJsonResult(new RestResultBean(resultData)); }