コード例 #1
0
  private static void checkConfiguration(final Configuration configuration)
      throws PwmUnrecoverableException {
    final String namingAttribute =
        configuration.getDefaultLdapProfile().readSettingAsString(PwmSetting.LDAP_NAMING_ATTRIBUTE);
    final List<FormConfiguration> formItems =
        configuration.readSettingAsForm(PwmSetting.GUEST_FORM);

    {
      boolean namingIsInForm = false;
      for (final FormConfiguration formItem : formItems) {
        if (namingAttribute.equalsIgnoreCase(formItem.getName())) {
          namingIsInForm = true;
        }
      }

      if (!namingIsInForm) {
        final String errorMsg =
            "ldap naming attribute '"
                + namingAttribute
                + "' is not in form configuration, but is required";
        final ErrorInformation errorInformation =
            new ErrorInformation(
                PwmError.ERROR_INVALID_CONFIG, errorMsg, new String[] {namingAttribute});
        throw new PwmUnrecoverableException(errorInformation);
      }
    }
  }
コード例 #2
0
ファイル: PasswordUtility.java プロジェクト: ldchrist/pwm
  private static ErrorInformation sendNewPasswordEmail(
      final UserInfoBean userInfoBean,
      final PwmApplication pwmApplication,
      final MacroMachine macroMachine,
      final PasswordData newPassword,
      final String toAddress,
      final Locale userLocale)
      throws PwmOperationalException, PwmUnrecoverableException {
    final Configuration config = pwmApplication.getConfig();
    final EmailItemBean configuredEmailSetting =
        config.readSettingAsEmail(PwmSetting.EMAIL_SENDPASSWORD, userLocale);

    if (configuredEmailSetting == null) {
      final String errorMsg = "send password email contents are not configured";
      return new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
    }

    final EmailItemBean emailItemBean =
        new EmailItemBean(
            configuredEmailSetting.getTo(),
            configuredEmailSetting.getFrom(),
            configuredEmailSetting.getSubject(),
            configuredEmailSetting.getBodyPlain().replace("%TOKEN%", newPassword.getStringValue()),
            configuredEmailSetting.getBodyHtml().replace("%TOKEN%", newPassword.getStringValue()));
    pwmApplication.getEmailQueue().submitEmail(emailItemBean, userInfoBean, macroMachine);

    LOGGER.debug(
        "new password email to "
            + userInfoBean.getUserIdentity()
            + " added to send queue for "
            + toAddress);
    return null;
  }
コード例 #3
0
ファイル: PasswordUtility.java プロジェクト: ldchrist/pwm
  private static ErrorInformation sendNewPasswordSms(
      final UserInfoBean userInfoBean,
      final PwmApplication pwmApplication,
      final MacroMachine macroMachine,
      final PasswordData newPassword,
      final String toNumber,
      final Locale userLocale)
      throws PwmOperationalException, PwmUnrecoverableException {
    final Configuration config = pwmApplication.getConfig();
    String message =
        config.readSettingAsLocalizedString(PwmSetting.SMS_CHALLENGE_NEW_PASSWORD_TEXT, userLocale);

    if (toNumber == null || toNumber.length() < 1) {
      final String errorMsg =
          String.format(
              "unable to send new password email for '%s'; no SMS number available in ldap",
              userInfoBean.getUserIdentity());
      return new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
    }

    message = message.replace("%TOKEN%", newPassword.getStringValue());

    pwmApplication.sendSmsUsingQueue(new SmsItemBean(toNumber, message), macroMachine);
    LOGGER.debug(String.format("password SMS added to send queue for %s", toNumber));
    return null;
  }
コード例 #4
0
ファイル: PasswordUtility.java プロジェクト: ldchrist/pwm
  private static void sendChangePasswordHelpdeskEmailNotice(
      final PwmSession pwmSession,
      final PwmApplication pwmApplication,
      final UserInfoBean userInfoBean)
      throws PwmUnrecoverableException {
    final Configuration config = pwmApplication.getConfig();
    final Locale locale = pwmSession.getSessionStateBean().getLocale();
    final EmailItemBean configuredEmailSetting =
        config.readSettingAsEmail(PwmSetting.EMAIL_CHANGEPASSWORD_HELPDESK, locale);

    if (configuredEmailSetting == null) {
      LOGGER.debug(
          pwmSession,
          "skipping send change password email for '"
              + pwmSession.getUserInfoBean().getUserIdentity()
              + "' no email configured");
      return;
    }

    final MacroMachine macroMachine =
        userInfoBean == null
            ? null
            : new MacroMachine(
                pwmApplication,
                pwmSession.getLabel(),
                userInfoBean,
                null,
                LdapUserDataReader.appProxiedReader(
                    pwmApplication, userInfoBean.getUserIdentity()));

    pwmApplication.getEmailQueue().submitEmail(configuredEmailSetting, userInfoBean, macroMachine);
  }
コード例 #5
0
  public void init(final Configuration config) throws PwmException {
    final Map<FileValue.FileInformation, FileValue.FileContent> fileValue =
        config.readSettingAsFile(PwmSetting.DATABASE_JDBC_DRIVER);
    final byte[] jdbcDriverBytes;
    if (fileValue != null && !fileValue.isEmpty()) {
      final FileValue.FileInformation fileInformation1 = fileValue.keySet().iterator().next();
      final FileValue.FileContent fileContent = fileValue.get(fileInformation1);
      jdbcDriverBytes = fileContent.getContents();
    } else {
      jdbcDriverBytes = null;
    }

    this.dbConfiguration =
        new DBConfiguration(
            config.readSettingAsString(PwmSetting.DATABASE_CLASS),
            config.readSettingAsString(PwmSetting.DATABASE_URL),
            config.readSettingAsString(PwmSetting.DATABASE_USERNAME),
            config.readSettingAsPassword(PwmSetting.DATABASE_PASSWORD),
            config.readSettingAsString(PwmSetting.DATABASE_COLUMN_TYPE_KEY),
            config.readSettingAsString(PwmSetting.DATABASE_COLUMN_TYPE_VALUE),
            jdbcDriverBytes);

    this.instanceID = pwmApplication == null ? null : pwmApplication.getInstanceID();
    this.traceLogging = config.readSettingAsBoolean(PwmSetting.DATABASE_DEBUG_TRACE);

    if (this.dbConfiguration.isEmpty()) {
      status = PwmService.STATUS.CLOSED;
      LOGGER.debug("skipping database connection open, no connection parameters configured");
    }
  }
コード例 #6
0
 String getTlsProtocolsValue() {
   final Configuration config = cliEnvironment.getConfig();
   final Set<TLSVersion> tlsVersions =
       config.readSettingAsOptionList(PwmSetting.HTTPS_PROTOCOLS, TLSVersion.class);
   final StringBuilder output = new StringBuilder();
   for (final Iterator<TLSVersion> versionIterator = tlsVersions.iterator();
       versionIterator.hasNext(); ) {
     final TLSVersion tlsVersion = versionIterator.next();
     output.append(tlsVersion.getTomcatValueName());
     if (versionIterator.hasNext()) {
       output.append(", ");
     }
   }
   return output.toString();
 }
コード例 #7
0
  protected void processAction(final PwmRequest pwmRequest)
      throws ServletException, ChaiUnavailableException, IOException, PwmUnrecoverableException {
    // Fetch the session state bean.
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final GuestRegistrationBean guestRegistrationBean =
        pwmApplication.getSessionStateService().getBean(pwmRequest, GuestRegistrationBean.class);

    final Configuration config = pwmApplication.getConfig();

    if (!config.readSettingAsBoolean(PwmSetting.GUEST_ENABLE)) {
      pwmRequest.respondWithError(PwmError.ERROR_SERVICE_NOT_AVAILABLE.toInfo());
      return;
    }

    if (!pwmSession
        .getSessionManager()
        .checkPermission(pwmApplication, Permission.GUEST_REGISTRATION)) {
      pwmRequest.respondWithError(PwmError.ERROR_UNAUTHORIZED.toInfo());
      return;
    }

    checkConfiguration(config);

    final GuestRegistrationAction action = readProcessAction(pwmRequest);
    if (action != null) {
      pwmRequest.validatePwmFormID();
      switch (action) {
        case create:
          handleCreateRequest(pwmRequest, guestRegistrationBean);
          return;

        case search:
          handleSearchRequest(pwmRequest, guestRegistrationBean);
          return;

        case update:
          handleUpdateRequest(pwmRequest, guestRegistrationBean);
          return;

        case selectPage:
          handleSelectPageRequest(pwmRequest, guestRegistrationBean);
          return;
      }
    }

    this.forwardToJSP(pwmRequest, guestRegistrationBean);
  }
コード例 #8
0
  private static Date readExpirationFromRequest(final PwmRequest pwmRequest)
      throws PwmOperationalException, ChaiUnavailableException, ChaiOperationException,
          PwmUnrecoverableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final Configuration config = pwmApplication.getConfig();
    final long durationValueDays = config.readSettingAsLong(PwmSetting.GUEST_MAX_VALID_DAYS);
    final String expirationAttribute =
        config.readSettingAsString(PwmSetting.GUEST_EXPIRATION_ATTRIBUTE);

    if (durationValueDays == 0
        || expirationAttribute == null
        || expirationAttribute.length() <= 0) {
      return null;
    }

    final String expirationDateStr = pwmRequest.readParameterAsString(HTTP_PARAM_EXPIRATION_DATE);

    Date expirationDate;
    try {
      expirationDate = new SimpleDateFormat("yyyy-MM-dd").parse(expirationDateStr);
    } catch (ParseException e) {
      final String errorMsg = "unable to read expiration date value: " + e.getMessage();
      throw new PwmOperationalException(
          new ErrorInformation(
              PwmError.ERROR_FIELD_REQUIRED, errorMsg, new String[] {"expiration date"}));
    }

    if (expirationDate.before(new Date())) {
      final String errorMsg = "expiration date must be in the future";
      throw new PwmOperationalException(
          new ErrorInformation(PwmError.ERROR_FIELD_REQUIRED, errorMsg));
    }

    final long durationValueMs = durationValueDays * 24 * 60 * 60 * 1000;
    final long futureDateMs = System.currentTimeMillis() + durationValueMs;
    final Date futureDate = new Date(futureDateMs);

    if (expirationDate.after(futureDate)) {
      final String errorMsg = "expiration date must be sooner than " + futureDate.toString();
      throw new PwmOperationalException(
          new ErrorInformation(PwmError.ERROR_FIELD_REQUIRED, errorMsg));
    }

    LOGGER.trace(pwmRequest, "read expiration date as " + expirationDate.toString());
    return expirationDate;
  }
コード例 #9
0
  private void sendUpdateGuestEmailConfirmation(
      final PwmRequest pwmRequest, final UserInfoBean guestUserInfoBean)
      throws PwmUnrecoverableException {
    final Configuration config = pwmRequest.getConfig();
    final Locale locale = pwmRequest.getLocale();
    final EmailItemBean configuredEmailSetting =
        config.readSettingAsEmail(PwmSetting.EMAIL_UPDATEGUEST, locale);

    if (configuredEmailSetting == null) {
      LOGGER.debug(pwmRequest, "unable to send updated guest user email: no email configured");
      return;
    }

    pwmRequest
        .getPwmApplication()
        .getEmailQueue()
        .submitEmail(configuredEmailSetting, guestUserInfoBean, null);
  }
コード例 #10
0
ファイル: NAAFEndPoint.java プロジェクト: idwright/pwm
  public NAAFEndPoint(final PwmApplication pwmApplication, final String url, final Locale locale)
      throws PwmUnrecoverableException {
    this.locale = locale;

    final Configuration config = pwmApplication.getConfig();
    this.endpointURL = url;
    this.id = config.readAppProperty(AppProperty.NAAF_ID);
    this.secret = config.readAppProperty(AppProperty.NAAF_SECRET);
    final int saltLength = Integer.parseInt(config.readAppProperty(AppProperty.NAAF_SALT_LENGTH));
    this.salt = PwmRandom.getInstance().alphaNumericString(saltLength);

    final X509Certificate[] naafWsCerts =
        config.readSettingAsCertificate(PwmSetting.NAAF_WS_CERTIFICATE);
    final PwmHttpClientConfiguration pwmHttpClientConfiguration =
        new PwmHttpClientConfiguration.Builder().setCertificate(naafWsCerts).create();
    this.pwmHttpClient = new PwmHttpClient(pwmApplication, null, pwmHttpClientConfiguration);
    establishEndpointSession();
  }
コード例 #11
0
 private static String determineUserDN(
     final Map<FormConfiguration, String> formValues, final Configuration config)
     throws PwmUnrecoverableException {
   final String namingAttribute =
       config.getDefaultLdapProfile().readSettingAsString(PwmSetting.LDAP_NAMING_ATTRIBUTE);
   for (final FormConfiguration formItem : formValues.keySet()) {
     if (namingAttribute.equals(formItem.getName())) {
       final String namingValue = formValues.get(formItem);
       final String gestUserContextDN = config.readSettingAsString(PwmSetting.GUEST_CONTEXT);
       return namingAttribute + "=" + namingValue + "," + gestUserContextDN;
     }
   }
   final String errorMsg =
       "unable to determine new user DN due to missing form value for naming attribute '"
           + namingAttribute
           + '"';
   throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg));
 }
コード例 #12
0
 public static HealthMonitorSettings fromConfiguration(final Configuration config) {
   final HealthMonitorSettings settings = new HealthMonitorSettings();
   settings.nominalCheckInterval =
       new TimeDuration(
           Long.parseLong(config.readAppProperty(AppProperty.HEALTHCHECK_NOMINAL_CHECK_INTERVAL)),
           TimeUnit.SECONDS);
   settings.minimumCheckInterval =
       new TimeDuration(
           Long.parseLong(config.readAppProperty(AppProperty.HEALTHCHECK_MIN_CHECK_INTERVAL)),
           TimeUnit.SECONDS);
   settings.maximumRecordAge =
       new TimeDuration(
           Long.parseLong(config.readAppProperty(AppProperty.HEALTHCHECK_MAX_RECORD_AGE)),
           TimeUnit.SECONDS);
   settings.maximumForceCheckWait =
       new TimeDuration(
           Long.parseLong(config.readAppProperty(AppProperty.HEALTHCHECK_MAX_FORCE_WAIT)),
           TimeUnit.SECONDS);
   return settings;
 }
コード例 #13
0
  private void sendGuestUserEmailConfirmation(
      final PwmRequest pwmRequest, final UserIdentity userIdentity)
      throws PwmUnrecoverableException {
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final Configuration config = pwmApplication.getConfig();
    final Locale locale = pwmSession.getSessionStateBean().getLocale();
    final EmailItemBean configuredEmailSetting =
        config.readSettingAsEmail(PwmSetting.EMAIL_GUEST, locale);

    if (configuredEmailSetting == null) {
      LOGGER.debug(
          pwmSession,
          "unable to send guest registration email for '" + userIdentity + "' no email configured");
      return;
    }

    final MacroMachine macroMachine = MacroMachine.forUser(pwmRequest, userIdentity);

    pwmApplication.getEmailQueue().submitEmail(configuredEmailSetting, null, macroMachine);
  }
コード例 #14
0
  public static LocalDBLoggerSettings fromConfiguration(final Configuration configuration) {
    final Set<Flag> flags = new HashSet<>();
    if (configuration.isDevDebugMode()) {
      flags.add(Flag.DevDebug);
    }
    final int maxEvents = (int) configuration.readSettingAsLong(PwmSetting.EVENTS_PWMDB_MAX_EVENTS);
    final long maxAgeMS = 1000 * configuration.readSettingAsLong(PwmSetting.EVENTS_PWMDB_MAX_AGE);
    final TimeDuration maxAge = new TimeDuration(maxAgeMS);
    final int maxBufferSize =
        Integer.parseInt(configuration.readAppProperty(AppProperty.LOCALDB_LOGWRITER_BUFFER_SIZE));
    final TimeDuration maxBufferWaitTime =
        new TimeDuration(
            Long.parseLong(
                configuration.readAppProperty(AppProperty.LOCALDB_LOGWRITER_MAX_BUFFER_WAIT_MS)));
    final int maxTrimSize =
        Integer.parseInt(
            configuration.readAppProperty(AppProperty.LOCALDB_LOGWRITER_MAX_TRIM_SIZE));

    return new Builder()
        .setMaxEvents(maxEvents)
        .setMaxAge(maxAge)
        .setFlags(flags)
        .setMaxBufferSize(maxBufferSize)
        .setMaxBufferWaitTime(maxBufferWaitTime)
        .setMaxTrimSize(maxTrimSize)
        .createLocalDBLoggerSettings();
  }
コード例 #15
0
  private static void sendProfileUpdateEmailNotice(
      final PwmSession pwmSession, final PwmApplication pwmApplication)
      throws PwmUnrecoverableException, ChaiUnavailableException {
    final Configuration config = pwmApplication.getConfig();
    final Locale locale = pwmSession.getSessionStateBean().getLocale();
    final EmailItemBean configuredEmailSetting =
        config.readSettingAsEmail(PwmSetting.EMAIL_UPDATEPROFILE, locale);

    if (configuredEmailSetting == null) {
      LOGGER.debug(
          pwmSession,
          "skipping send profile update email for '"
              + pwmSession.getUserInfoBean().getUserIdentity()
              + "' no email configured");
      return;
    }

    pwmApplication
        .getEmailQueue()
        .submitEmail(
            configuredEmailSetting,
            pwmSession.getUserInfoBean(),
            pwmSession.getSessionManager().getMacroMachine(pwmApplication));
  }
コード例 #16
0
  public void initializeToken(
      final PwmRequest pwmRequest,
      final UpdateProfileBean updateProfileBean,
      final TokenVerificationProgress.TokenChannel tokenType)
      throws PwmUnrecoverableException {
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();

    if (pwmApplication.getConfig().getTokenStorageMethod() == TokenStorageMethod.STORE_LDAP) {
      throw new PwmUnrecoverableException(
          new ErrorInformation(
              PwmError.CONFIG_FORMAT_ERROR,
              null,
              new String[] {
                "cannot generate new user tokens when storage type is configured as STORE_LDAP."
              }));
    }

    final MacroMachine macroMachine =
        pwmRequest.getPwmSession().getSessionManager().getMacroMachine(pwmApplication);
    final Configuration config = pwmApplication.getConfig();

    switch (tokenType) {
      case SMS:
        {
          final String telephoneNumberAttribute =
              pwmRequest.getConfig().readSettingAsString(PwmSetting.SMS_USER_PHONE_ATTRIBUTE);
          final String toNum = updateProfileBean.getFormData().get(telephoneNumberAttribute);
          final String tokenKey;
          try {
            final TokenPayload tokenPayload =
                pwmApplication
                    .getTokenService()
                    .createTokenPayload(
                        TokenType.UPDATE_SMS,
                        Collections.<String, String>emptyMap(),
                        pwmRequest.getUserInfoIfLoggedIn(),
                        Collections.singleton(toNum));
            tokenKey =
                pwmApplication
                    .getTokenService()
                    .generateNewToken(tokenPayload, pwmRequest.getSessionLabel());
          } catch (PwmOperationalException e) {
            throw new PwmUnrecoverableException(e.getErrorInformation());
          }

          final String message =
              config.readSettingAsLocalizedString(
                  PwmSetting.SMS_UPDATE_PROFILE_TOKEN_TEXT,
                  pwmSession.getSessionStateBean().getLocale());

          try {
            TokenService.TokenSender.sendSmsToken(
                pwmApplication, null, macroMachine, toNum, message, tokenKey);
          } catch (Exception e) {
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN));
          }

          updateProfileBean
              .getTokenVerificationProgress()
              .getIssuedTokens()
              .add(TokenVerificationProgress.TokenChannel.SMS);
          updateProfileBean.getTokenVerificationProgress().setTokenDisplayText(toNum);
          updateProfileBean
              .getTokenVerificationProgress()
              .setPhase(TokenVerificationProgress.TokenChannel.SMS);
        }
        break;

      case EMAIL:
        {
          final EmailItemBean configuredEmailSetting =
              config.readSettingAsEmail(
                  PwmSetting.EMAIL_UPDATEPROFILE_VERIFICATION, pwmRequest.getLocale());
          final String emailAddressAttribute =
              pwmRequest.getConfig().readSettingAsString(PwmSetting.EMAIL_USER_MAIL_ATTRIBUTE);
          final String toAddress = updateProfileBean.getFormData().get(emailAddressAttribute);

          final String tokenKey;
          try {
            final TokenPayload tokenPayload =
                pwmApplication
                    .getTokenService()
                    .createTokenPayload(
                        TokenType.UPDATE_EMAIL,
                        Collections.<String, String>emptyMap(),
                        pwmRequest.getUserInfoIfLoggedIn(),
                        Collections.singleton(toAddress));
            tokenKey =
                pwmApplication
                    .getTokenService()
                    .generateNewToken(tokenPayload, pwmRequest.getSessionLabel());
          } catch (PwmOperationalException e) {
            throw new PwmUnrecoverableException(e.getErrorInformation());
          }

          updateProfileBean
              .getTokenVerificationProgress()
              .getIssuedTokens()
              .add(TokenVerificationProgress.TokenChannel.EMAIL);
          updateProfileBean
              .getTokenVerificationProgress()
              .setPhase(TokenVerificationProgress.TokenChannel.EMAIL);
          updateProfileBean.getTokenVerificationProgress().setTokenDisplayText(toAddress);

          final EmailItemBean emailItemBean =
              new EmailItemBean(
                  toAddress,
                  configuredEmailSetting.getFrom(),
                  configuredEmailSetting.getSubject(),
                  configuredEmailSetting.getBodyPlain().replace("%TOKEN%", tokenKey),
                  configuredEmailSetting.getBodyHtml().replace("%TOKEN%", tokenKey));

          try {
            TokenService.TokenSender.sendEmailToken(
                pwmApplication, null, macroMachine, emailItemBean, toAddress, tokenKey);
          } catch (Exception e) {
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN));
          }
        }
        break;

      default:
        LOGGER.error("Unimplemented token purpose: " + tokenType);
        updateProfileBean.getTokenVerificationProgress().setPhase(null);
    }
  }
コード例 #17
0
ファイル: RestAppDataServer.java プロジェクト: CherifSy/pwm
  private static Map<String, Object> makeClientData(
      final PwmApplication pwmApplication,
      final PwmSession pwmSession,
      final HttpServletRequest request,
      final HttpServletResponse response,
      final String pageUrl)
      throws ChaiUnavailableException, PwmUnrecoverableException {
    final Configuration config = pwmApplication.getConfig();
    final TreeMap<String, Object> settingMap = new TreeMap<>();
    settingMap.put(
        "client.ajaxTypingTimeout",
        Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_AJAX_TYPING_TIMEOUT)));
    settingMap.put(
        "client.ajaxTypingWait",
        Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_AJAX_TYPING_WAIT)));
    settingMap.put(
        "client.activityMaxEpsRate",
        Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_ACTIVITY_MAX_EPS_RATE)));
    settingMap.put(
        "client.js.enableHtml5Dialog",
        Boolean.parseBoolean(config.readAppProperty(AppProperty.CLIENT_JS_ENABLE_HTML5DIALOG)));
    settingMap.put(
        "client.pwShowRevertTimeout",
        Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_PW_SHOW_REVERT_TIMEOUT)));
    settingMap.put(
        "enableIdleTimeout", config.readSettingAsBoolean(PwmSetting.DISPLAY_IDLE_TIMEOUT));
    settingMap.put(
        "pageLeaveNotice", config.readSettingAsLong(PwmSetting.SECURITY_PAGE_LEAVE_NOTICE_TIMEOUT));
    settingMap.put(
        "setting-showHidePasswordFields",
        pwmApplication
            .getConfig()
            .readSettingAsBoolean(
                password.pwm.config.PwmSetting.DISPLAY_SHOW_HIDE_PASSWORD_FIELDS));
    settingMap.put("setting-displayEula", PwmConstants.ENABLE_EULA_DISPLAY);
    settingMap.put(
        "setting-showStrengthMeter",
        config.readSettingAsBoolean(PwmSetting.PASSWORD_SHOW_STRENGTH_METER));

    {
      long idleSeconds = config.readSettingAsLong(PwmSetting.IDLE_TIMEOUT_SECONDS);
      if (pageUrl == null || pageUrl.isEmpty()) {
        LOGGER.warn(pwmSession, "request to /client data did not incliude pageUrl");
      } else {
        try {
          final PwmURL pwmURL = new PwmURL(new URI(pageUrl), request.getContextPath());
          final TimeDuration maxIdleTime =
              IdleTimeoutCalculator.idleTimeoutForRequest(pwmURL, pwmApplication, pwmSession);
          idleSeconds = maxIdleTime.getTotalSeconds();
        } catch (Exception e) {
          LOGGER.error(
              pwmSession, "error determining idle timeout time for request: " + e.getMessage());
        }
      }
      settingMap.put("MaxInactiveInterval", idleSeconds);
    }
    settingMap.put("paramName.locale", config.readAppProperty(AppProperty.HTTP_PARAM_NAME_LOCALE));
    settingMap.put("startupTime", pwmApplication.getStartupTime());
    settingMap.put("applicationMode", pwmApplication.getApplicationMode());

    final String contextPath = request.getContextPath();
    settingMap.put("url-context", contextPath);
    settingMap.put(
        "url-logout", contextPath + PwmServletDefinition.Logout.servletUrl() + "?idle=true");
    settingMap.put("url-command", contextPath + PwmServletDefinition.Command.servletUrl());
    settingMap.put(
        "url-resources",
        contextPath
            + "/public/resources"
            + pwmApplication.getResourceServletService().getResourceNonce());
    settingMap.put("url-restservice", contextPath + "/public/rest");

    {
      String passwordGuideText =
          pwmApplication
              .getConfig()
              .readSettingAsLocalizedString(
                  PwmSetting.DISPLAY_PASSWORD_GUIDE_TEXT,
                  pwmSession.getSessionStateBean().getLocale());
      final MacroMachine macroMachine =
          pwmSession.getSessionManager().getMacroMachine(pwmApplication);
      passwordGuideText = macroMachine.expandMacros(passwordGuideText);
      settingMap.put("passwordGuideText", passwordGuideText);
    }

    {
      final List<String> formTypeOptions = new ArrayList<>();
      for (final FormConfiguration.Type type : FormConfiguration.Type.values()) {
        formTypeOptions.add(type.toString());
      }
      settingMap.put("formTypeOptions", formTypeOptions);
    }

    {
      final List<String> actionTypeOptions = new ArrayList<>();
      for (final ActionConfiguration.Type type : ActionConfiguration.Type.values()) {
        actionTypeOptions.add(type.toString());
      }
      settingMap.put("actionTypeOptions", actionTypeOptions);
    }

    {
      final List<String> epsTypes = new ArrayList<>();
      for (final Statistic.EpsType loopEpsType : Statistic.EpsType.values()) {
        epsTypes.add(loopEpsType.toString());
      }
      settingMap.put("epsTypes", epsTypes);
    }

    {
      final List<String> epsDurations = new ArrayList<>();
      for (final Statistic.EpsDuration loopEpsDuration : Statistic.EpsDuration.values()) {
        epsDurations.add(loopEpsDuration.toString());
      }
      settingMap.put("epsDurations", epsDurations);
    }

    {
      final Map<String, String> localeInfo = new TreeMap<>();
      final Map<String, String> localeDisplayNames = new TreeMap<>();
      final Map<String, String> localeFlags = new TreeMap<>();

      for (final Locale locale : pwmApplication.getConfig().getKnownLocales()) {
        final String flagCode = pwmApplication.getConfig().getKnownLocaleFlagMap().get(locale);
        localeFlags.put(locale.toString(), flagCode);
        localeInfo.put(
            locale.toString(), locale.getDisplayName() + " - " + locale.getDisplayLanguage(locale));
        localeDisplayNames.put(locale.toString(), locale.getDisplayLanguage());
      }

      settingMap.put("localeInfo", localeInfo);
      settingMap.put("localeDisplayNames", localeDisplayNames);
      settingMap.put("localeFlags", localeFlags);
      settingMap.put("defaultLocale", PwmConstants.DEFAULT_LOCALE.toString());
    }

    if (pwmApplication
            .getConfig()
            .readSettingAsEnum(PwmSetting.LDAP_SELECTABLE_CONTEXT_MODE, SelectableContextMode.class)
        != SelectableContextMode.NONE) {
      final Map<String, Map<String, String>> ldapProfiles = new LinkedHashMap<>();
      for (final String ldapProfile : pwmApplication.getConfig().getLdapProfiles().keySet()) {
        final Map<String, String> contexts =
            pwmApplication.getConfig().getLdapProfiles().get(ldapProfile).getLoginContexts();
        ldapProfiles.put(ldapProfile, contexts);
      }
      settingMap.put("ldapProfiles", ldapProfiles);
    }

    return settingMap;
  }
コード例 #18
0
ファイル: PwmApplication.java プロジェクト: Alqobais/pwm
  private void initialize(final boolean initLogging) throws PwmUnrecoverableException {
    final Date startTime = new Date();

    // initialize log4j
    if (initLogging) {
      final String log4jFileName =
          configuration.readSettingAsString(PwmSetting.EVENTS_JAVA_LOG4JCONFIG_FILE);
      final File log4jFile = Helper.figureFilepath(log4jFileName, applicationPath);
      final String consoleLevel, fileLevel;
      switch (getApplicationMode()) {
        case ERROR:
        case NEW:
          consoleLevel = PwmLogLevel.TRACE.toString();
          fileLevel = PwmLogLevel.TRACE.toString();
          break;

        default:
          consoleLevel = configuration.readSettingAsString(PwmSetting.EVENTS_JAVA_STDOUT_LEVEL);
          fileLevel = configuration.readSettingAsString(PwmSetting.EVENTS_FILE_LEVEL);
          break;
      }

      PwmLogManager.initializeLogger(
          this, configuration, log4jFile, consoleLevel, applicationPath, fileLevel);

      switch (getApplicationMode()) {
        case RUNNING:
          break;

        case ERROR:
          LOGGER.fatal(
              "starting up in ERROR mode! Check log or health check information for cause");
          break;

        default:
          LOGGER.trace(
              "setting log level to TRACE because application mode is " + getApplicationMode());
          break;
      }
    }

    LOGGER.info(
        "initializing, application mode="
            + getApplicationMode()
            + ", applicationPath="
            + (applicationPath == null ? "null" : applicationPath.getAbsolutePath())
            + ", configurationFile="
            + (configurationFile == null ? "null" : configurationFile.getAbsolutePath()));

    this.localDB = Initializer.initializeLocalDB(this);
    this.localDBLogger = PwmLogManager.initializeLocalDBLogger(this);

    // log the loaded configuration
    LOGGER.info("configuration load completed");

    // read the pwm servlet instance id
    instanceID = fetchInstanceID(localDB, this);
    LOGGER.info("using '" + getInstanceID() + "' for instance's ID (instanceID)");

    // read the pwm installation date
    installTime = fetchInstallDate(startupTime);
    LOGGER.debug(
        "this application instance first installed on "
            + PwmConstants.DEFAULT_DATETIME_FORMAT.format(installTime));

    initServices();

    final TimeDuration totalTime = TimeDuration.fromCurrent(startTime);
    LOGGER.info(
        PwmConstants.PWM_APP_NAME
            + " "
            + PwmConstants.SERVLET_VERSION
            + " open for bidness! ("
            + totalTime.asCompactString()
            + ")");
    StatisticsManager.incrementStat(this, Statistic.PWM_STARTUPS);
    LOGGER.debug(
        "buildTime="
            + PwmConstants.BUILD_TIME
            + ", javaLocale="
            + Locale.getDefault()
            + ", DefaultLocale="
            + PwmConstants.DEFAULT_LOCALE);

    final Thread postInitThread =
        new Thread() {
          @Override
          public void run() {
            postInitTasks();
          }
        };
    postInitThread.setDaemon(true);
    postInitThread.setName(Helper.makeThreadName(this, PwmApplication.class));
    postInitThread.start();
  }
コード例 #19
0
  private void publishStatisticsToCloud()
      throws URISyntaxException, IOException, PwmUnrecoverableException {
    final StatsPublishBean statsPublishData;
    {
      final StatisticsBundle bundle = getStatBundleForKey(KEY_CUMULATIVE);
      final Map<String, String> statData = new HashMap<>();
      for (final Statistic loopStat : Statistic.values()) {
        statData.put(loopStat.getKey(), bundle.getStatistic(loopStat));
      }
      final Configuration config = pwmApplication.getConfig();
      final List<String> configuredSettings = new ArrayList<>();
      for (final PwmSetting pwmSetting : config.nonDefaultSettings()) {
        if (!pwmSetting.getCategory().hasProfiles() && !config.isDefaultValue(pwmSetting)) {
          configuredSettings.add(pwmSetting.getKey());
        }
      }
      final Map<String, String> otherData = new HashMap<>();
      otherData.put(
          StatsPublishBean.KEYS.SITE_URL.toString(),
          config.readSettingAsString(PwmSetting.PWM_SITE_URL));
      otherData.put(
          StatsPublishBean.KEYS.SITE_DESCRIPTION.toString(),
          config.readSettingAsString(PwmSetting.PUBLISH_STATS_SITE_DESCRIPTION));
      otherData.put(
          StatsPublishBean.KEYS.INSTALL_DATE.toString(),
          PwmConstants.DEFAULT_DATETIME_FORMAT.format(pwmApplication.getInstallTime()));

      try {
        otherData.put(
            StatsPublishBean.KEYS.LDAP_VENDOR.toString(),
            pwmApplication
                .getProxyChaiProvider(config.getDefaultLdapProfile().getIdentifier())
                .getDirectoryVendor()
                .toString());
      } catch (Exception e) {
        LOGGER.trace("unable to read ldap vendor type for stats publication: " + e.getMessage());
      }

      statsPublishData =
          new StatsPublishBean(
              pwmApplication.getInstanceID(),
              new Date(),
              statData,
              configuredSettings,
              PwmConstants.BUILD_NUMBER,
              PwmConstants.BUILD_VERSION,
              otherData);
    }
    final URI requestURI = new URI(PwmConstants.PWM_URL_CLOUD + "/rest/pwm/statistics");
    final HttpPost httpPost = new HttpPost(requestURI.toString());
    final String jsonDataString = JsonUtil.serialize(statsPublishData);
    httpPost.setEntity(new StringEntity(jsonDataString));
    httpPost.setHeader("Accept", PwmConstants.AcceptValue.json.getHeaderValue());
    httpPost.setHeader("Content-Type", PwmConstants.ContentTypeValue.json.getHeaderValue());
    LOGGER.debug(
        "preparing to send anonymous statistics to "
            + requestURI.toString()
            + ", data to send: "
            + jsonDataString);
    final HttpResponse httpResponse =
        PwmHttpClient.getHttpClient(pwmApplication.getConfig()).execute(httpPost);
    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
      throw new IOException(
          "http response error code: " + httpResponse.getStatusLine().getStatusCode());
    }
    LOGGER.info("published anonymous statistics to " + requestURI.toString());
    try {
      localDB.put(
          LocalDB.DB.PWM_STATS,
          KEY_CLOUD_PUBLISH_TIMESTAMP,
          String.valueOf(System.currentTimeMillis()));
    } catch (LocalDBException e) {
      LOGGER.error(
          "unexpected error trying to save last statistics published time to LocalDB: "
              + e.getMessage());
    }
  }
コード例 #20
0
ファイル: PwmApplication.java プロジェクト: Alqobais/pwm
  private void postInitTasks() {
    final Date startTime = new Date();

    LOGGER.debug("loaded configuration: \n" + configuration.toDebugString());

    // detect if config has been modified since previous startup
    try {
      final String previousHash = readAppAttribute(AppAttribute.CONFIG_HASH);
      final String currentHash = configuration.configurationHash();
      if (previousHash == null || !previousHash.equals(currentHash)) {
        writeAppAttribute(AppAttribute.CONFIG_HASH, currentHash);
        LOGGER.warn(
            "configuration checksum does not match previously seen checksum, configuration has been modified since last startup");
        if (this.getAuditManager() != null) {
          final String modifyMessage =
              "configuration was modified directly (not using ConfigEditor UI)";
          this.getAuditManager()
              .submit(
                  SystemAuditRecord.create(
                      AuditEvent.MODIFY_CONFIGURATION, modifyMessage, this.getInstanceID()));
        }
      }
    } catch (Exception e) {
      LOGGER.debug(
          "unable to detect if configuration has been modified since previous startup: "
              + e.getMessage());
    }

    if (this.getConfig() != null) {
      final Map<AppProperty, String> nonDefaultProperties =
          getConfig().readAllNonDefaultAppProperties();
      if (nonDefaultProperties != null && !nonDefaultProperties.isEmpty()) {
        final Map<String, String> tempMap = new LinkedHashMap<>();
        for (final AppProperty loopProperty : nonDefaultProperties.keySet()) {
          tempMap.put(loopProperty.getKey(), nonDefaultProperties.get(loopProperty));
        }
        LOGGER.trace(
            "non-default app properties read from configuration: "
                + JsonUtil.serializeMap(tempMap));
      } else {
        LOGGER.trace("no non-default app properties in configuration");
      }
    }

    // send system audit event
    final SystemAuditRecord auditRecord =
        SystemAuditRecord.create(AuditEvent.STARTUP, null, getInstanceID());
    try {
      getAuditManager().submit(auditRecord);
    } catch (PwmException e) {
      LOGGER.warn("unable to submit alert event " + JsonUtil.serialize(auditRecord));
    }

    try {
      Map<PwmAboutProperty, String> infoMap = Helper.makeInfoBean(this);
      LOGGER.trace("application info: " + JsonUtil.serializeMap(infoMap));
    } catch (Exception e) {
      LOGGER.error("error generating about application bean: " + e.getMessage());
    }

    try {
      this.getIntruderManager()
          .clear(RecordType.USERNAME, PwmConstants.CONFIGMANAGER_INTRUDER_USERNAME);
    } catch (Exception e) {
      LOGGER.debug(
          "error while clearing configmanager-intruder-username from intruder table: "
              + e.getMessage());
    }

    LOGGER.trace(
        "completed post init tasks in " + TimeDuration.fromCurrent(startTime).asCompactString());
  }
コード例 #21
0
  private void handleCreateRequest(
      final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean)
      throws PwmUnrecoverableException, ChaiUnavailableException, IOException, ServletException {
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final LocalSessionStateBean ssBean = pwmSession.getSessionStateBean();
    final Configuration config = pwmApplication.getConfig();
    final Locale locale = ssBean.getLocale();

    final List<FormConfiguration> guestUserForm = config.readSettingAsForm(PwmSetting.GUEST_FORM);

    try {
      // read the values from the request
      final Map<FormConfiguration, String> formValues =
          FormUtility.readFormValuesFromRequest(pwmRequest, guestUserForm, locale);

      // read the expiration date from the request.
      final Date expirationDate = readExpirationFromRequest(pwmRequest);

      // see if the values meet form requirements.
      FormUtility.validateFormValues(config, formValues, locale);

      // read new user DN
      final String guestUserDN = determineUserDN(formValues, config);

      // read a chai provider to make the user
      final ChaiProvider provider = pwmSession.getSessionManager().getChaiProvider();

      // set up the user creation attributes
      final Map<String, String> createAttributes = new HashMap<>();
      for (final FormConfiguration formItem : formValues.keySet()) {
        LOGGER.debug(
            pwmSession,
            "Attribute from form: " + formItem.getName() + " = " + formValues.get(formItem));
        final String n = formItem.getName();
        final String v = formValues.get(formItem);
        if (n != null && n.length() > 0 && v != null && v.length() > 0) {
          createAttributes.put(n, v);
        }
      }

      // Write creator DN
      createAttributes.put(
          config.readSettingAsString(PwmSetting.GUEST_ADMIN_ATTRIBUTE),
          pwmSession.getUserInfoBean().getUserIdentity().getUserDN());

      // read the creation object classes.
      final Set<String> createObjectClasses =
          new HashSet<>(config.readSettingAsStringArray(PwmSetting.DEFAULT_OBJECT_CLASSES));

      provider.createEntry(guestUserDN, createObjectClasses, createAttributes);
      LOGGER.info(pwmSession, "created user object: " + guestUserDN);

      final ChaiUser theUser = ChaiFactory.createChaiUser(guestUserDN, provider);
      final UserIdentity userIdentity =
          new UserIdentity(
              guestUserDN, pwmSession.getUserInfoBean().getUserIdentity().getLdapProfileID());

      // write the expiration date:
      if (expirationDate != null) {
        final String expirationAttr =
            config.readSettingAsString(PwmSetting.GUEST_EXPIRATION_ATTRIBUTE);
        theUser.writeDateAttribute(expirationAttr, expirationDate);
      }

      final PwmPasswordPolicy passwordPolicy =
          PasswordUtility.readPasswordPolicyForUser(
              pwmApplication, pwmSession.getLabel(), userIdentity, theUser, locale);
      final PasswordData newPassword =
          RandomPasswordGenerator.createRandomPassword(
              pwmSession.getLabel(), passwordPolicy, pwmApplication);
      theUser.setPassword(newPassword.getStringValue());
      /*
      final UserInfoBean guestUserInfoBean = new UserInfoBean();
      final UserStatusReader userStatusReader = new UserStatusReader(pwmApplication);
      userStatusReader.populateUserInfoBean(
              pwmSession.getLabel(),
              guestUserInfoBean,
              pwmSession.getSessionStateBean().getLocale(),
              userIdentity,
              theUser.getChaiProvider()
      );
      */

      { // execute configured actions
        LOGGER.debug(pwmSession, "executing configured actions to user " + theUser.getEntryDN());
        final List<ActionConfiguration> actions =
            pwmApplication.getConfig().readSettingAsAction(PwmSetting.GUEST_WRITE_ATTRIBUTES);
        if (actions != null && !actions.isEmpty()) {
          final MacroMachine macroMachine = MacroMachine.forUser(pwmRequest, userIdentity);

          final ActionExecutor actionExecutor =
              new ActionExecutor.ActionExecutorSettings(pwmApplication, theUser)
                  .setExpandPwmMacros(true)
                  .setMacroMachine(macroMachine)
                  .createActionExecutor();

          actionExecutor.executeActions(actions, pwmSession);
        }
      }

      // everything good so forward to success page.
      this.sendGuestUserEmailConfirmation(pwmRequest, userIdentity);

      pwmApplication.getStatisticsManager().incrementValue(Statistic.NEW_USERS);

      pwmRequest.getPwmResponse().forwardToSuccessPage(Message.Success_CreateGuest);
    } catch (ChaiOperationException e) {
      final ErrorInformation info =
          new ErrorInformation(
              PwmError.ERROR_NEW_USER_FAILURE, "error creating user: " + e.getMessage());
      pwmRequest.setResponseError(info);
      LOGGER.warn(pwmSession, info);
      this.forwardToJSP(pwmRequest, guestRegistrationBean);
    } catch (PwmOperationalException e) {
      LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr());
      pwmRequest.setResponseError(e.getErrorInformation());
      this.forwardToJSP(pwmRequest, guestRegistrationBean);
    }
  }
コード例 #22
0
  protected void handleSearchRequest(
      final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean)
      throws ServletException, ChaiUnavailableException, IOException, PwmUnrecoverableException {
    LOGGER.trace(pwmRequest, "Enter: handleSearchRequest(...)");
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final ChaiProvider chaiProvider = pwmSession.getSessionManager().getChaiProvider();
    final Configuration config = pwmApplication.getConfig();

    final String adminDnAttribute = config.readSettingAsString(PwmSetting.GUEST_ADMIN_ATTRIBUTE);
    final Boolean origAdminOnly =
        config.readSettingAsBoolean(PwmSetting.GUEST_EDIT_ORIG_ADMIN_ONLY);

    final String usernameParam = pwmRequest.readParameterAsString("username");
    final GuestRegistrationBean guBean =
        pwmApplication.getSessionStateService().getBean(pwmRequest, GuestRegistrationBean.class);

    final UserSearchEngine.SearchConfiguration searchConfiguration =
        new UserSearchEngine.SearchConfiguration();
    searchConfiguration.setChaiProvider(chaiProvider);
    searchConfiguration.setContexts(
        Collections.singletonList(config.readSettingAsString(PwmSetting.GUEST_CONTEXT)));
    searchConfiguration.setEnableContextValidation(false);
    searchConfiguration.setUsername(usernameParam);
    final UserSearchEngine userSearchEngine =
        new UserSearchEngine(pwmApplication, pwmSession.getLabel());

    try {
      final UserIdentity theGuest = userSearchEngine.performSingleUserSearch(searchConfiguration);
      final FormMap formProps = guBean.getFormValues();
      try {
        final List<FormConfiguration> guestUpdateForm =
            config.readSettingAsForm(PwmSetting.GUEST_UPDATE_FORM);
        final Set<String> involvedAttrs = new HashSet<>();
        for (final FormConfiguration formItem : guestUpdateForm) {
          if (!formItem.getName().equalsIgnoreCase(HTTP_PARAM_EXPIRATION_DATE)) {
            involvedAttrs.add(formItem.getName());
          }
        }
        final UserDataReader userDataReader =
            LdapUserDataReader.selfProxiedReader(pwmApplication, pwmSession, theGuest);
        final Map<String, String> userAttrValues =
            userDataReader.readStringAttributes(involvedAttrs);
        if (origAdminOnly && adminDnAttribute != null && adminDnAttribute.length() > 0) {
          final String origAdminDn = userAttrValues.get(adminDnAttribute);
          if (origAdminDn != null && origAdminDn.length() > 0) {
            if (!pwmSession
                .getUserInfoBean()
                .getUserIdentity()
                .getUserDN()
                .equalsIgnoreCase(origAdminDn)) {
              final ErrorInformation info = new ErrorInformation(PwmError.ERROR_ORIG_ADMIN_ONLY);
              pwmRequest.setResponseError(info);
              LOGGER.warn(pwmSession, info);
              this.forwardToJSP(pwmRequest, guestRegistrationBean);
            }
          }
        }
        final String expirationAttribute =
            config.readSettingAsString(PwmSetting.GUEST_EXPIRATION_ATTRIBUTE);
        if (expirationAttribute != null && expirationAttribute.length() > 0) {
          final Date expiration = userDataReader.readDateAttribute(expirationAttribute);
          if (expiration != null) {
            guBean.setUpdateUserExpirationDate(expiration);
          }
        }

        for (final FormConfiguration formItem : guestUpdateForm) {
          final String key = formItem.getName();
          final String value = userAttrValues.get(key);
          if (value != null) {
            formProps.put(key, value);
          }
        }

        guBean.setUpdateUserIdentity(theGuest);

        this.forwardToUpdateJSP(pwmRequest, guestRegistrationBean);
        return;
      } catch (ChaiOperationException e) {
        LOGGER.warn(pwmSession, "error reading current attributes for user: " + e.getMessage());
      }
    } catch (PwmOperationalException e) {
      final ErrorInformation error = e.getErrorInformation();
      pwmRequest.setResponseError(error);
      this.forwardToJSP(pwmRequest, guestRegistrationBean);
      return;
    }
    this.forwardToJSP(pwmRequest, guestRegistrationBean);
  }
コード例 #23
0
ファイル: ConfigGuideServlet.java プロジェクト: aboieriu/pwm
  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);
  }
コード例 #24
0
  protected void handleUpdateRequest(
      final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean)
      throws ServletException, ChaiUnavailableException, IOException, PwmUnrecoverableException {
    // Fetch the session state bean.
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final LocalSessionStateBean ssBean = pwmSession.getSessionStateBean();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final Configuration config = pwmApplication.getConfig();

    final List<FormConfiguration> formItems =
        pwmApplication.getConfig().readSettingAsForm(PwmSetting.GUEST_UPDATE_FORM);
    final String expirationAttribute =
        config.readSettingAsString(PwmSetting.GUEST_EXPIRATION_ATTRIBUTE);

    try {
      // read the values from the request
      final Map<FormConfiguration, String> formValues =
          FormUtility.readFormValuesFromRequest(pwmRequest, formItems, pwmRequest.getLocale());

      // see if the values meet form requirements.
      FormUtility.validateFormValues(config, formValues, ssBean.getLocale());

      // read current values from user.
      final ChaiUser theGuest =
          pwmSession
              .getSessionManager()
              .getActor(pwmApplication, guestRegistrationBean.getUpdateUserIdentity());

      // check unique fields against ldap
      FormUtility.validateFormValueUniqueness(
          pwmApplication,
          formValues,
          ssBean.getLocale(),
          Collections.singletonList(guestRegistrationBean.getUpdateUserIdentity()),
          false);

      final Date expirationDate = readExpirationFromRequest(pwmRequest);

      // Update user attributes
      Helper.writeFormValuesToLdap(pwmApplication, pwmSession, theGuest, formValues, false);

      // Write expirationDate
      if (expirationDate != null) {
        theGuest.writeDateAttribute(expirationAttribute, expirationDate);
      }

      // send email.
      final UserStatusReader userStatusReader =
          new UserStatusReader(pwmApplication, pwmSession.getLabel());
      final UserInfoBean guestUserInfoBean = new UserInfoBean();
      userStatusReader.populateUserInfoBean(
          guestUserInfoBean,
          pwmSession.getSessionStateBean().getLocale(),
          guestRegistrationBean.getUpdateUserIdentity(),
          theGuest.getChaiProvider());
      this.sendUpdateGuestEmailConfirmation(pwmRequest, guestUserInfoBean);

      pwmApplication.getStatisticsManager().incrementValue(Statistic.UPDATED_GUESTS);

      // everything good so forward to confirmation page.
      pwmRequest.getPwmResponse().forwardToSuccessPage(Message.Success_UpdateGuest);
      return;
    } catch (PwmOperationalException e) {
      LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr());
      pwmRequest.setResponseError(e.getErrorInformation());
    } catch (ChaiOperationException e) {
      final ErrorInformation info =
          new ErrorInformation(
              PwmError.ERROR_UNKNOWN, "unexpected error writing to ldap: " + e.getMessage());
      LOGGER.error(pwmSession, info);
      pwmRequest.setResponseError(info);
    }
    this.forwardToUpdateJSP(pwmRequest, guestRegistrationBean);
  }