Exemplo n.º 1
0
  void restUploadWordlist(final PwmRequest pwmRequest)
      throws IOException, ServletException, PwmUnrecoverableException {

    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final HttpServletRequest req = pwmRequest.getHttpServletRequest();

    if (!ServletFileUpload.isMultipartContent(req)) {
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.ERROR_UNKNOWN, "no file found in upload");
      pwmRequest.outputJsonResult(RestResultBean.fromError(errorInformation, pwmRequest));
      LOGGER.error(pwmRequest, "error during import: " + errorInformation.toDebugStr());
      return;
    }

    final InputStream inputStream =
        ServletHelper.readFileUpload(pwmRequest.getHttpServletRequest(), "uploadFile");
    try {
      pwmApplication.getWordlistManager().populate(inputStream);
    } catch (PwmUnrecoverableException e) {
      final ErrorInformation errorInfo =
          new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage());
      final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest);
      LOGGER.debug(pwmRequest, errorInfo.toDebugStr());
      pwmRequest.outputJsonResult(restResultBean);
      return;
    }

    pwmRequest.outputJsonResult(
        RestResultBean.forSuccessMessage(pwmRequest, Message.Success_Unknown));
  }
Exemplo n.º 2
0
  public void clearResponses(final ChaiUser theUser, final String userGUID)
      throws PwmUnrecoverableException {
    if (userGUID == null || userGUID.length() < 1) {
      throw new PwmUnrecoverableException(
          new ErrorInformation(
              PwmError.ERROR_MISSING_GUID,
              "cannot clear responses to remote database, user "
                  + theUser.getEntryDN()
                  + " does not have a guid"));
    }

    try {
      final DatabaseAccessorImpl databaseAccessor = pwmApplication.getDatabaseAccessor();
      databaseAccessor.remove(DatabaseTable.PWM_RESPONSES, userGUID);
      LOGGER.info("cleared responses for user " + theUser.getEntryDN() + " in remote database");
    } catch (DatabaseException e) {
      final ErrorInformation errorInfo =
          new ErrorInformation(
              PwmError.ERROR_CLEARING_RESPONSES,
              "unexpected error clearing responses for "
                  + theUser.getEntryDN()
                  + " in remote database, error: "
                  + e.getMessage());
      final PwmUnrecoverableException pwmOE = new PwmUnrecoverableException(errorInfo);
      pwmOE.initCause(e);
      throw pwmOE;
    }
  }
Exemplo n.º 3
0
  @Override
  public void clearOtpUserConfiguration(
      final PwmSession pwmSession, final UserIdentity theUser, final String userGUID)
      throws PwmUnrecoverableException {
    if (userGUID == null || userGUID.length() < 1) {
      throw new PwmUnrecoverableException(
          new ErrorInformation(
              PwmError.ERROR_MISSING_GUID,
              "cannot save OTP secret to remote database, user "
                  + theUser
                  + " does not have a guid"));
    }

    LOGGER.trace(
        "attempting to clear OTP secret for "
            + theUser
            + " in remote database (key="
            + userGUID
            + ")");

    try {
      final DatabaseAccessorImpl databaseAccessor = pwmApplication.getDatabaseAccessor();
      databaseAccessor.remove(DatabaseTable.OTP, userGUID);
      LOGGER.info(
          "cleared OTP secret for " + theUser + " in remote database (key=" + userGUID + ")");
    } catch (DatabaseException ex) {
      final ErrorInformation errorInfo =
          new ErrorInformation(
              PwmError.ERROR_WRITING_OTP_SECRET,
              "unexpected error saving otp to db: " + ex.getMessage());
      final PwmUnrecoverableException pwmOE = new PwmUnrecoverableException(errorInfo);
      pwmOE.initCause(ex);
      throw pwmOE;
    }
  }
Exemplo n.º 4
0
  private static void invokePostChangePasswordActions(
      final PwmSession pwmSession, final String newPassword) throws PwmUnrecoverableException {
    final List<PostChangePasswordAction> postChangePasswordActions =
        pwmSession.getUserSessionDataCacheBean().removePostChangePasswordActions();
    if (postChangePasswordActions == null || postChangePasswordActions.isEmpty()) {
      LOGGER.trace(pwmSession, "no post change password actions pending from previous operations");
      return;
    }

    for (final PostChangePasswordAction postChangePasswordAction : postChangePasswordActions) {
      try {
        postChangePasswordAction.doAction(pwmSession, newPassword);
      } catch (PwmUnrecoverableException e) {
        LOGGER.error(
            pwmSession,
            "error during post change password action '"
                + postChangePasswordAction.getLabel()
                + "' "
                + e.getMessage());
        throw e;
      } catch (Exception e) {
        LOGGER.error(
            pwmSession,
            "unexpected error during post change password action '"
                + postChangePasswordAction.getLabel()
                + "' "
                + e.getMessage(),
            e);
        final ErrorInformation errorInfo =
            new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage());
        throw new PwmUnrecoverableException(errorInfo);
      }
    }
  }
Exemplo n.º 5
0
  private PwmApplication(final PwmEnvironment pwmEnvironment) throws PwmUnrecoverableException {
    verifyIfApplicationPathIsSetProperly(pwmEnvironment);

    this.configuration = pwmEnvironment.config;
    this.applicationMode = pwmEnvironment.applicationMode;
    this.applicationPath = pwmEnvironment.applicationPath;
    this.configurationFile = pwmEnvironment.configurationFile;
    this.webInfPath = pwmEnvironment.webInfPath;

    try {
      initialize(pwmEnvironment.initLogging);
    } catch (PwmUnrecoverableException e) {
      LOGGER.fatal(e.getMessage());
      throw e;
    }
  }
Exemplo n.º 6
0
  @GET
  @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
  @Path("/client")
  public Response doGetAppClientData(
      @QueryParam("pageUrl") String pageUrl,
      @PathParam(value = "eTagUri") final String eTagUri,
      @Context HttpServletRequest request,
      @Context HttpServletResponse response)
      throws PwmUnrecoverableException, IOException, ChaiUnavailableException {
    final int maxCacheAgeSeconds = 60 * 5;
    final RestRequestBean restRequestBean;
    try {
      restRequestBean =
          RestServerHelper.initializeRestRequest(
              request, response, ServicePermissions.PUBLIC, null);
    } catch (PwmUnrecoverableException e) {
      return RestResultBean.fromError(e.getErrorInformation()).asJsonResponse();
    }

    final String eTagValue =
        makeClientEtag(
            restRequestBean.getPwmApplication(), restRequestBean.getPwmSession(), request);

    // check the incoming header;
    final String ifNoneMatchValue = request.getHeader("If-None-Match");

    if (ifNoneMatchValue != null
        && ifNoneMatchValue.equals(eTagValue)
        && eTagValue.equals(eTagUri)) {
      return Response.notModified().build();
    }

    response.setHeader("ETag", eTagValue);
    response.setDateHeader("Expires", System.currentTimeMillis() + (maxCacheAgeSeconds * 1000));
    response.setHeader("Cache-Control", "public, max-age=" + maxCacheAgeSeconds);

    final AppData appData =
        makeAppData(
            restRequestBean.getPwmApplication(),
            restRequestBean.getPwmSession(),
            request,
            response,
            pageUrl);
    final RestResultBean restResultBean = new RestResultBean();
    restResultBean.setData(appData);
    return restResultBean.asJsonResponse();
  }
Exemplo n.º 7
0
  @GET
  @Path("/intruder")
  @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
  public Response doGetAppIntruderData(@QueryParam("maximum") int maximum)
      throws ChaiUnavailableException, PwmUnrecoverableException {
    maximum = maximum > 0 ? maximum : 10 * 1000;

    final RestRequestBean restRequestBean;
    try {
      final ServicePermissions servicePermissions = new ServicePermissions();
      servicePermissions.setAdminOnly(true);
      servicePermissions.setAuthRequired(true);
      servicePermissions.setBlockExternal(true);
      restRequestBean =
          RestServerHelper.initializeRestRequest(request, response, servicePermissions, null);
    } catch (PwmUnrecoverableException e) {
      return RestResultBean.fromError(e.getErrorInformation()).asJsonResponse();
    }

    if (!restRequestBean
        .getPwmSession()
        .getSessionManager()
        .checkPermission(restRequestBean.getPwmApplication(), Permission.PWMADMIN)) {
      final ErrorInformation errorInfo = PwmError.ERROR_UNAUTHORIZED.toInfo();
      return RestResultBean.fromError(errorInfo, restRequestBean).asJsonResponse();
    }

    final TreeMap<String, Object> returnData = new TreeMap<>();
    try {
      for (final RecordType recordType : RecordType.values()) {
        returnData.put(
            recordType.toString(),
            restRequestBean
                .getPwmApplication()
                .getIntruderManager()
                .getRecords(recordType, maximum));
      }
    } catch (PwmOperationalException e) {
      final ErrorInformation errorInfo =
          new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage());
      return RestResultBean.fromError(errorInfo, restRequestBean).asJsonResponse();
    }

    final RestResultBean restResultBean = new RestResultBean();
    restResultBean.setData(returnData);
    return restResultBean.asJsonResponse();
  }
Exemplo n.º 8
0
  @GET
  @Path("/audit")
  @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
  public Response doGetAppAuditData(@QueryParam("maximum") int maximum)
      throws ChaiUnavailableException, PwmUnrecoverableException {
    maximum = maximum > 0 ? maximum : 10 * 1000;

    final RestRequestBean restRequestBean;
    try {
      final ServicePermissions servicePermissions = new ServicePermissions();
      servicePermissions.setAdminOnly(true);
      servicePermissions.setAuthRequired(true);
      servicePermissions.setBlockExternal(true);
      restRequestBean =
          RestServerHelper.initializeRestRequest(request, response, servicePermissions, null);
    } catch (PwmUnrecoverableException e) {
      return RestResultBean.fromError(e.getErrorInformation()).asJsonResponse();
    }

    final ArrayList<UserAuditRecord> userRecords = new ArrayList<>();
    final ArrayList<HelpdeskAuditRecord> helpdeskRecords = new ArrayList<>();
    final ArrayList<SystemAuditRecord> systemRecords = new ArrayList<>();
    final Iterator<AuditRecord> iterator =
        restRequestBean.getPwmApplication().getAuditManager().readVault();
    int counter = 0;
    while (iterator.hasNext() && counter <= maximum) {
      final AuditRecord loopRecord = iterator.next();
      counter++;
      if (loopRecord instanceof SystemAuditRecord) {
        systemRecords.add((SystemAuditRecord) loopRecord);
      } else if (loopRecord instanceof HelpdeskAuditRecord) {
        helpdeskRecords.add((HelpdeskAuditRecord) loopRecord);
      } else if (loopRecord instanceof UserAuditRecord) {
        userRecords.add((UserAuditRecord) loopRecord);
      }
    }
    final HashMap<String, List> outputMap = new HashMap<>();
    outputMap.put("user", userRecords);
    outputMap.put("helpdesk", helpdeskRecords);
    outputMap.put("system", systemRecords);

    final RestResultBean restResultBean = new RestResultBean();
    restResultBean.setData(outputMap);
    LOGGER.debug(restRequestBean.getPwmSession(), "output " + counter + " audit records.");
    return restResultBean.asJsonResponse();
  }
Exemplo n.º 9
0
  public void sendSmsUsingQueue(final SmsItemBean smsItem, final MacroMachine macroMachine) {
    final SmsQueueManager smsQueue = getSmsQueue();
    if (smsQueue == null) {
      LOGGER.error("SMS queue is unavailable, unable to send SMS: " + smsItem.toString());
      return;
    }

    final SmsItemBean rewrittenSmsItem =
        new SmsItemBean(
            macroMachine.expandMacros(smsItem.getTo()),
            macroMachine.expandMacros(smsItem.getMessage()));

    try {
      smsQueue.addSmsToQueue(rewrittenSmsItem);
    } catch (PwmUnrecoverableException e) {
      LOGGER.warn("unable to add sms to queue: " + e.getMessage());
    }
  }
Exemplo n.º 10
0
 public ChaiUser getProxiedChaiUser(final UserIdentity userIdentity)
     throws PwmUnrecoverableException {
   try {
     final ChaiProvider proxiedProvider = getProxyChaiProvider(userIdentity.getLdapProfileID());
     return ChaiFactory.createChaiUser(userIdentity.getUserDN(), proxiedProvider);
   } catch (ChaiUnavailableException e) {
     throw PwmUnrecoverableException.fromChaiException(e);
   }
 }
Exemplo n.º 11
0
  @Override
  public void writeOtpUserConfiguration(
      final PwmSession pwmSession,
      final UserIdentity theUser,
      final String userGUID,
      final OTPUserRecord otpConfig)
      throws PwmUnrecoverableException {
    if (userGUID == null || userGUID.length() < 1) {
      throw new PwmUnrecoverableException(
          new ErrorInformation(
              PwmError.ERROR_MISSING_GUID,
              "cannot save OTP secret to remote database, user "
                  + theUser
                  + " does not have a guid"));
    }

    LOGGER.trace(
        "attempting to save OTP secret for "
            + theUser
            + " in remote database (key="
            + userGUID
            + ")");

    try {
      String value = composeOtpAttribute(otpConfig);
      if (getPwmApplication().getConfig().readSettingAsBoolean(PwmSetting.OTP_SECRET_ENCRYPT)) {
        LOGGER.debug("Encrypting OTP secret for storage");
        value = encryptAttributeValue(value);
      }
      final DatabaseAccessorImpl databaseAccessor = pwmApplication.getDatabaseAccessor();
      databaseAccessor.put(DatabaseTable.OTP, userGUID, value);
      LOGGER.info("saved OTP secret for " + theUser + " in remote database (key=" + userGUID + ")");
    } catch (PwmOperationalException ex) {
      final ErrorInformation errorInfo =
          new ErrorInformation(
              PwmError.ERROR_WRITING_OTP_SECRET,
              "unexpected error saving otp to db: " + ex.getMessage());
      final PwmUnrecoverableException pwmOE = new PwmUnrecoverableException(errorInfo);
      pwmOE.initCause(ex);
      throw pwmOE;
    }
  }
Exemplo n.º 12
0
  @GET
  @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
  @Path("/strings/{bundle}")
  public Response doGetStringData(@PathParam(value = "bundle") final String bundleName)
      throws PwmUnrecoverableException, IOException, ChaiUnavailableException {
    final int maxCacheAgeSeconds = 60 * 5;
    final RestRequestBean restRequestBean;
    try {
      restRequestBean =
          RestServerHelper.initializeRestRequest(
              request, response, ServicePermissions.PUBLIC, null);
    } catch (PwmUnrecoverableException e) {
      return RestResultBean.fromError(e.getErrorInformation()).asJsonResponse();
    }

    final String eTagValue =
        makeClientEtag(
            restRequestBean.getPwmApplication(), restRequestBean.getPwmSession(), request);
    response.setHeader("ETag", eTagValue);
    response.setDateHeader("Expires", System.currentTimeMillis() + (maxCacheAgeSeconds * 1000));
    response.setHeader("Cache-Control", "public, max-age=" + maxCacheAgeSeconds);

    try {
      final LinkedHashMap<String, String> displayData =
          new LinkedHashMap<>(
              makeDisplayData(
                  restRequestBean.getPwmApplication(),
                  restRequestBean.getPwmSession(),
                  bundleName));
      final RestResultBean restResultBean = new RestResultBean();
      restResultBean.setData(displayData);
      return restResultBean.asJsonResponse();
    } catch (Exception e) {
      final String errorMSg =
          "error during rest /strings call for bundle " + bundleName + ", error: " + e.getMessage();
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMSg);
      return RestResultBean.fromError(errorInformation).asJsonResponse();
    }
  }
Exemplo n.º 13
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;
  }
Exemplo n.º 14
0
  protected static PwmPasswordPolicy determineConfiguredPolicyProfileForUser(
      final PwmApplication pwmApplication,
      final SessionLabel pwmSession,
      final UserIdentity userIdentity,
      final Locale locale)
      throws PwmUnrecoverableException {
    final List<String> profiles = pwmApplication.getConfig().getPasswordProfileIDs();
    if (profiles.isEmpty()) {
      throw new PwmUnrecoverableException(
          new ErrorInformation(
              PwmError.ERROR_NO_PROFILE_ASSIGNED, "no password profiles are configured"));
    }

    for (final String profile : profiles) {
      final PwmPasswordPolicy loopPolicy =
          pwmApplication.getConfig().getPasswordPolicy(profile, locale);
      final List<UserPermission> userPermissions = loopPolicy.getUserPermissions();
      LOGGER.debug(pwmSession, "testing password policy profile '" + profile + "'");
      try {
        boolean match =
            LdapPermissionTester.testUserPermissions(
                pwmApplication, pwmSession, userIdentity, userPermissions);
        if (match) {
          return loopPolicy;
        }
      } catch (PwmUnrecoverableException e) {
        LOGGER.error(
            pwmSession,
            "unexpected error while testing password policy profile '"
                + profile
                + "', error: "
                + e.getMessage());
      }
    }

    throw new PwmUnrecoverableException(
        new ErrorInformation(
            PwmError.ERROR_NO_PROFILE_ASSIGNED, "no challenge profile is configured"));
  }
Exemplo n.º 15
0
  @GET
  @Path("/session")
  @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
  public Response doGetAppSessionData(@QueryParam("maximum") int maximum)
      throws ChaiUnavailableException, PwmUnrecoverableException {
    maximum = maximum > 0 ? maximum : 10 * 1000;

    final RestRequestBean restRequestBean;
    try {
      final ServicePermissions servicePermissions = new ServicePermissions();
      servicePermissions.setAdminOnly(true);
      servicePermissions.setAuthRequired(true);
      servicePermissions.setBlockExternal(true);
      restRequestBean =
          RestServerHelper.initializeRestRequest(request, response, servicePermissions, null);
    } catch (PwmUnrecoverableException e) {
      return RestResultBean.fromError(e.getErrorInformation()).asJsonResponse();
    }

    if (!restRequestBean
        .getPwmSession()
        .getSessionManager()
        .checkPermission(restRequestBean.getPwmApplication(), Permission.PWMADMIN)) {
      final ErrorInformation errorInfo = PwmError.ERROR_UNAUTHORIZED.toInfo();
      return RestResultBean.fromError(errorInfo, restRequestBean).asJsonResponse();
    }

    final ArrayList<SessionStateInfoBean> gridData = new ArrayList<>();
    int counter = 0;
    final Iterator<SessionStateInfoBean> infos =
        restRequestBean.getPwmApplication().getSessionTrackService().getSessionInfoIterator();
    while (counter < maximum && infos.hasNext()) {
      gridData.add(infos.next());
      counter++;
    }
    final RestResultBean restResultBean = new RestResultBean();
    restResultBean.setData(gridData);
    return restResultBean.asJsonResponse();
  }
Exemplo n.º 16
0
  @Override
  public void writeResponses(ChaiUser theUser, String userGUID, ResponseInfoBean responseInfoBean)
      throws PwmUnrecoverableException {
    if (userGUID == null || userGUID.length() < 1) {
      throw new PwmUnrecoverableException(
          new ErrorInformation(
              PwmError.ERROR_MISSING_GUID,
              "cannot save responses to remote database, user "
                  + theUser.getEntryDN()
                  + " does not have a guid"));
    }

    LOGGER.trace(
        "attempting to save responses for "
            + theUser.getEntryDN()
            + " in remote database (key="
            + userGUID
            + ")");

    try {
      final ChaiResponseSet responseSet =
          ChaiCrFactory.newChaiResponseSet(
              responseInfoBean.getCrMap(),
              responseInfoBean.getHelpdeskCrMap(),
              responseInfoBean.getLocale(),
              responseInfoBean.getMinRandoms(),
              theUser.getChaiProvider().getChaiConfiguration(),
              responseInfoBean.getCsIdentifier());

      final DatabaseAccessorImpl databaseAccessor = pwmApplication.getDatabaseAccessor();
      databaseAccessor.put(DatabaseTable.PWM_RESPONSES, userGUID, responseSet.stringValue());
      LOGGER.info(
          "saved responses for "
              + theUser.getEntryDN()
              + " in remote database (key="
              + userGUID
              + ")");
    } catch (ChaiException e) {
      final ErrorInformation errorInfo =
          new ErrorInformation(
              PwmError.ERROR_WRITING_RESPONSES,
              "unexpected error saving responses for "
                  + theUser.getEntryDN()
                  + " in remote database: "
                  + e.getMessage());
      final PwmUnrecoverableException pwmOE = new PwmUnrecoverableException(errorInfo);
      LOGGER.error(errorInfo.toDebugStr());
      pwmOE.initCause(e);
      throw pwmOE;
    } catch (DatabaseException e) {
      final ErrorInformation errorInfo =
          new ErrorInformation(
              PwmError.ERROR_WRITING_RESPONSES,
              "unexpected error saving responses for "
                  + theUser.getEntryDN()
                  + " in remote database: "
                  + e.getMessage());
      final PwmUnrecoverableException pwmOE = new PwmUnrecoverableException(errorInfo);
      LOGGER.error(errorInfo.toDebugStr());
      pwmOE.initCause(e);
      throw pwmOE;
    }
  }