Esempio n. 1
0
  public static Map<String, String> defaultForm(PwmSettingTemplate template) {
    final Map<String, String> defaultLdapForm = new HashMap<>();

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

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

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

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

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

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

    return Collections.unmodifiableMap(defaultLdapForm);
  }
Esempio n. 2
0
  public static void restUploadConfig(final PwmRequest pwmRequest)
      throws PwmUnrecoverableException, IOException, ServletException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final HttpServletRequest req = pwmRequest.getHttpServletRequest();

    if (pwmApplication.getApplicationMode() == PwmApplication.MODE.RUNNING) {
      final String errorMsg = "config upload is not permitted when in running mode";
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.CONFIG_UPLOAD_FAILURE, errorMsg, new String[] {errorMsg});
      pwmRequest.respondWithError(errorInformation, true);
      return;
    }

    if (ServletFileUpload.isMultipartContent(req)) {
      final InputStream uploadedFile = ServletHelper.readFileUpload(req, "uploadFile");
      if (uploadedFile != null) {
        try {
          final StoredConfigurationImpl storedConfig =
              StoredConfigurationImpl.fromXml(uploadedFile);
          final List<String> configErrors = storedConfig.validateValues();
          if (configErrors != null && !configErrors.isEmpty()) {
            throw new PwmOperationalException(
                new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, configErrors.get(0)));
          }
          writeConfig(ContextManager.getContextManager(req.getSession()), storedConfig);
          LOGGER.trace(pwmSession, "read config from file: " + storedConfig.toString());
          final RestResultBean restResultBean = new RestResultBean();
          restResultBean.setSuccessMessage("read message");
          pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
          req.getSession().invalidate();
        } catch (PwmException e) {
          final RestResultBean restResultBean =
              RestResultBean.fromError(e.getErrorInformation(), pwmRequest);
          pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
          LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr());
        }
      } else {
        final ErrorInformation errorInformation =
            new ErrorInformation(
                PwmError.CONFIG_UPLOAD_FAILURE,
                "error reading config file: no file present in upload");
        final RestResultBean restResultBean =
            RestResultBean.fromError(errorInformation, pwmRequest);
        pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
        LOGGER.error(pwmSession, errorInformation.toDebugStr());
      }
    }
  }
Esempio n. 3
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);
    }
  }
Esempio n. 4
0
  private void restLdapHealth(final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
      throws IOException, PwmUnrecoverableException {
    final Configuration tempConfiguration =
        new Configuration(configGuideBean.getStoredConfiguration());
    final PwmApplication tempApplication =
        new PwmApplication.PwmEnvironment(
                tempConfiguration, pwmRequest.getPwmApplication().getApplicationPath())
            .setApplicationMode(PwmApplication.MODE.NEW)
            .setInternalRuntimeInstance(true)
            .setWebInfPath(pwmRequest.getPwmApplication().getWebInfPath())
            .createPwmApplication();
    final LDAPStatusChecker ldapStatusChecker = new LDAPStatusChecker();
    final List<HealthRecord> records = new ArrayList<>();
    final LdapProfile ldapProfile = tempConfiguration.getDefaultLdapProfile();
    switch (configGuideBean.getStep()) {
      case LDAP_SERVER:
        {
          try {
            checkLdapServer(configGuideBean);
            records.add(password.pwm.health.HealthRecord.forMessage(HealthMessage.LDAP_OK));
          } catch (Exception e) {
            records.add(
                new HealthRecord(
                    HealthStatus.WARN,
                    HealthTopic.LDAP,
                    "Can not connect to remote server: " + e.getMessage()));
          }
        }
        break;

      case LDAP_ADMIN:
        {
          records.addAll(
              ldapStatusChecker.checkBasicLdapConnectivity(
                  tempApplication, tempConfiguration, ldapProfile, false));
          if (records.isEmpty()) {
            records.add(password.pwm.health.HealthRecord.forMessage(HealthMessage.LDAP_OK));
          }
        }
        break;

      case LDAP_CONTEXT:
        {
          records.addAll(
              ldapStatusChecker.checkBasicLdapConnectivity(
                  tempApplication, tempConfiguration, ldapProfile, true));
          if (records.isEmpty()) {
            records.add(
                new HealthRecord(
                    HealthStatus.GOOD, HealthTopic.LDAP, "LDAP Contextless Login Root validated"));
          }
          try {
            final UserMatchViewerFunction userMatchViewerFunction = new UserMatchViewerFunction();
            final Collection<UserIdentity> results =
                userMatchViewerFunction.discoverMatchingUsers(
                    pwmRequest.getPwmApplication(),
                    2,
                    configGuideBean.getStoredConfiguration(),
                    PwmSetting.QUERY_MATCH_PWM_ADMIN,
                    null);

            if (results.isEmpty()) {
              records.add(
                  new HealthRecord(HealthStatus.WARN, HealthTopic.LDAP, "No matching admin users"));
            } else {
              records.add(
                  new HealthRecord(HealthStatus.GOOD, HealthTopic.LDAP, "Admin group validated"));
            }
          } catch (PwmException e) {
            records.add(
                new HealthRecord(
                    HealthStatus.WARN,
                    HealthTopic.LDAP,
                    "Error during admin group validation: "
                        + e.getErrorInformation().toDebugStr()));
          } catch (Exception e) {
            records.add(
                new HealthRecord(
                    HealthStatus.WARN,
                    HealthTopic.LDAP,
                    "Error during admin group validation: " + e.getMessage()));
          }
        }
        break;

      case LDAP_TESTUSER:
        {
          final String testUserValue = configGuideBean.getFormData().get(PARAM_LDAP_TEST_USER);
          if (testUserValue != null && !testUserValue.isEmpty()) {
            records.addAll(
                ldapStatusChecker.checkBasicLdapConnectivity(
                    tempApplication, tempConfiguration, ldapProfile, false));
            records.addAll(
                ldapStatusChecker.doLdapTestUserCheck(
                    tempConfiguration, ldapProfile, tempApplication));
          } else {
            records.add(
                new HealthRecord(HealthStatus.CAUTION, HealthTopic.LDAP, "No test user specified"));
          }
        }
        break;
    }

    HealthData jsonOutput = new HealthData();
    jsonOutput.records =
        password.pwm.ws.server.rest.bean.HealthRecord.fromHealthRecords(
            records, pwmRequest.getLocale(), tempConfiguration);
    jsonOutput.timestamp = new Date();
    jsonOutput.overall = HealthMonitor.getMostSevereHealthStatus(records).toString();
    final RestResultBean restResultBean = new RestResultBean();
    restResultBean.setData(jsonOutput);
    pwmRequest.outputJsonResult(restResultBean);
  }
Esempio n. 5
0
  public static void doProfileUpdate(
      final PwmRequest pwmRequest,
      final Map<FormConfiguration, String> formValues,
      final ChaiUser theUser)
      throws PwmUnrecoverableException, ChaiUnavailableException, PwmOperationalException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final UserInfoBean uiBean = pwmRequest.getPwmSession().getUserInfoBean();

    // verify form meets the form requirements (may be redundant, but shouldn't hurt)
    verifyFormAttributes(pwmRequest, formValues, false);

    // write values.
    LOGGER.info(
        "updating profile for " + pwmRequest.getPwmSession().getUserInfoBean().getUserIdentity());

    pwmRequest.getPwmSession().getSessionManager().getChaiProvider();

    Helper.writeFormValuesToLdap(
        pwmRequest.getPwmApplication(), pwmRequest.getPwmSession(), theUser, formValues, false);

    final UserIdentity userIdentity = uiBean.getUserIdentity();

    // re-populate the uiBean because we have changed some values.
    final UserStatusReader userStatusReader =
        new UserStatusReader(pwmRequest.getPwmApplication(), pwmRequest.getSessionLabel());
    userStatusReader.populateActorUserInfoBean(pwmRequest.getPwmSession(), userIdentity);

    // clear cached read attributes.
    pwmRequest.getPwmSession().getSessionManager().clearUserDataReader();

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

        final ActionExecutor actionExecutor =
            new ActionExecutor.ActionExecutorSettings(pwmApplication, userIdentity)
                .setExpandPwmMacros(true)
                .createActionExecutor();

        actionExecutor.executeActions(actions, pwmSession);
      }
    }

    sendProfileUpdateEmailNotice(pwmSession, pwmApplication);

    // mark the event log
    pwmApplication
        .getAuditManager()
        .submit(AuditEvent.UPDATE_PROFILE, pwmSession.getUserInfoBean(), pwmSession);

    // mark the uiBean so we user isn't recycled to the update profile page by the CommandServlet
    uiBean.setRequiresUpdateProfile(false);

    // clear out the updateProfileBean
    pwmSession.clearUpdateProfileBean();

    // success, so forward to success page
    pwmApplication.getStatisticsManager().incrementValue(Statistic.UPDATE_ATTRIBUTES);
  }