Ejemplo n.º 1
0
  private static void writeConfig(
      final ContextManager contextManager, final StoredConfigurationImpl storedConfiguration)
      throws PwmOperationalException, PwmUnrecoverableException {
    ConfigurationReader configReader = contextManager.getConfigReader();
    PwmApplication pwmApplication = contextManager.getPwmApplication();

    try {
      // add a random security key
      storedConfiguration.initNewRandomSecurityKey();

      storedConfiguration.writeConfigProperty(
          StoredConfigurationImpl.ConfigProperty.PROPERTY_KEY_CONFIG_IS_EDITABLE, "true");
      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);
    }
  }
Ejemplo n.º 2
0
 @Override
 public void run() {
   reportStatus.setCurrentProcess(ReportStatusInfo.ReportEngineProcess.DredgeTask);
   try {
     updateCacheFromLdap();
   } catch (Exception e) {
     if (e instanceof PwmException) {
       if (((PwmException) e).getErrorInformation().getError()
           == PwmError.ERROR_DIRECTORY_UNAVAILABLE) {
         if (executorService != null) {
           LOGGER.error(
               PwmConstants.REPORTING_SESSION_LABEL,
               "directory unavailable error during background DredgeTask, will retry; error: "
                   + e.getMessage());
           executorService.schedule(new DredgeTask(), 10, TimeUnit.MINUTES);
         }
       } else {
         LOGGER.error(
             PwmConstants.REPORTING_SESSION_LABEL,
             "error during background DredgeTask: " + e.getMessage());
       }
     }
   } finally {
     reportStatus.setCurrentProcess(ReportStatusInfo.ReportEngineProcess.None);
   }
 }
Ejemplo n.º 3
0
 public static SchemaOperationResult extendSchema(
     ConfigGuideBean configGuideBean, final boolean doSchemaExtension) {
   final Map<String, String> form = configGuideBean.getFormData();
   final boolean ldapServerSecure = "true".equalsIgnoreCase(form.get(PARAM_LDAP_SECURE));
   final String ldapUrl =
       "ldap"
           + (ldapServerSecure ? "s" : "")
           + "://"
           + form.get(PARAM_LDAP_HOST)
           + ":"
           + form.get(PARAM_LDAP_PORT);
   try {
     final ChaiConfiguration chaiConfiguration =
         new ChaiConfiguration(
             ldapUrl, form.get(PARAM_LDAP_PROXY_DN), form.get(PARAM_LDAP_PROXY_PW));
     chaiConfiguration.setSetting(ChaiSetting.PROMISCUOUS_SSL, "true");
     final ChaiProvider chaiProvider = ChaiProviderFactory.createProvider(chaiConfiguration);
     if (doSchemaExtension) {
       return SchemaManager.extendSchema(chaiProvider);
     } else {
       return SchemaManager.checkExistingSchema(chaiProvider);
     }
   } catch (Exception e) {
     LOGGER.error("unable to create schema extender object: " + e.getMessage());
     return null;
   }
 }
Ejemplo n.º 4
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.º 5
0
  private static void invokePostChangePasswordActions(
      final PwmSession pwmSession, final String newPassword) throws PwmUnrecoverableException {
    final List<PostChangePasswordAction> postChangePasswordActions =
        pwmSession.getUserSessionDataCacheBean().removePostChangePasswordActions();
    if (postChangePasswordActions == null || postChangePasswordActions.isEmpty()) {
      LOGGER.trace(pwmSession, "no post change password actions pending from previous operations");
      return;
    }

    for (final PostChangePasswordAction postChangePasswordAction : postChangePasswordActions) {
      try {
        postChangePasswordAction.doAction(pwmSession, newPassword);
      } catch (PwmUnrecoverableException e) {
        LOGGER.error(
            pwmSession,
            "error during post change password action '"
                + postChangePasswordAction.getLabel()
                + "' "
                + e.getMessage());
        throw e;
      } catch (Exception e) {
        LOGGER.error(
            pwmSession,
            "unexpected error during post change password action '"
                + postChangePasswordAction.getLabel()
                + "' "
                + e.getMessage(),
            e);
        final ErrorInformation errorInfo =
            new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage());
        throw new PwmUnrecoverableException(errorInfo);
      }
    }
  }
Ejemplo n.º 6
0
 private void updateCacheFromLdap()
     throws ChaiUnavailableException, ChaiOperationException, PwmOperationalException,
         PwmUnrecoverableException {
   LOGGER.debug(
       PwmConstants.REPORTING_SESSION_LABEL,
       "beginning process to updating user cache records from ldap");
   if (status != STATUS.OPEN) {
     return;
   }
   cancelFlag = false;
   reportStatus = new ReportStatusInfo(settings.getSettingsHash());
   reportStatus.setInProgress(true);
   reportStatus.setStartDate(new Date());
   try {
     final Queue<UserIdentity> allUsers = new LinkedList<>(getListOfUsers());
     reportStatus.setTotal(allUsers.size());
     while (status == STATUS.OPEN && !allUsers.isEmpty() && !cancelFlag) {
       final Date startUpdateTime = new Date();
       final UserIdentity userIdentity = allUsers.poll();
       try {
         if (updateCachedRecordFromLdap(userIdentity)) {
           reportStatus.setUpdated(reportStatus.getUpdated() + 1);
         }
       } catch (Exception e) {
         String errorMsg =
             "error while updating report cache for " + userIdentity.toString() + ", cause: ";
         errorMsg +=
             e instanceof PwmException
                 ? ((PwmException) e).getErrorInformation().toDebugStr()
                 : e.getMessage();
         final ErrorInformation errorInformation;
         errorInformation = new ErrorInformation(PwmError.ERROR_REPORTING_ERROR, errorMsg);
         LOGGER.error(PwmConstants.REPORTING_SESSION_LABEL, errorInformation.toDebugStr());
         reportStatus.setLastError(errorInformation);
         reportStatus.setErrors(reportStatus.getErrors() + 1);
       }
       reportStatus.setCount(reportStatus.getCount() + 1);
       reportStatus.getEventRateMeter().markEvents(1);
       final TimeDuration totalUpdateTime = TimeDuration.fromCurrent(startUpdateTime);
       if (settings.isAutoCalcRest()) {
         avgTracker.addSample(totalUpdateTime.getTotalMilliseconds());
         Helper.pause(avgTracker.avgAsLong());
       } else {
         Helper.pause(settings.getRestTime().getTotalMilliseconds());
       }
     }
     if (cancelFlag) {
       reportStatus.setLastError(
           new ErrorInformation(
               PwmError.ERROR_SERVICE_NOT_AVAILABLE, "report cancelled by operator"));
     }
   } finally {
     reportStatus.setFinishDate(new Date());
     reportStatus.setInProgress(false);
   }
   LOGGER.debug(
       PwmConstants.REPORTING_SESSION_LABEL,
       "update user cache process completed: " + JsonUtil.serialize(reportStatus));
 }
Ejemplo n.º 7
0
 private void saveTempData() {
   try {
     final String jsonInfo = JsonUtil.serialize(reportStatus);
     pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.REPORT_STATUS, jsonInfo);
   } catch (Exception e) {
     LOGGER.error(
         PwmConstants.REPORTING_SESSION_LABEL,
         "error writing cached report dredge info into memory: " + e.getMessage());
   }
 }
Ejemplo n.º 8
0
  public static Map<String, String> defaultForm(PwmSettingTemplate template) {
    final Map<String, String> defaultLdapForm = new HashMap<>();

    try {
      final String defaultLdapUrlString =
          ((List<String>) PwmSetting.LDAP_SERVER_URLS.getDefaultValue(template).toNativeObject())
              .get(0);
      final URI uri = new URI(defaultLdapUrlString);

      defaultLdapForm.put(PARAM_LDAP_HOST, uri.getHost());
      defaultLdapForm.put(PARAM_LDAP_PORT, String.valueOf(uri.getPort()));
      defaultLdapForm.put(
          PARAM_LDAP_SECURE, "ldaps".equalsIgnoreCase(uri.getScheme()) ? "true" : "false");

      defaultLdapForm.put(
          PARAM_LDAP_ADMIN_DN,
          (String) PwmSetting.LDAP_PROXY_USER_DN.getDefaultValue(template).toNativeObject());
      defaultLdapForm.put(PARAM_LDAP_ADMIN_PW, "");

      defaultLdapForm.put(
          PARAM_LDAP_CONTEXT,
          ((List<String>)
                  PwmSetting.LDAP_CONTEXTLESS_ROOT.getDefaultValue(template).toNativeObject())
              .get(0));
      defaultLdapForm.put(
          PARAM_LDAP_TEST_USER,
          (String) PwmSetting.LDAP_TEST_USER_DN.getDefaultValue(template).toNativeObject());
      {
        List<UserPermission> userPermissions =
            (List<UserPermission>)
                PwmSetting.QUERY_MATCH_PWM_ADMIN.getDefaultValue(template).toNativeObject();
        final String groupDN =
            userPermissions != null && userPermissions.size() > 0
                ? userPermissions.get(0).getLdapBase()
                : "";
        defaultLdapForm.put(PARAM_LDAP_ADMIN_GROUP, groupDN);
      }

      defaultLdapForm.put(
          PARAM_CR_STORAGE_PREF,
          (String)
              PwmSetting.FORGOTTEN_PASSWORD_WRITE_PREFERENCE
                  .getDefaultValue(template)
                  .toNativeObject());

      defaultLdapForm.put(PARAM_CONFIG_PASSWORD, "");
      defaultLdapForm.put(PARAM_CONFIG_PASSWORD_VERIFY, "");
    } catch (Exception e) {
      LOGGER.error(
          "error building static form values using default configuration: " + e.getMessage());
      e.printStackTrace();
    }

    return Collections.unmodifiableMap(defaultLdapForm);
  }
Ejemplo n.º 9
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.º 10
0
  private boolean isValid(final Connection connection) {
    if (connection == null) {
      return false;
    }

    if (status != PwmService.STATUS.OPEN) {
      return false;
    }

    try {
      final Method getFreeSpaceMethod = File.class.getMethod("isValid");
      final Object rawResult = getFreeSpaceMethod.invoke(connection, 10);
      return (Boolean) rawResult;
    } catch (NoSuchMethodException e) {
      /* no error, pre java 1.6 doesn't have this method */
    } catch (Exception e) {
      LOGGER.debug(
          "error checking for isValid for " + connection.toString() + ",: " + e.getMessage());
    }

    final StringBuilder sb = new StringBuilder();
    sb.append("SELECT * FROM ")
        .append(DatabaseTable.PWM_META.toString())
        .append(" WHERE " + KEY_COLUMN + " = ?");
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
      statement = connection.prepareStatement(sb.toString());
      statement.setString(1, KEY_ENGINE_START_PREFIX + instanceID);
      statement.setMaxRows(1);
      resultSet = statement.executeQuery();
      if (resultSet.next()) {
        resultSet.getString(VALUE_COLUMN);
      }
    } catch (SQLException e) {
      final ErrorInformation errorInformation =
          new ErrorInformation(
              PwmError.ERROR_DB_UNAVAILABLE, "isValid operation failed: " + e.getMessage());
      lastError = errorInformation;
      LOGGER.error(errorInformation.toDebugStr());
      return false;
    } finally {
      close(statement);
      close(resultSet);
    }
    return true;
  }
Ejemplo n.º 11
0
  public void close() {
    status = PwmService.STATUS.CLOSED;
    if (connection != null) {
      try {
        connection.close();
      } catch (Exception e) {
        LOGGER.debug("error while closing DB: " + e.getMessage());
      }
    }

    try {
      driver = null;
    } catch (Exception e) {
      LOGGER.debug("error while de-registering driver: " + e.getMessage());
    }

    connection = null;
  }
Ejemplo n.º 12
0
  private void restUpdateLdapForm(
      final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
      throws IOException, PwmUnrecoverableException {
    final StoredConfiguration 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);
          {
            final String settingValue = AppProperty.LDAP_PROMISCUOUS_ENABLE.getKey() + "=true";
            storedConfiguration.writeSetting(
                PwmSetting.APP_PROPERTY_OVERRIDES,
                new StringArrayValue(Collections.singletonList(settingValue)),
                null);
          }
        }
      } 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.º 13
0
  public static Map<String, String> placeholderForm(PwmSettingTemplate template) {
    final Map<String, String> defaultLdapForm = new HashMap<>();

    try {
      final String defaultLdapUrlString = PwmSetting.LDAP_SERVER_URLS.getPlaceholder(template);
      final URI uri = new URI(defaultLdapUrlString);

      defaultLdapForm.put(PARAM_LDAP_HOST, uri.getHost());
      defaultLdapForm.put(PARAM_LDAP_PORT, String.valueOf(uri.getPort()));
      defaultLdapForm.put(
          PARAM_LDAP_SECURE, "ldaps".equalsIgnoreCase(uri.getScheme()) ? "true" : "false");

      defaultLdapForm.put(
          PARAM_LDAP_PROXY_DN, PwmSetting.LDAP_PROXY_USER_DN.getPlaceholder(template));
      defaultLdapForm.put(PARAM_LDAP_PROXY_PW, "");

      defaultLdapForm.put(
          PARAM_LDAP_CONTEXT, PwmSetting.LDAP_CONTEXTLESS_ROOT.getPlaceholder(template));
      defaultLdapForm.put(
          PARAM_LDAP_TEST_USER, PwmSetting.LDAP_TEST_USER_DN.getPlaceholder(template));
      defaultLdapForm.put(
          PARAM_LDAP_ADMIN_GROUP, PwmSetting.LDAP_TEST_USER_DN.getPlaceholder(template));

      defaultLdapForm.put(
          PARAM_CR_STORAGE_PREF,
          (String)
              PwmSetting.FORGOTTEN_PASSWORD_WRITE_PREFERENCE
                  .getDefaultValue(template)
                  .toNativeObject());

      defaultLdapForm.put(PARAM_CONFIG_PASSWORD, "");
      defaultLdapForm.put(PARAM_CONFIG_PASSWORD_VERIFY, "");
    } catch (Exception e) {
      LOGGER.error(
          "error building static form values using default configuration: " + e.getMessage());
      e.printStackTrace();
    }

    return Collections.unmodifiableMap(defaultLdapForm);
  }
Ejemplo n.º 14
0
  private void initTempData() throws LocalDBException, PwmUnrecoverableException {
    final String cleanFlag =
        pwmApplication.readAppAttribute(PwmApplication.AppAttribute.REPORT_CLEAN_FLAG);
    if (!"true".equals(cleanFlag)) {
      LOGGER.error(PwmConstants.REPORTING_SESSION_LABEL, "did not shut down cleanly");
      reportStatus = new ReportStatusInfo(settings.getSettingsHash());
      reportStatus.setTotal(userCacheService.size());
    } else {
      try {
        final String jsonInfo =
            pwmApplication.readAppAttribute(PwmApplication.AppAttribute.REPORT_STATUS);
        if (jsonInfo != null && !jsonInfo.isEmpty()) {
          reportStatus = JsonUtil.deserialize(jsonInfo, ReportStatusInfo.class);
        }
      } catch (Exception e) {
        LOGGER.error(
            PwmConstants.REPORTING_SESSION_LABEL,
            "error loading cached report status info into memory: " + e.getMessage());
      }
    }

    reportStatus =
        reportStatus == null
            ? new ReportStatusInfo(settings.getSettingsHash())
            : reportStatus; // safety

    final String currentSettingCache = settings.getSettingsHash();
    if (reportStatus.getSettingsHash() != null
        && !reportStatus.getSettingsHash().equals(currentSettingCache)) {
      LOGGER.error(
          PwmConstants.REPORTING_SESSION_LABEL,
          "configuration has changed, will clear cached report data");
      clear();
    }

    reportStatus.setInProgress(false);

    pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.REPORT_CLEAN_FLAG, "false");
  }
Ejemplo n.º 15
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.º 16
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.º 17
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.º 18
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);
    }
  }