Ejemplo n.º 1
0
  public static void saveConfiguration(
      final PwmRequest pwmRequest, final StoredConfigurationImpl storedConfiguration)
      throws PwmUnrecoverableException {
    {
      final List<String> errorStrings = storedConfiguration.validateValues();
      if (errorStrings != null && !errorStrings.isEmpty()) {
        final String errorString = errorStrings.get(0);
        throw new PwmUnrecoverableException(
            new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, null, new String[] {errorString}));
      }
    }

    try {
      ContextManager contextManager =
          ContextManager.getContextManager(
              pwmRequest.getHttpServletRequest().getSession().getServletContext());
      contextManager
          .getConfigReader()
          .saveConfiguration(
              storedConfiguration,
              contextManager.getPwmApplication(),
              pwmRequest.getSessionLabel());
      contextManager.requestPwmApplicationRestart();
    } catch (Exception e) {
      final String errorString = "error saving file: " + e.getMessage();
      LOGGER.error(pwmRequest, errorString);
      throw new PwmUnrecoverableException(
          new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, null, new String[] {errorString}));
    }
  }
Ejemplo n.º 2
0
  private static void writeConfig(
      final ContextManager contextManager, final StoredConfigurationImpl storedConfiguration)
      throws PwmOperationalException, PwmUnrecoverableException {
    ConfigurationReader configReader = contextManager.getConfigReader();
    PwmApplication pwmApplication = contextManager.getPwmApplication();

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

      storedConfiguration.writeConfigProperty(
          StoredConfigurationImpl.ConfigProperty.PROPERTY_KEY_CONFIG_IS_EDITABLE, "true");
      configReader.saveConfiguration(storedConfiguration, pwmApplication, null);

      contextManager.requestPwmApplicationRestart();
    } catch (PwmException e) {
      throw new PwmOperationalException(e.getErrorInformation());
    } catch (Exception e) {
      final ErrorInformation errorInformation =
          new ErrorInformation(
              PwmError.ERROR_INVALID_CONFIG,
              "unable to save configuration: " + e.getLocalizedMessage());
      throw new PwmOperationalException(errorInformation);
    }
  }
Ejemplo n.º 3
0
 public static StoredConfigurationImpl readCurrentConfiguration(final PwmRequest pwmRequest)
     throws PwmUnrecoverableException {
   final ContextManager contextManager =
       ContextManager.getContextManager(pwmRequest.getHttpServletRequest().getSession());
   final ConfigurationReader runningConfigReader = contextManager.getConfigReader();
   final StoredConfigurationImpl runningConfig = runningConfigReader.getStoredConfiguration();
   return StoredConfigurationImpl.copy(runningConfig);
 }
Ejemplo n.º 4
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());
      }
    }
  }
Ejemplo n.º 5
0
  private boolean isEnabled(final ServletRequest servletRequest) {

    try {
      final PwmURL pwmURL = new PwmURL((HttpServletRequest) servletRequest);
      if (pwmURL.isResourceURL() || pwmURL.isWebServiceURL()) {
        return false;
      }
    } catch (Exception e) {
      LOGGER.error("unable to parse request url, defaulting to non-gzip: " + e.getMessage());
    }

    final PwmApplication pwmApplication;
    try {
      pwmApplication = ContextManager.getPwmApplication((HttpServletRequest) servletRequest);
      return Boolean.parseBoolean(
          pwmApplication.getConfig().readAppProperty(AppProperty.HTTP_ENABLE_GZIP));
    } catch (PwmUnrecoverableException e) {
      LOGGER.trace(
          "unable to read http-gzip app-property, defaulting to non-gzip: " + e.getMessage());
    }
    return false;
  }
Ejemplo n.º 6
0
  private void restGotoStep(final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
      throws PwmUnrecoverableException, IOException, ServletException {
    final String requestedStep = pwmRequest.readParameterAsString("step");
    STEP step = null;
    if (requestedStep != null && requestedStep.length() > 0) {
      try {
        step = STEP.valueOf(requestedStep);
      } catch (IllegalArgumentException e) {
        /* */
      }
    }

    final boolean ldapSchemaPermitted =
        "LDAP".equals(configGuideBean.getFormData().get(PARAM_CR_STORAGE_PREF))
            && configGuideBean.getSelectedTemplate() == PwmSettingTemplate.NOVL;

    if ("NEXT".equals(requestedStep)) {
      step = configGuideBean.getStep().next();
      if (step == STEP.LDAP_SCHEMA && !ldapSchemaPermitted) {
        step = step.next();
      }
    } else if ("PREVIOUS".equals(requestedStep)) {
      step = configGuideBean.getStep().previous();
      if (step == STEP.LDAP_SCHEMA && !ldapSchemaPermitted) {
        step = step.previous();
      }
    }

    if (step == null) {
      final String errorMsg = "unknown goto step request: " + requestedStep;
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, errorMsg);
      final RestResultBean restResultBean = RestResultBean.fromError(errorInformation, pwmRequest);
      LOGGER.error(pwmRequest, errorInformation.toDebugStr());
      pwmRequest.outputJsonResult(restResultBean);
      return;
    }

    if (step == STEP.FINISH) {
      final ContextManager contextManager = ContextManager.getContextManager(pwmRequest);
      try {
        writeConfig(contextManager, configGuideBean);
      } catch (PwmException e) {
        final RestResultBean restResultBean =
            RestResultBean.fromError(e.getErrorInformation(), pwmRequest);
        pwmRequest.outputJsonResult(restResultBean);
        return;
      } catch (Exception e) {
        final RestResultBean restResultBean =
            RestResultBean.fromError(
                new ErrorInformation(
                    PwmError.ERROR_UNKNOWN, "error during save: " + e.getMessage()),
                pwmRequest);
        pwmRequest.outputJsonResult(restResultBean);
        return;
      }
      final HashMap<String, String> resultData = new HashMap<>();
      resultData.put("serverRestart", "true");
      pwmRequest.outputJsonResult(new RestResultBean(resultData));
      pwmRequest.invalidateSession();
    } else {
      configGuideBean.setStep(step);
      pwmRequest.outputJsonResult(new RestResultBean());
      LOGGER.trace("setting current step to: " + step);
    }
  }
Ejemplo n.º 7
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;
  }