Esempio n. 1
0
  static Set<TokenVerificationProgress.TokenChannel> determineTokenPhaseRequired(
      final PwmRequest pwmRequest,
      final UpdateProfileBean updateProfileBean,
      final UpdateAttributesProfile updateAttributesProfile)
      throws PwmUnrecoverableException {
    final Set<TokenVerificationProgress.TokenChannel> returnObj = new HashSet<>();

    final Map<String, String> userFormData = updateProfileBean.getFormData();
    Map<String, String> ldapData = null;

    if (updateAttributesProfile.readSettingAsBoolean(
        PwmSetting.UPDATE_PROFILE_EMAIL_VERIFICATION)) {
      final String emailAddressAttribute =
          pwmRequest.getConfig().readSettingAsString(PwmSetting.EMAIL_USER_MAIL_ATTRIBUTE);
      if (userFormData.containsKey(emailAddressAttribute)) {
        ldapData = formDataFromLdap(pwmRequest, updateAttributesProfile);
        if (userFormData.get(emailAddressAttribute) != null
            && !userFormData
                .get(emailAddressAttribute)
                .equalsIgnoreCase(ldapData.get(emailAddressAttribute))) {
          returnObj.add(TokenVerificationProgress.TokenChannel.EMAIL);
        }
      } else {
        LOGGER.warn(
            pwmRequest,
            "email verification enabled, but email attribute '"
                + emailAddressAttribute
                + "' is not in update form");
      }
    }

    if (updateAttributesProfile.readSettingAsBoolean(PwmSetting.UPDATE_PROFILE_SMS_VERIFICATION)) {
      final String phoneNumberAttribute =
          pwmRequest.getConfig().readSettingAsString(PwmSetting.SMS_USER_PHONE_ATTRIBUTE);
      if (userFormData.containsKey(phoneNumberAttribute)) {
        if (ldapData == null) {
          ldapData = formDataFromLdap(pwmRequest, updateAttributesProfile);
        }
        if (userFormData.get(phoneNumberAttribute) != null
            && !userFormData
                .get(phoneNumberAttribute)
                .equalsIgnoreCase(ldapData.get(phoneNumberAttribute))) {
          returnObj.add(TokenVerificationProgress.TokenChannel.SMS);
        }
      } else {
        LOGGER.warn(
            pwmRequest,
            "sms verification enabled, but phone attribute '"
                + phoneNumberAttribute
                + "' is not in update form");
      }
    }

    return returnObj;
  }
Esempio n. 2
0
  protected static void restValidateForm(
      final PwmRequest pwmRequest, final UpdateProfileBean updateProfileBean)
      throws IOException, ServletException, PwmUnrecoverableException, ChaiUnavailableException {
    boolean success = true;
    String userMessage =
        Message.getLocalizedMessage(
            pwmRequest.getLocale(), Message.Success_UpdateForm, pwmRequest.getConfig());
    final Map<FormConfiguration, String> formValues = updateProfileBean.getFormData();

    try {
      // read in the responses from the request
      readFromJsonRequest(pwmRequest, updateProfileBean);

      // verify form meets the form requirements
      verifyFormAttributes(pwmRequest, formValues, true);
    } catch (PwmOperationalException e) {
      success = false;
      userMessage =
          e.getErrorInformation()
              .toUserStr(pwmRequest.getPwmSession(), pwmRequest.getPwmApplication());
    }

    final LinkedHashMap<String, String> outputMap = new LinkedHashMap<>();
    outputMap.put("version", "1");
    outputMap.put("message", userMessage);
    outputMap.put("success", String.valueOf(success));

    pwmRequest.outputJsonResult(new RestResultBean(outputMap));
  }
Esempio n. 3
0
 void initRequestAttributes(final PwmRequest pwmRequest) throws PwmUnrecoverableException {
   final ConfigurationReader configurationReader =
       pwmRequest.getContextManager().getConfigReader();
   pwmRequest.setAttribute(
       PwmRequest.Attribute.PageTitle,
       LocaleHelper.getLocalizedMessage(Config.Title_ConfigManager, pwmRequest));
   pwmRequest.setAttribute(
       PwmRequest.Attribute.ApplicationPath,
       pwmRequest.getPwmApplication().getPwmEnvironment().getApplicationPath().getAbsolutePath());
   pwmRequest.setAttribute(
       PwmRequest.Attribute.ConfigFilename, configurationReader.getConfigFile().getAbsolutePath());
   {
     final Date lastModifyTime = configurationReader.getStoredConfiguration().modifyTime();
     final String output =
         lastModifyTime == null
             ? LocaleHelper.getLocalizedMessage(Display.Value_NotApplicable, pwmRequest)
             : PwmConstants.DEFAULT_DATETIME_FORMAT.format(lastModifyTime);
     pwmRequest.setAttribute(PwmRequest.Attribute.ConfigLastModified, output);
   }
   pwmRequest.setAttribute(
       PwmRequest.Attribute.ConfigHasPassword,
       LocaleHelper.booleanString(
           configurationReader.getStoredConfiguration().hasPassword(),
           pwmRequest.getLocale(),
           pwmRequest.getConfig()));
 }
Esempio n. 4
0
 protected void forwardToConfirmForm(final PwmRequest pwmRequest)
     throws ServletException, PwmUnrecoverableException, IOException {
   final List<FormConfiguration> form =
       pwmRequest.getConfig().readSettingAsForm(PwmSetting.UPDATE_PROFILE_FORM);
   final Map<FormConfiguration, String> formData =
       pwmRequest.getPwmSession().getUpdateProfileBean().getFormData();
   pwmRequest.addFormInfoToRequestAttr(form, formData, true, false);
   pwmRequest.forwardToJsp(PwmConstants.JSP_URL.UPDATE_ATTRIBUTES_CONFIRM);
 }
Esempio n. 5
0
  private void readFormParametersFromRequest(
      final PwmRequest pwmRequest, final UpdateProfileBean updateProfileBean)
      throws PwmUnrecoverableException, PwmDataValidationException, ChaiUnavailableException {
    final List<FormConfiguration> formFields =
        pwmRequest.getConfig().readSettingAsForm(PwmSetting.UPDATE_PROFILE_FORM);

    final Map<FormConfiguration, String> existingForm = updateProfileBean.getFormData();

    // read the values from the request
    existingForm.putAll(
        FormUtility.readFormValuesFromRequest(pwmRequest, formFields, pwmRequest.getLocale()));
  }
Esempio n. 6
0
  private static void readFromJsonRequest(
      final PwmRequest pwmRequest, final UpdateProfileBean updateProfileBean)
      throws PwmDataValidationException, PwmUnrecoverableException, IOException {
    final List<FormConfiguration> formFields =
        pwmRequest.getConfig().readSettingAsForm(PwmSetting.UPDATE_PROFILE_FORM);
    final Map<FormConfiguration, String> existingForm = updateProfileBean.getFormData();

    final Map<String, String> clientValues = pwmRequest.readBodyAsJsonStringMap();

    if (clientValues != null) {
      existingForm.putAll(
          FormUtility.readFormValuesFromMap(clientValues, formFields, pwmRequest.getLocale()));
    }
  }
Esempio n. 7
0
  private void forwardToUpdateJSP(
      final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean)
      throws IOException, ServletException, PwmUnrecoverableException {
    calculateFutureDateFlags(pwmRequest, guestRegistrationBean);
    final List<FormConfiguration> guestUpdateForm =
        pwmRequest.getConfig().readSettingAsForm(PwmSetting.GUEST_UPDATE_FORM);
    final Map<FormConfiguration, String> formValueMap = new LinkedHashMap<>();
    for (final FormConfiguration formConfiguration : guestUpdateForm) {
      final String value = guestRegistrationBean.getFormValues().get(formConfiguration.getName());
      formValueMap.put(formConfiguration, value);
    }

    pwmRequest.addFormInfoToRequestAttr(guestUpdateForm, formValueMap, false, false);
    pwmRequest.forwardToJsp(PwmConstants.JSP_URL.GUEST_UPDATE);
  }
Esempio n. 8
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);
  }
Esempio n. 9
0
  private static void verifyFormAttributes(
      final PwmRequest pwmRequest,
      final Map<FormConfiguration, String> formValues,
      final boolean allowResultCaching)
      throws PwmOperationalException, PwmUnrecoverableException {
    final Locale userLocale = pwmRequest.getLocale();

    // see if the values meet form requirements.
    FormUtility.validateFormValues(pwmRequest.getConfig(), formValues, userLocale);

    // check unique fields against ldap
    FormUtility.validateFormValueUniqueness(
        pwmRequest.getPwmApplication(),
        formValues,
        userLocale,
        Collections.singletonList(pwmRequest.getPwmSession().getUserInfoBean().getUserIdentity()),
        allowResultCaching);
  }
Esempio n. 10
0
  private void calculateFutureDateFlags(
      final PwmRequest pwmRequest, GuestRegistrationBean guestRegistrationBean) {
    final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    final long maxValidDays =
        pwmRequest.getConfig().readSettingAsLong(PwmSetting.GUEST_MAX_VALID_DAYS);
    pwmRequest.setAttribute(
        PwmRequest.Attribute.GuestMaximumValidDays, String.valueOf(maxValidDays));

    final String maxExpirationDate;
    {
      if (maxValidDays > 0) {
        long futureMS = maxValidDays * 24 * 60 * 60 * 1000;
        Date maxValidDate = new Date(new Date().getTime() + (futureMS));
        maxExpirationDate = DATE_FORMAT.format(maxValidDate);
      } else {
        maxExpirationDate = "";
      }
    }
    final String currentExpirationDate;
    {
      String selectedDate = guestRegistrationBean.getFormValues().get(HTTP_PARAM_EXPIRATION_DATE);
      if (selectedDate == null || selectedDate.isEmpty()) {
        Date currentDate = guestRegistrationBean.getUpdateUserExpirationDate();

        if (currentDate == null) {
          currentExpirationDate = maxExpirationDate;
        } else {
          currentExpirationDate = DATE_FORMAT.format(currentDate);
        }
      } else {
        currentExpirationDate = DATE_FORMAT.format(new Date());
      }
    }

    pwmRequest.setAttribute(PwmRequest.Attribute.GuestCurrentExpirationDate, currentExpirationDate);
    pwmRequest.setAttribute(PwmRequest.Attribute.GuestMaximumExpirationDate, maxExpirationDate);
  }
Esempio n. 11
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);
    }
  }
Esempio n. 12
0
  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;
  }
Esempio n. 13
0
 static int figureMaxLoginSeconds(final PwmRequest pwmRequest) {
   return Integer.parseInt(
       pwmRequest.getConfig().readAppProperty(AppProperty.CONFIG_MAX_PERSISTENT_LOGIN_SECONDS));
 }