示例#1
0
  public String getStatistic(final Statistic statistic) {
    switch (statistic.getType()) {
      case INCREMENTOR:
        return valueMap.containsKey(statistic) ? valueMap.get(statistic) : "0";

      case AVERAGE:
        final String avgStrValue = valueMap.get(statistic);

        AverageBean avgBean = new AverageBean();
        if (avgStrValue != null && avgStrValue.length() > 0) {
          try {
            avgBean = JsonUtil.deserialize(avgStrValue, AverageBean.class);
          } catch (Exception e) {
            LOGGER.trace(
                "unable to parse statistics value for stat "
                    + statistic.toString()
                    + ", value="
                    + avgStrValue);
          }
        }
        return avgBean.getAverage().toString();

      default:
        return "";
    }
  }
示例#2
0
 private UserCacheRecord read(StorageKey key) throws LocalDBException {
   final String jsonValue = localDB.get(DB, key.getKey());
   if (jsonValue != null && !jsonValue.isEmpty()) {
     try {
       return JsonUtil.deserialize(jsonValue, UserCacheRecord.class);
     } catch (JsonSyntaxException e) {
       LOGGER.error(
           "error reading record from cache store for key="
               + key.getKey()
               + ", error: "
               + e.getMessage());
       localDB.remove(DB, key.getKey());
     }
   }
   return null;
 }
示例#3
0
  public List<NAAFChainBean> readChains(final String username) throws PwmUnrecoverableException {
    final Map<String, String> urlParams = new LinkedHashMap<>();
    urlParams.put("username", username);
    urlParams.put("application", "NAM");
    urlParams.put("is_trusted", "true");
    urlParams.put("endpoint_session_id", this.getEndpoint_session_id());

    final String url = PwmURL.appendAndEncodeUrlParameters("/logon/chains", urlParams);

    final PwmHttpClientResponse response = makeApiRequest(HttpMethod.POST, url, null);

    final NAAFChainInformationResponseBean naafChainInformationResponseBean =
        JsonUtil.deserialize(response.getBody(), NAAFChainInformationResponseBean.class);

    return naafChainInformationResponseBean.getChains();
  }
示例#4
0
  private void initTempData() throws LocalDBException, PwmUnrecoverableException {
    final String cleanFlag =
        pwmApplication.readAppAttribute(PwmApplication.AppAttribute.REPORT_CLEAN_FLAG);
    if (!"true".equals(cleanFlag)) {
      LOGGER.error(PwmConstants.REPORTING_SESSION_LABEL, "did not shut down cleanly");
      reportStatus = new ReportStatusInfo(settings.getSettingsHash());
      reportStatus.setTotal(userCacheService.size());
    } else {
      try {
        final String jsonInfo =
            pwmApplication.readAppAttribute(PwmApplication.AppAttribute.REPORT_STATUS);
        if (jsonInfo != null && !jsonInfo.isEmpty()) {
          reportStatus = JsonUtil.deserialize(jsonInfo, ReportStatusInfo.class);
        }
      } catch (Exception e) {
        LOGGER.error(
            PwmConstants.REPORTING_SESSION_LABEL,
            "error loading cached report status info into memory: " + e.getMessage());
      }
    }

    reportStatus =
        reportStatus == null
            ? new ReportStatusInfo(settings.getSettingsHash())
            : reportStatus; // safety

    final String currentSettingCache = settings.getSettingsHash();
    if (reportStatus.getSettingsHash() != null
        && !reportStatus.getSettingsHash().equals(currentSettingCache)) {
      LOGGER.error(
          PwmConstants.REPORTING_SESSION_LABEL,
          "configuration has changed, will clear cached report data");
      clear();
    }

    reportStatus.setInProgress(false);

    pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.REPORT_CLEAN_FLAG, "false");
  }
示例#5
0
  public synchronized void updateAverageValue(final Statistic statistic, final long timeDuration) {
    if (Statistic.Type.AVERAGE != statistic.getType()) {
      LOGGER.error("attempt to update average value of non-average stat " + statistic);
      return;
    }

    final String avgStrValue = valueMap.get(statistic);

    AverageBean avgBean = new AverageBean();
    if (avgStrValue != null && avgStrValue.length() > 0) {
      try {
        avgBean = JsonUtil.deserialize(avgStrValue, AverageBean.class);
      } catch (Exception e) {
        LOGGER.trace(
            "unable to parse statistics value for stat "
                + statistic.toString()
                + ", value="
                + avgStrValue);
      }
    }

    avgBean.appendValue(timeDuration);
    valueMap.put(statistic, JsonUtil.serialize(avgBean));
  }
示例#6
0
  @Override
  void doCommand() throws Exception {
    final PwmApplication pwmApplication = cliEnvironment.getPwmApplication();

    final File inputFile =
        (File)
            cliEnvironment.getOptions().get(CliParameters.REQUIRED_EXISTING_INPUT_FILE.getName());
    final BufferedReader reader =
        new BufferedReader(
            new InputStreamReader(
                new FileInputStream(inputFile), PwmConstants.DEFAULT_CHARSET.toString()));
    out("importing stored responses from " + inputFile.getAbsolutePath() + "....");

    int counter = 0;
    String line;
    final long startTime = System.currentTimeMillis();
    while ((line = reader.readLine()) != null) {
      counter++;
      final RestChallengesServer.JsonChallengesData inputData;
      inputData = JsonUtil.deserialize(line, RestChallengesServer.JsonChallengesData.class);

      final UserIdentity userIdentity = UserIdentity.fromDelimitedKey(inputData.username);
      final ChaiUser user = pwmApplication.getProxiedChaiUser(userIdentity);
      if (user.isValid()) {
        out("writing responses to user '" + user.getEntryDN() + "'");
        try {
          final ChallengeProfile challengeProfile =
              pwmApplication
                  .getCrService()
                  .readUserChallengeProfile(
                      null,
                      userIdentity,
                      user,
                      PwmPasswordPolicy.defaultPolicy(),
                      PwmConstants.DEFAULT_LOCALE);
          final ChallengeSet challengeSet = challengeProfile.getChallengeSet();
          final String userGuid =
              LdapOperationsHelper.readLdapGuidValue(pwmApplication, null, userIdentity, false);
          final ResponseInfoBean responseInfoBean =
              inputData.toResponseInfoBean(
                  PwmConstants.DEFAULT_LOCALE, challengeSet.getIdentifier());
          pwmApplication.getCrService().writeResponses(user, userGuid, responseInfoBean);
        } catch (Exception e) {
          out(
              "error writing responses to user '"
                  + user.getEntryDN()
                  + "', error: "
                  + e.getMessage());
          return;
        }
      } else {
        out("user '" + user.getEntryDN() + "' is not a valid userDN");
        return;
      }
    }

    out(
        "output complete, "
            + counter
            + " responses imported in "
            + TimeDuration.fromCurrent(startTime).asCompactString());
  }
示例#7
0
  public void init(PwmApplication pwmApplication) throws PwmException {
    for (final Statistic.EpsType type : Statistic.EpsType.values()) {
      for (final Statistic.EpsDuration duration : Statistic.EpsDuration.values()) {
        epsMeterMap.put(
            type.toString() + duration.toString(), new EventRateMeter(duration.getTimeDuration()));
      }
    }

    status = STATUS.OPENING;
    this.localDB = pwmApplication.getLocalDB();
    this.pwmApplication = pwmApplication;

    if (localDB == null) {
      LOGGER.error("LocalDB is not available, will remain closed");
      status = STATUS.CLOSED;
      return;
    }

    {
      final String storedCummulativeBundleStr =
          localDB.get(LocalDB.DB.PWM_STATS, DB_KEY_CUMULATIVE);
      if (storedCummulativeBundleStr != null && storedCummulativeBundleStr.length() > 0) {
        statsCummulative = StatisticsBundle.input(storedCummulativeBundleStr);
      }
    }

    {
      for (final Statistic.EpsType loopEpsType : Statistic.EpsType.values()) {
        for (final Statistic.EpsType loopEpsDuration : Statistic.EpsType.values()) {
          final String key = "EPS-" + loopEpsType.toString() + loopEpsDuration.toString();
          final String storedValue = localDB.get(LocalDB.DB.PWM_STATS, key);
          if (storedValue != null && storedValue.length() > 0) {
            try {
              final EventRateMeter eventRateMeter =
                  JsonUtil.deserialize(storedValue, EventRateMeter.class);
              epsMeterMap.put(loopEpsType.toString() + loopEpsDuration.toString(), eventRateMeter);
            } catch (Exception e) {
              LOGGER.error(
                  "unexpected error reading last EPS rate for "
                      + loopEpsType
                      + " from LocalDB: "
                      + e.getMessage());
            }
          }
        }
      }
    }

    {
      final String storedInitialString =
          localDB.get(LocalDB.DB.PWM_STATS, DB_KEY_INITIAL_DAILY_KEY);
      if (storedInitialString != null && storedInitialString.length() > 0) {
        initialDailyKey = new DailyKey(storedInitialString);
      }
    }

    {
      currentDailyKey = new DailyKey(new Date());
      final String storedDailyStr = localDB.get(LocalDB.DB.PWM_STATS, currentDailyKey.toString());
      if (storedDailyStr != null && storedDailyStr.length() > 0) {
        statsDaily = StatisticsBundle.input(storedDailyStr);
      }
    }

    try {
      localDB.put(
          LocalDB.DB.PWM_STATS,
          DB_KEY_TEMP,
          PwmConstants.DEFAULT_DATETIME_FORMAT.format(new Date()));
    } catch (IllegalStateException e) {
      LOGGER.error("unable to write to localDB, will remain closed, error: " + e.getMessage());
      status = STATUS.CLOSED;
      return;
    }

    localDB.put(LocalDB.DB.PWM_STATS, DB_KEY_VERSION, DB_VALUE_VERSION);
    localDB.put(LocalDB.DB.PWM_STATS, DB_KEY_INITIAL_DAILY_KEY, initialDailyKey.toString());

    { // setup a timer to roll over at 0 Zula and one to write current stats every 10 seconds
      final String threadName = Helper.makeThreadName(pwmApplication, this.getClass()) + " timer";
      daemonTimer = new Timer(threadName, true);
      daemonTimer.schedule(new FlushTask(), 10 * 1000, DB_WRITE_FREQUENCY_MS);
      daemonTimer.schedule(new NightlyTask(), Helper.nextZuluZeroTime());
    }

    if (pwmApplication.getApplicationMode() == PwmApplication.MODE.RUNNING) {
      if (pwmApplication.getConfig().readSettingAsBoolean(PwmSetting.PUBLISH_STATS_ENABLE)) {
        long lastPublishTimestamp = pwmApplication.getInstallTime().getTime();
        {
          final String lastPublishDateStr =
              localDB.get(LocalDB.DB.PWM_STATS, KEY_CLOUD_PUBLISH_TIMESTAMP);
          if (lastPublishDateStr != null && lastPublishDateStr.length() > 0) {
            try {
              lastPublishTimestamp = Long.parseLong(lastPublishDateStr);
            } catch (Exception e) {
              LOGGER.error(
                  "unexpected error reading last publish timestamp from PwmDB: " + e.getMessage());
            }
          }
        }
        final Date nextPublishTime =
            new Date(
                lastPublishTimestamp
                    + PwmConstants.STATISTICS_PUBLISH_FREQUENCY_MS
                    + (long) PwmRandom.getInstance().nextInt(3600 * 1000));
        daemonTimer.schedule(
            new PublishTask(), nextPublishTime, PwmConstants.STATISTICS_PUBLISH_FREQUENCY_MS);
      }
    }

    status = STATUS.OPEN;
  }
示例#8
0
  public static PasswordCheckInfo checkEnteredPassword(
      final PwmApplication pwmApplication,
      final Locale locale,
      final ChaiUser user,
      final UserInfoBean userInfoBean,
      final LoginInfoBean loginInfoBean,
      final PasswordData password,
      final PasswordData confirmPassword)
      throws PwmUnrecoverableException, ChaiUnavailableException {
    if (userInfoBean == null) {
      throw new NullPointerException("userInfoBean cannot be null");
    }

    boolean pass = false;
    String userMessage = "";
    int errorCode = 0;

    final boolean passwordIsCaseSensitive =
        userInfoBean.getPasswordPolicy() == null
            || userInfoBean
                .getPasswordPolicy()
                .getRuleHelper()
                .readBooleanValue(PwmPasswordRule.CaseSensitive);
    final CachePolicy cachePolicy;
    {
      final long cacheLifetimeMS =
          Long.parseLong(
              pwmApplication
                  .getConfig()
                  .readAppProperty(AppProperty.CACHE_PWRULECHECK_LIFETIME_MS));
      cachePolicy = CachePolicy.makePolicyWithExpirationMS(cacheLifetimeMS);
    }

    if (password == null) {
      userMessage =
          new ErrorInformation(PwmError.PASSWORD_MISSING)
              .toUserStr(locale, pwmApplication.getConfig());
    } else {
      final CacheService cacheService = pwmApplication.getCacheService();
      final CacheKey cacheKey =
          user != null && userInfoBean.getUserIdentity() != null
              ? CacheKey.makeCacheKey(
                  PasswordUtility.class,
                  userInfoBean.getUserIdentity(),
                  user.getEntryDN() + ":" + password.hash())
              : null;
      if (pwmApplication.getConfig().isDevDebugMode()) {
        LOGGER.trace("generated cacheKey for password check request: " + cacheKey);
      }
      try {
        if (cacheService != null && cacheKey != null) {
          final String cachedValue = cacheService.get(cacheKey);
          if (cachedValue != null) {
            if (NEGATIVE_CACHE_HIT.equals(cachedValue)) {
              pass = true;
            } else {
              LOGGER.trace("cache hit!");
              final ErrorInformation errorInformation =
                  JsonUtil.deserialize(cachedValue, ErrorInformation.class);
              throw new PwmDataValidationException(errorInformation);
            }
          }
        }
        if (!pass) {
          final PwmPasswordRuleValidator pwmPasswordRuleValidator =
              new PwmPasswordRuleValidator(
                  pwmApplication, userInfoBean.getPasswordPolicy(), locale);
          final PasswordData oldPassword =
              loginInfoBean == null ? null : loginInfoBean.getUserCurrentPassword();
          pwmPasswordRuleValidator.testPassword(password, oldPassword, userInfoBean, user);
          pass = true;
          if (cacheService != null && cacheKey != null) {
            cacheService.put(cacheKey, cachePolicy, NEGATIVE_CACHE_HIT);
          }
        }
      } catch (PwmDataValidationException e) {
        errorCode = e.getError().getErrorCode();
        userMessage = e.getErrorInformation().toUserStr(locale, pwmApplication.getConfig());
        pass = false;
        if (cacheService != null && cacheKey != null) {
          final String jsonPayload = JsonUtil.serialize(e.getErrorInformation());
          cacheService.put(cacheKey, cachePolicy, jsonPayload);
        }
      }
    }

    final PasswordCheckInfo.MATCH_STATUS matchStatus =
        figureMatchStatus(passwordIsCaseSensitive, password, confirmPassword);
    if (pass) {
      switch (matchStatus) {
        case EMPTY:
          userMessage =
              new ErrorInformation(PwmError.PASSWORD_MISSING_CONFIRM)
                  .toUserStr(locale, pwmApplication.getConfig());
          break;
        case MATCH:
          userMessage =
              new ErrorInformation(PwmError.PASSWORD_MEETS_RULES)
                  .toUserStr(locale, pwmApplication.getConfig());
          break;
        case NO_MATCH:
          userMessage =
              new ErrorInformation(PwmError.PASSWORD_DOESNOTMATCH)
                  .toUserStr(locale, pwmApplication.getConfig());
          break;
        default:
          userMessage = "";
      }
    }

    final int strength = judgePasswordStrength(password == null ? null : password.getStringValue());
    return new PasswordCheckInfo(userMessage, pass, strength, matchStatus, errorCode);
  }
  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;
  }