Esempio n. 1
0
  private void handleEnterCodeRequest(
      final PwmRequest pwmRequest, final UpdateProfileBean updateProfileBean)
      throws PwmUnrecoverableException, IOException, ServletException, ChaiUnavailableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final String userEnteredCode = pwmRequest.readParameterAsString(PwmConstants.PARAM_TOKEN);

    boolean tokenPassed = false;
    ErrorInformation errorInformation = null;
    try {
      final TokenPayload tokenPayload =
          pwmApplication
              .getTokenService()
              .processUserEnteredCode(
                  pwmSession, pwmRequest.getUserInfoIfLoggedIn(), null, userEnteredCode);
      if (tokenPayload != null) {
        if (TokenType.UPDATE_EMAIL.matchesName(tokenPayload.getName())) {
          LOGGER.debug(pwmRequest, "email token passed");

          updateProfileBean
              .getTokenVerificationProgress()
              .getPassedTokens()
              .add(TokenVerificationProgress.TokenChannel.EMAIL);
          updateProfileBean
              .getTokenVerificationProgress()
              .getIssuedTokens()
              .add(TokenVerificationProgress.TokenChannel.EMAIL);
          updateProfileBean.getTokenVerificationProgress().setPhase(null);
          tokenPassed = true;
        } else if (TokenType.UPDATE_SMS.matchesName(tokenPayload.getName())) {
          LOGGER.debug(pwmRequest, "SMS token passed");
          updateProfileBean
              .getTokenVerificationProgress()
              .getPassedTokens()
              .add(TokenVerificationProgress.TokenChannel.SMS);
          updateProfileBean
              .getTokenVerificationProgress()
              .getIssuedTokens()
              .add(TokenVerificationProgress.TokenChannel.SMS);
          updateProfileBean.getTokenVerificationProgress().setPhase(null);
          tokenPassed = true;
        } else {
          final String errorMsg = "token name/type is not recognized: " + tokenPayload.getName();
          errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, errorMsg);
        }
      }
    } catch (PwmOperationalException e) {
      final String errorMsg = "token incorrect: " + e.getMessage();
      errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, errorMsg);
    }

    if (!tokenPassed) {
      if (errorInformation == null) {
        errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT);
      }
      LOGGER.debug(pwmSession, errorInformation.toDebugStr());
      pwmRequest.setResponseError(errorInformation);
    }
  }
Esempio n. 2
0
 protected GuestRegistrationAction readProcessAction(final PwmRequest request)
     throws PwmUnrecoverableException {
   try {
     return GuestRegistrationAction.valueOf(
         request.readParameterAsString(PwmConstants.PARAM_ACTION_REQUEST));
   } catch (IllegalArgumentException e) {
     return null;
   }
 }
Esempio n. 3
0
 protected void handleSelectPageRequest(
     final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean)
     throws PwmUnrecoverableException, IOException, ServletException {
   final String requestedPage = pwmRequest.readParameterAsString("page");
   try {
     guestRegistrationBean.setCurrentPage(Page.valueOf(requestedPage));
   } catch (IllegalArgumentException e) {
     LOGGER.error(pwmRequest, "unknown page select request: " + requestedPage);
   }
   this.forwardToJSP(pwmRequest, guestRegistrationBean);
 }
Esempio n. 4
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());
 }
Esempio n. 5
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;
  }
Esempio n. 6
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);
  }
Esempio n. 7
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);
    }
  }
  static boolean checkAuthentication(
      final PwmRequest pwmRequest, final ConfigManagerBean configManagerBean)
      throws IOException, PwmUnrecoverableException, ServletException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final ConfigurationReader runningConfigReader =
        ContextManager.getContextManager(pwmRequest.getHttpServletRequest().getSession())
            .getConfigReader();
    final StoredConfigurationImpl storedConfig = runningConfigReader.getStoredConfiguration();

    boolean authRequired = false;
    if (storedConfig.hasPassword()) {
      authRequired = true;
    }

    if (PwmApplication.MODE.RUNNING == pwmRequest.getPwmApplication().getApplicationMode()) {
      if (!pwmSession.getSessionStateBean().isAuthenticated()) {
        throw new PwmUnrecoverableException(PwmError.ERROR_AUTHENTICATION_REQUIRED);
      }

      if (!pwmRequest
          .getPwmSession()
          .getSessionManager()
          .checkPermission(pwmRequest.getPwmApplication(), Permission.PWMADMIN)) {
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNAUTHORIZED);
        pwmRequest.respondWithError(errorInformation);
        return true;
      }

      if (pwmSession.getLoginInfoBean().getAuthenticationType()
          != AuthenticationType.AUTHENTICATED) {
        throw new PwmUnrecoverableException(
            new ErrorInformation(
                PwmError.ERROR_AUTHENTICATION_REQUIRED,
                "Username/Password authentication is required to edit configuration.  This session has not been authenticated using a user password (SSO or other method used)."));
      }
    }

    if (PwmApplication.MODE.CONFIGURATION != pwmRequest.getPwmApplication().getApplicationMode()) {
      authRequired = true;
    }

    if (!authRequired) {
      return false;
    }

    if (!storedConfig.hasPassword()) {
      final String errorMsg = "config file does not have a configuration password";
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, errorMsg, new String[] {errorMsg});
      pwmRequest.respondWithError(errorInformation, true);
      return true;
    }

    if (configManagerBean.isPasswordVerified()) {
      return false;
    }

    String persistentLoginValue = null;
    boolean persistentLoginAccepted = false;
    boolean persistentLoginEnabled = false;
    if (pwmRequest.getConfig().isDefaultValue(PwmSetting.PWM_SECURITY_KEY)) {
      LOGGER.debug(pwmRequest, "security not available, persistent login not possible.");
    } else {
      persistentLoginEnabled = true;
      final PwmSecurityKey securityKey = pwmRequest.getConfig().getSecurityKey();

      if (PwmApplication.MODE.RUNNING == pwmRequest.getPwmApplication().getApplicationMode()) {
        persistentLoginValue =
            SecureEngine.hash(
                storedConfig.readConfigProperty(ConfigurationProperty.PASSWORD_HASH)
                    + pwmSession.getUserInfoBean().getUserIdentity().toDelimitedKey(),
                PwmHashAlgorithm.SHA512);

      } else {
        persistentLoginValue =
            SecureEngine.hash(
                storedConfig.readConfigProperty(ConfigurationProperty.PASSWORD_HASH),
                PwmHashAlgorithm.SHA512);
      }

      {
        final String cookieStr =
            ServletHelper.readCookie(
                pwmRequest.getHttpServletRequest(), PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN);
        if (securityKey != null && cookieStr != null && !cookieStr.isEmpty()) {
          try {
            final String jsonStr = pwmApplication.getSecureService().decryptStringValue(cookieStr);
            final PersistentLoginInfo persistentLoginInfo =
                JsonUtil.deserialize(jsonStr, PersistentLoginInfo.class);
            if (persistentLoginInfo != null && persistentLoginValue != null) {
              if (persistentLoginInfo.getExpireDate().after(new Date())) {
                if (persistentLoginValue.equals(persistentLoginInfo.getPassword())) {
                  persistentLoginAccepted = true;
                  LOGGER.debug(
                      pwmRequest,
                      "accepting persistent config login from cookie (expires "
                          + PwmConstants.DEFAULT_DATETIME_FORMAT.format(
                              persistentLoginInfo.getExpireDate())
                          + ")");
                }
              }
            }
          } catch (Exception e) {
            LOGGER.error(
                pwmRequest, "error examining persistent config login cookie: " + e.getMessage());
          }
          if (!persistentLoginAccepted) {
            Cookie removalCookie = new Cookie(PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN, null);
            removalCookie.setMaxAge(0);
            pwmRequest.getPwmResponse().addCookie(removalCookie);
            LOGGER.debug(pwmRequest, "removing non-working persistent config login cookie");
          }
        }
      }
    }

    final String password = pwmRequest.readParameterAsString("password");
    boolean passwordAccepted = false;
    if (!persistentLoginAccepted) {
      if (password != null && password.length() > 0) {
        if (storedConfig.verifyPassword(password)) {
          passwordAccepted = true;
          LOGGER.trace(pwmRequest, "valid configuration password accepted");
          updateLoginHistory(pwmRequest, pwmRequest.getUserInfoIfLoggedIn(), true);
        } else {
          LOGGER.trace(pwmRequest, "configuration password is not correct");
          pwmApplication.getIntruderManager().convenience().markAddressAndSession(pwmSession);
          pwmApplication
              .getIntruderManager()
              .mark(
                  RecordType.USERNAME,
                  PwmConstants.CONFIGMANAGER_INTRUDER_USERNAME,
                  pwmSession.getLabel());
          final ErrorInformation errorInformation =
              new ErrorInformation(PwmError.ERROR_WRONGPASSWORD);
          pwmRequest.setResponseError(errorInformation);
          updateLoginHistory(pwmRequest, pwmRequest.getUserInfoIfLoggedIn(), false);
        }
      }
    }

    if ((persistentLoginAccepted || passwordAccepted)) {
      configManagerBean.setPasswordVerified(true);
      pwmApplication.getIntruderManager().convenience().clearAddressAndSession(pwmSession);
      pwmApplication
          .getIntruderManager()
          .clear(RecordType.USERNAME, PwmConstants.CONFIGMANAGER_INTRUDER_USERNAME);
      if (persistentLoginEnabled
          && !persistentLoginAccepted
          && "on".equals(pwmRequest.readParameterAsString("remember"))) {
        final int persistentSeconds = figureMaxLoginSeconds(pwmRequest);
        if (persistentSeconds > 0) {
          final Date expirationDate =
              new Date(System.currentTimeMillis() + (persistentSeconds * 1000));
          final PersistentLoginInfo persistentLoginInfo =
              new PersistentLoginInfo(expirationDate, persistentLoginValue);
          final String jsonPersistentLoginInfo = JsonUtil.serialize(persistentLoginInfo);
          final String cookieValue =
              pwmApplication.getSecureService().encryptToString(jsonPersistentLoginInfo);
          pwmRequest
              .getPwmResponse()
              .writeCookie(
                  PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN, cookieValue, persistentSeconds);
          LOGGER.debug(
              pwmRequest,
              "set persistent config login cookie (expires "
                  + PwmConstants.DEFAULT_DATETIME_FORMAT.format(expirationDate)
                  + ")");
        }
      }

      if (configManagerBean.getPrePasswordEntryUrl() != null) {
        final String originalUrl = configManagerBean.getPrePasswordEntryUrl();
        configManagerBean.setPrePasswordEntryUrl(null);
        pwmRequest.getPwmResponse().sendRedirect(originalUrl);
        return true;
      }
      return false;
    }

    if (configManagerBean.getPrePasswordEntryUrl() == null) {
      configManagerBean.setPrePasswordEntryUrl(
          pwmRequest.getHttpServletRequest().getRequestURL().toString());
    }

    forwardToJsp(pwmRequest);
    return true;
  }