Ejemplo n.º 1
0
  private void restBrowseLdap(final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
      throws IOException, ServletException, PwmUnrecoverableException {
    final StoredConfigurationImpl storedConfiguration =
        StoredConfigurationImpl.copy(configGuideBean.getStoredConfiguration());
    if (configGuideBean.getStep() == STEP.LDAP_ADMIN) {
      storedConfiguration.resetSetting(PwmSetting.LDAP_PROXY_USER_DN, LDAP_PROFILE_KEY, null);
      storedConfiguration.resetSetting(PwmSetting.LDAP_PROXY_USER_PASSWORD, LDAP_PROFILE_KEY, null);
    }

    final Date startTime = new Date();
    final Map<String, String> inputMap =
        pwmRequest.readBodyAsJsonStringMap(PwmHttpRequestWrapper.Flag.BypassValidation);
    final String profile = inputMap.get("profile");
    final String dn = inputMap.containsKey("dn") ? inputMap.get("dn") : "";

    final LdapBrowser ldapBrowser = new LdapBrowser(storedConfiguration);
    final LdapBrowser.LdapBrowseResult result = ldapBrowser.doBrowse(profile, dn);
    ldapBrowser.close();

    LOGGER.trace(
        pwmRequest,
        "performed ldapBrowse operation in "
            + TimeDuration.fromCurrent(startTime).asCompactString()
            + ", result="
            + JsonUtil.serialize(result));

    pwmRequest.outputJsonResult(new RestResultBean(result));
  }
Ejemplo n.º 2
0
  public static void saveConfiguration(
      final PwmRequest pwmRequest, final StoredConfigurationImpl storedConfiguration)
      throws PwmUnrecoverableException {
    {
      final List<String> errorStrings = storedConfiguration.validateValues();
      if (errorStrings != null && !errorStrings.isEmpty()) {
        final String errorString = errorStrings.get(0);
        throw new PwmUnrecoverableException(
            new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, null, new String[] {errorString}));
      }
    }

    try {
      ContextManager contextManager =
          ContextManager.getContextManager(
              pwmRequest.getHttpServletRequest().getSession().getServletContext());
      contextManager
          .getConfigReader()
          .saveConfiguration(
              storedConfiguration,
              contextManager.getPwmApplication(),
              pwmRequest.getSessionLabel());
      contextManager.requestPwmApplicationRestart();
    } catch (Exception e) {
      final String errorString = "error saving file: " + e.getMessage();
      LOGGER.error(pwmRequest, errorString);
      throw new PwmUnrecoverableException(
          new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, null, new String[] {errorString}));
    }
  }
Ejemplo n.º 3
0
  private void restUpdateLdapForm(
      final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
      throws IOException, PwmUnrecoverableException {
    final StoredConfigurationImpl storedConfiguration = configGuideBean.getStoredConfiguration();
    final Map<String, String> incomingFormData = pwmRequest.readBodyAsJsonStringMap();

    if (incomingFormData != null) {
      configGuideBean.getFormData().putAll(incomingFormData);
    }

    if (incomingFormData != null
        && incomingFormData.get(PARAM_TEMPLATE_NAME) != null
        && !incomingFormData.get(PARAM_TEMPLATE_NAME).isEmpty()) {
      try {
        final PwmSettingTemplate template =
            PwmSettingTemplate.valueOf(incomingFormData.get(PARAM_TEMPLATE_NAME));
        if (configGuideBean.getSelectedTemplate() != template) {
          LOGGER.debug(
              pwmRequest, "resetting form defaults using " + template.toString() + " template");
          final Map<String, String> defaultForm = defaultForm(template);
          configGuideBean.getFormData().putAll(defaultForm);
          configGuideBean.setSelectedTemplate(template);
          storedConfiguration.setTemplate(template);
        }
      } catch (Exception e) {
        LOGGER.error("unknown template set request: " + e.getMessage());
      }
    }

    final RestResultBean restResultBean = new RestResultBean();
    pwmRequest.outputJsonResult(restResultBean);
    convertFormToConfiguration(
        storedConfiguration, configGuideBean.getFormData(), incomingFormData);
    // LOGGER.info("config: " + storedConfiguration.toString());
  }
Ejemplo n.º 4
0
 private void showSummary(final PwmRequest pwmRequest)
     throws IOException, ServletException, PwmUnrecoverableException {
   final StoredConfigurationImpl storedConfiguration = readCurrentConfiguration(pwmRequest);
   final LinkedHashMap<String, Object> outputMap =
       new LinkedHashMap<>(storedConfiguration.toOutputMap(pwmRequest.getLocale()));
   pwmRequest.setAttribute(PwmRequest.Attribute.ConfigurationSummaryOutput, outputMap);
   pwmRequest.forwardToJsp(PwmConstants.JSP_URL.CONFIG_MANAGER_EDITOR_SUMMARY);
 }
Ejemplo n.º 5
0
 private void showPermissions(final PwmRequest pwmRequest)
     throws IOException, ServletException, PwmUnrecoverableException {
   final StoredConfigurationImpl storedConfiguration = readCurrentConfiguration(pwmRequest);
   LDAPPermissionCalculator ldapPermissionCalculator =
       new LDAPPermissionCalculator(storedConfiguration);
   pwmRequest.setAttribute(
       PwmRequest.Attribute.ConfigurationSummaryOutput, ldapPermissionCalculator);
   pwmRequest.forwardToJsp(PwmConstants.JSP_URL.CONFIG_MANAGER_PERMISSIONS);
 }
Ejemplo n.º 6
0
 void initRequestAttributes(final PwmRequest pwmRequest) throws PwmUnrecoverableException {
   final ConfigurationReader configurationReader =
       pwmRequest.getContextManager().getConfigReader();
   pwmRequest.setAttribute(
       PwmRequest.Attribute.PageTitle,
       LocaleHelper.getLocalizedMessage(Config.Title_ConfigManager, pwmRequest));
   pwmRequest.setAttribute(
       PwmRequest.Attribute.ApplicationPath,
       pwmRequest.getPwmApplication().getPwmEnvironment().getApplicationPath().getAbsolutePath());
   pwmRequest.setAttribute(
       PwmRequest.Attribute.ConfigFilename, configurationReader.getConfigFile().getAbsolutePath());
   {
     final Date lastModifyTime = configurationReader.getStoredConfiguration().modifyTime();
     final String output =
         lastModifyTime == null
             ? LocaleHelper.getLocalizedMessage(Display.Value_NotApplicable, pwmRequest)
             : PwmConstants.DEFAULT_DATETIME_FORMAT.format(lastModifyTime);
     pwmRequest.setAttribute(PwmRequest.Attribute.ConfigLastModified, output);
   }
   pwmRequest.setAttribute(
       PwmRequest.Attribute.ConfigHasPassword,
       LocaleHelper.booleanString(
           configurationReader.getStoredConfiguration().hasPassword(),
           pwmRequest.getLocale(),
           pwmRequest.getConfig()));
 }
Ejemplo n.º 7
0
 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);
   }
 }
Ejemplo n.º 8
0
 static void forwardToJSP(final PwmRequest pwmRequest)
     throws IOException, ServletException, PwmUnrecoverableException {
   final HttpServletRequest req = pwmRequest.getHttpServletRequest();
   final ServletContext servletContext = req.getSession().getServletContext();
   final ConfigGuideBean configGuideBean =
       pwmRequest.getPwmSession().getSessionBean(ConfigGuideBean.class);
   String destURL = '/' + PwmConstants.URL_JSP_CONFIG_GUIDE;
   destURL = destURL.replace("%1%", configGuideBean.getStep().toString().toLowerCase());
   servletContext
       .getRequestDispatcher(destURL)
       .forward(req, pwmRequest.getPwmResponse().getHttpServletResponse());
 }
Ejemplo n.º 9
0
 private void restUseConfiguredCerts(
     final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
     throws PwmUnrecoverableException, IOException {
   final boolean value = Boolean.parseBoolean(pwmRequest.readParameterAsString("value"));
   configGuideBean.setUseConfiguredCerts(value);
   final StoredValue newStoredValue =
       value
           ? new X509CertificateValue(configGuideBean.getLdapCertificates())
           : new X509CertificateValue(new X509Certificate[0]);
   configGuideBean
       .getStoredConfiguration()
       .writeSetting(PwmSetting.LDAP_SERVER_CERTS, LDAP_PROFILE_KEY, newStoredValue, null);
   pwmRequest.outputJsonResult(new RestResultBean());
 }
Ejemplo n.º 10
0
  protected void processAction(final PwmRequest pwmRequest)
      throws ServletException, IOException, ChaiUnavailableException, PwmUnrecoverableException {
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final ConfigManagerBean configManagerBean =
        pwmRequest
            .getPwmApplication()
            .getSessionStateService()
            .getBean(pwmRequest, ConfigManagerBean.class);

    final ConfigManagerAction processAction = readProcessAction(pwmRequest);
    if (processAction != null) {
      switch (processAction) {
        case lockConfiguration:
          restLockConfiguration(pwmRequest);
          break;

        case startEditing:
          doStartEditing(pwmRequest);
          break;

        case downloadConfig:
          doDownloadConfig(pwmRequest);
          break;

        case generateSupportZip:
          doGenerateSupportZip(pwmRequest);
          break;

        case uploadConfig:
          ConfigGuideServlet.restUploadConfig(pwmRequest);
          return;

        case uploadWordlist:
          restUploadWordlist(pwmRequest);
          return;

        case summary:
          showSummary(pwmRequest);
          return;

        case permissions:
          showPermissions(pwmRequest);
          return;
      }
      return;
    }

    initRequestAttributes(pwmRequest);
    pwmRequest.forwardToJsp(PwmConstants.JSP_URL.CONFIG_MANAGER_MODE_CONFIGURATION);
  }
Ejemplo n.º 11
0
  private void doGenerateSupportZip(final PwmRequest pwmRequest)
      throws IOException, ServletException {
    final PwmResponse resp = pwmRequest.getPwmResponse();
    resp.setHeader(
        PwmConstants.HttpHeader.ContentDisposition,
        "attachment;filename=" + PwmConstants.PWM_APP_NAME + "-Support.zip");
    resp.setContentType(PwmConstants.ContentTypeValue.zip);

    final String pathPrefix = PwmConstants.PWM_APP_NAME + "-Support" + "/";

    ZipOutputStream zipOutput = null;
    try {
      zipOutput = new ZipOutputStream(resp.getOutputStream(), PwmConstants.DEFAULT_CHARSET);
      DebugItemGenerator.outputZipDebugFile(pwmRequest, zipOutput, pathPrefix);
    } catch (Exception e) {
      LOGGER.error(pwmRequest, "error during zip debug building: " + e.getMessage());
    } finally {
      if (zipOutput != null) {
        try {
          zipOutput.close();
        } catch (Exception e) {
          LOGGER.error(pwmRequest, "error during zip debug closing: " + e.getMessage());
        }
      }
    }
  }
Ejemplo n.º 12
0
 public static StoredConfigurationImpl readCurrentConfiguration(final PwmRequest pwmRequest)
     throws PwmUnrecoverableException {
   final ContextManager contextManager =
       ContextManager.getContextManager(pwmRequest.getHttpServletRequest().getSession());
   final ConfigurationReader runningConfigReader = contextManager.getConfigReader();
   final StoredConfigurationImpl runningConfig = runningConfigReader.getStoredConfiguration();
   return StoredConfigurationImpl.copy(runningConfig);
 }
Ejemplo n.º 13
0
 protected ConfigGuideAction readProcessAction(final PwmRequest request)
     throws PwmUnrecoverableException {
   try {
     return ConfigGuideAction.valueOf(
         request.readParameterAsString(PwmConstants.PARAM_ACTION_REQUEST));
   } catch (IllegalArgumentException e) {
     return null;
   }
 }
Ejemplo n.º 14
0
  private void doDownloadConfig(final PwmRequest pwmRequest)
      throws IOException, ServletException, PwmUnrecoverableException {
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final PwmResponse resp = pwmRequest.getPwmResponse();

    try {
      final StoredConfigurationImpl storedConfiguration = readCurrentConfiguration(pwmRequest);
      final OutputStream responseWriter = resp.getOutputStream();
      resp.setHeader(
          PwmConstants.HttpHeader.ContentDisposition,
          "attachment;filename=" + PwmConstants.DEFAULT_CONFIG_FILE_FILENAME);
      resp.setContentType(PwmConstants.ContentTypeValue.xml);
      storedConfiguration.toXml(responseWriter);
      responseWriter.close();
    } catch (Exception e) {
      LOGGER.error(pwmSession, "unable to download configuration: " + e.getMessage());
    }
  }
Ejemplo n.º 15
0
  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));
  }
Ejemplo n.º 16
0
  private void restViewAdminMatches(
      final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
      throws IOException, ServletException {

    try {
      final UserMatchViewerFunction userMatchViewerFunction = new UserMatchViewerFunction();
      final Serializable output =
          userMatchViewerFunction.provideFunction(
              pwmRequest,
              configGuideBean.getStoredConfiguration(),
              PwmSetting.QUERY_MATCH_PWM_ADMIN,
              null);
      pwmRequest.outputJsonResult(new RestResultBean(output));
    } catch (PwmException e) {
      LOGGER.error(pwmRequest, e.getErrorInformation());
      pwmRequest.respondWithError(e.getErrorInformation());
    } catch (Exception e) {
      final ErrorInformation errorInformation =
          new ErrorInformation(
              PwmError.ERROR_UNKNOWN, "error while testing matches = " + e.getMessage());
      LOGGER.error(pwmRequest, errorInformation);
      pwmRequest.respondWithError(errorInformation);
    }
  }
Ejemplo n.º 17
0
  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());
      }
    }
  }
Ejemplo n.º 18
0
  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);
    }
  }
Ejemplo n.º 19
0
  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));
  }
Ejemplo n.º 20
0
 static void forwardToEditor(final PwmRequest pwmRequest)
     throws IOException, ServletException, PwmUnrecoverableException {
   final String url =
       pwmRequest.getHttpServletRequest().getContextPath() + "/private/config/ConfigEditor";
   pwmRequest.sendRedirect(url);
 }
Ejemplo n.º 21
0
  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);
  }
Ejemplo n.º 22
0
  @Override
  protected void processAction(final PwmRequest pwmRequest)
      throws ServletException, IOException, ChaiUnavailableException, PwmUnrecoverableException {
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();

    if ((pwmSession.getSessionBean(ConfigGuideBean.class)).getStep() == STEP.START) {
      pwmSession.clearSessionBeans();
      pwmSession.getSessionStateBean().setTheme(null);
    }

    final ConfigGuideBean configGuideBean = pwmSession.getSessionBean(ConfigGuideBean.class);

    if (pwmApplication.getApplicationMode() != PwmApplication.MODE.NEW) {
      final ErrorInformation errorInformation =
          new ErrorInformation(
              PwmError.ERROR_SERVICE_NOT_AVAILABLE, "ConfigGuide unavailable unless in NEW mode");
      LOGGER.error(pwmSession, errorInformation.toDebugStr());
      pwmRequest.respondWithError(errorInformation);
      return;
    }

    if (!configGuideBean.getFormData().containsKey(PARAM_APP_SITEURL)) {
      final URI uri = URI.create(pwmRequest.getHttpServletRequest().getRequestURL().toString());
      final int port = Helper.portForUriSchema(uri);
      final String newUri =
          uri.getScheme() + "://" + uri.getHost() + ":" + port + pwmRequest.getContextPath();
      configGuideBean.getFormData().put(PARAM_APP_SITEURL, newUri);
    }

    pwmSession.setSessionTimeout(
        pwmRequest.getHttpServletRequest().getSession(),
        Integer.parseInt(
            pwmApplication.getConfig().readAppProperty(AppProperty.CONFIG_GUIDE_IDLE_TIMEOUT)));

    if (configGuideBean.getStep() == STEP.LDAP_CERT) {
      final String ldapServerString =
          ((List<String>)
                  configGuideBean
                      .getStoredConfiguration()
                      .readSetting(PwmSetting.LDAP_SERVER_URLS, LDAP_PROFILE_KEY)
                      .toNativeObject())
              .get(0);
      try {
        final URI ldapServerUri = new URI(ldapServerString);
        if ("ldaps".equalsIgnoreCase(ldapServerUri.getScheme())) {
          configGuideBean.setLdapCertificates(X509Utils.readRemoteCertificates(ldapServerUri));
          configGuideBean.setCertsTrustedbyKeystore(
              X509Utils.testIfLdapServerCertsInDefaultKeystore(ldapServerUri));
        } else {
          configGuideBean.setLdapCertificates(null);
          configGuideBean.setCertsTrustedbyKeystore(false);
        }
      } catch (Exception e) {
        LOGGER.error("error reading/testing ldap server certificates: " + e.getMessage());
      }
    }

    final ConfigGuideAction action = readProcessAction(pwmRequest);
    if (action != null) {
      pwmRequest.validatePwmFormID();
      switch (action) {
        case ldapHealth:
          restLdapHealth(pwmRequest, configGuideBean);
          return;

        case updateForm:
          restUpdateLdapForm(pwmRequest, configGuideBean);
          return;

        case gotoStep:
          restGotoStep(pwmRequest, configGuideBean);
          return;

        case useConfiguredCerts:
          restUseConfiguredCerts(pwmRequest, configGuideBean);
          return;

        case uploadConfig:
          restUploadConfig(pwmRequest);
          return;

        case extendSchema:
          restExtendSchema(pwmRequest, configGuideBean);
          return;

        case viewAdminMatches:
          restViewAdminMatches(pwmRequest, configGuideBean);
          return;

        case browseLdap:
          restBrowseLdap(pwmRequest, configGuideBean);
      }
    }

    if (!pwmRequest.getPwmResponse().getHttpServletResponse().isCommitted()) {
      forwardToJSP(pwmRequest);
    }
  }