use of password.pwm.bean.LocalSessionStateBean in project pwm by pwm-project.
the class RequestInitializationFilter method handleRequestSecurityChecks.
@SuppressWarnings("checkstyle:MethodLength")
public static void handleRequestSecurityChecks(final PwmRequest pwmRequest) throws PwmUnrecoverableException {
final LocalSessionStateBean ssBean = pwmRequest.getPwmSession().getSessionStateBean();
// check the user's IP address
if (!pwmRequest.getConfig().readSettingAsBoolean(PwmSetting.MULTI_IP_SESSION_ALLOWED)) {
final String remoteAddress = readUserIPAddress(pwmRequest.getHttpServletRequest(), pwmRequest.getConfig());
if (!ssBean.getSrcAddress().equals(remoteAddress)) {
final String errorMsg = "current network address '" + remoteAddress + "' has changed from original network address '" + ssBean.getSrcAddress() + "'";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, errorMsg);
throw new PwmUnrecoverableException(errorInformation);
}
}
// check total time.
{
if (ssBean.getSessionCreationTime() != null) {
final Long maxSessionSeconds = pwmRequest.getConfig().readSettingAsLong(PwmSetting.SESSION_MAX_SECONDS);
final TimeDuration sessionAge = TimeDuration.fromCurrent(ssBean.getSessionCreationTime());
if (sessionAge.getTotalSeconds() > maxSessionSeconds) {
final String errorMsg = "session age (" + sessionAge.asCompactString() + ") is longer than maximum permitted age";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, errorMsg);
throw new PwmUnrecoverableException(errorInformation);
}
}
}
// check headers
{
final List<String> requiredHeaders = pwmRequest.getConfig().readSettingAsStringArray(PwmSetting.REQUIRED_HEADERS);
if (requiredHeaders != null && !requiredHeaders.isEmpty()) {
final Map<String, String> configuredValues = StringUtil.convertStringListToNameValuePair(requiredHeaders, "=");
for (final Map.Entry<String, String> entry : configuredValues.entrySet()) {
final String key = entry.getKey();
if (key != null && key.length() > 0) {
final String requiredValue = entry.getValue();
if (requiredValue != null && requiredValue.length() > 0) {
final String value = pwmRequest.readHeaderValueAsString(key);
if (value == null || value.length() < 1) {
final String errorMsg = "request is missing required value for header '" + key + "'";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, errorMsg);
throw new PwmUnrecoverableException(errorInformation);
} else {
if (!requiredValue.equals(value)) {
final String errorMsg = "request has incorrect required value for header '" + key + "'";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, errorMsg);
throw new PwmUnrecoverableException(errorInformation);
}
}
}
}
}
}
}
// check permitted source IP address
{
final List<String> requiredHeaders = pwmRequest.getConfig().readSettingAsStringArray(PwmSetting.IP_PERMITTED_RANGE);
if (requiredHeaders != null && !requiredHeaders.isEmpty()) {
boolean match = false;
final String requestAddress = pwmRequest.getHttpServletRequest().getRemoteAddr();
for (int i = 0; i < requiredHeaders.size() && !match; i++) {
final String ipMatchString = requiredHeaders.get(i);
try {
final IPMatcher ipMatcher = new IPMatcher(ipMatchString);
try {
if (ipMatcher.match(requestAddress)) {
match = true;
}
} catch (IPMatcher.IPMatcherException e) {
LOGGER.error("error while attempting to match permitted address range '" + ipMatchString + "', error: " + e);
}
} catch (IPMatcher.IPMatcherException e) {
LOGGER.error("error parsing permitted address range '" + ipMatchString + "', error: " + e);
}
}
if (!match) {
final String errorMsg = "request network address '" + requestAddress + "' does not match any configured permitted source address";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, errorMsg);
throw new PwmUnrecoverableException(errorInformation);
}
}
}
// csrf cross-site request forgery checks
final boolean performCsrfHeaderChecks = Boolean.parseBoolean(pwmRequest.getConfig().readAppProperty(AppProperty.SECURITY_HTTP_PERFORM_CSRF_HEADER_CHECKS));
if (performCsrfHeaderChecks && !pwmRequest.getMethod().isIdempotent() && !pwmRequest.getURL().isRestService()) {
final String originValue = pwmRequest.readHeaderValueAsString(HttpHeader.Origin);
final String referrerValue = pwmRequest.readHeaderValueAsString(HttpHeader.Referer);
final String siteUrl = pwmRequest.getPwmApplication().getConfig().readSettingAsString(PwmSetting.PWM_SITE_URL);
final String targetValue = pwmRequest.getHttpServletRequest().getRequestURL().toString();
if (StringUtil.isEmpty(targetValue)) {
final String msg = "malformed request instance, missing target uri value";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, msg);
LOGGER.debug(pwmRequest, errorInformation.toDebugStr() + " [" + makeHeaderDebugStr(pwmRequest) + "]");
throw new PwmUnrecoverableException(errorInformation);
}
final boolean originHeaderEvaluated;
if (!StringUtil.isEmpty(originValue)) {
if (!PwmURL.compareUriBase(originValue, targetValue)) {
final String msg = "cross-origin request not permitted: origin header does not match incoming target url" + " [" + makeHeaderDebugStr(pwmRequest) + "]";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, msg);
LOGGER.debug(pwmRequest, errorInformation.toDebugStr());
throw new PwmUnrecoverableException(errorInformation);
}
originHeaderEvaluated = true;
} else {
originHeaderEvaluated = false;
}
final boolean referrerHeaderEvaluated;
if (!StringUtil.isEmpty(referrerValue)) {
if (!PwmURL.compareUriBase(referrerValue, targetValue) && !PwmURL.compareUriBase(referrerValue, siteUrl)) {
final String msg = "cross-origin request not permitted: referrer header does not match incoming target url" + " [" + makeHeaderDebugStr(pwmRequest) + "]";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, msg);
LOGGER.debug(pwmRequest, errorInformation.toDebugStr());
throw new PwmUnrecoverableException(errorInformation);
}
referrerHeaderEvaluated = true;
} else {
referrerHeaderEvaluated = false;
}
if (!referrerHeaderEvaluated && !originHeaderEvaluated && !PwmURL.compareUriBase(originValue, siteUrl)) {
final String msg = "neither referer nor origin header request are present on non-idempotent request";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, msg);
LOGGER.debug(pwmRequest, errorInformation.toDebugStr() + " [" + makeHeaderDebugStr(pwmRequest) + "]");
throw new PwmUnrecoverableException(errorInformation);
}
}
// check trial
if (PwmConstants.TRIAL_MODE) {
final StatisticsManager statisticsManager = pwmRequest.getPwmApplication().getStatisticsManager();
final String currentAuthString = statisticsManager.getStatBundleForKey(StatisticsManager.KEY_CURRENT).getStatistic(Statistic.AUTHENTICATIONS);
if (new BigInteger(currentAuthString).compareTo(BigInteger.valueOf(PwmConstants.TRIAL_MAX_AUTHENTICATIONS)) > 0) {
throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TRIAL_VIOLATION, "maximum usage per server startup exceeded"));
}
final String totalAuthString = statisticsManager.getStatBundleForKey(StatisticsManager.KEY_CUMULATIVE).getStatistic(Statistic.AUTHENTICATIONS);
if (new BigInteger(totalAuthString).compareTo(BigInteger.valueOf(PwmConstants.TRIAL_MAX_TOTAL_AUTH)) > 0) {
throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TRIAL_VIOLATION, "maximum usage for this server has been exceeded"));
}
}
// check intruder
pwmRequest.getPwmApplication().getIntruderManager().convenience().checkAddressAndSession(pwmRequest.getPwmSession());
}
use of password.pwm.bean.LocalSessionStateBean in project pwm by pwm-project.
the class PwmRequest method hasForwardUrl.
public boolean hasForwardUrl() {
final LocalSessionStateBean ssBean = this.getPwmSession().getSessionStateBean();
final String redirectURL = ssBean.getForwardURL();
return !((redirectURL == null || redirectURL.isEmpty()) && this.getConfig().isDefaultValue(PwmSetting.URL_FORWARD));
}
use of password.pwm.bean.LocalSessionStateBean in project pwm by pwm-project.
the class PwmSession method unauthenticateUser.
/**
* Unauthenticate the pwmSession.
*/
public void unauthenticateUser(final PwmRequest pwmRequest) {
final LocalSessionStateBean ssBean = getSessionStateBean();
if (getLoginInfoBean().isAuthenticated()) {
// try to tear out a session normally.
getUserSessionDataCacheBean().clearPermissions();
final StringBuilder sb = new StringBuilder();
sb.append("unauthenticate session from ").append(ssBean.getSrcAddress());
if (getUserInfo().getUserIdentity() != null) {
sb.append(" (").append(getUserInfo().getUserIdentity()).append(")");
}
// mark the session state bean as no longer being authenticated
this.getLoginInfoBean().setAuthenticated(false);
// close out any outstanding connections
getSessionManager().closeConnections();
LOGGER.debug(this, sb.toString());
}
if (pwmRequest != null) {
try {
pwmRequest.getPwmApplication().getSessionStateService().clearLoginSession(pwmRequest);
} catch (PwmUnrecoverableException e) {
final String errorMsg = "unexpected error writing removing login cookie from response: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
LOGGER.error(pwmRequest, errorInformation);
}
pwmRequest.getHttpServletRequest().setAttribute(PwmConstants.SESSION_ATTR_BEANS, null);
}
userInfo = null;
loginInfoBean = null;
userSessionDataCacheBean = null;
}
use of password.pwm.bean.LocalSessionStateBean in project pwm by pwm-project.
the class PwmSession method getLabel.
public SessionLabel getLabel() {
final LocalSessionStateBean ssBean = this.getSessionStateBean();
String userID = null;
try {
userID = isAuthenticated() ? this.getUserInfo().getUsername() : null;
} catch (PwmUnrecoverableException e) {
LOGGER.error("unexpected error reading username: " + e.getMessage(), e);
}
final UserIdentity userIdentity = isAuthenticated() ? this.getUserInfo().getUserIdentity() : null;
return new SessionLabel(ssBean.getSessionID(), userIdentity, userID, ssBean.getSrcAddress(), ssBean.getSrcAddress());
}
use of password.pwm.bean.LocalSessionStateBean in project pwm by pwm-project.
the class GuestRegistrationServlet method handleCreateRequest.
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 Instant 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 Map.Entry<FormConfiguration, String> entry : formValues.entrySet()) {
final FormConfiguration formItem = entry.getKey();
final String value = entry.getValue();
LOGGER.debug(pwmSession, "Attribute from form: " + formItem.getName() + " = " + value);
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.getUserInfo().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 = provider.getEntryFactory().newChaiUser(guestUserDN);
final UserIdentity userIdentity = new UserIdentity(guestUserDN, pwmSession.getUserInfo().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());
{
// 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, pwmRequest.getSessionLabel());
}
}
// 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());
setLastError(pwmRequest, info);
LOGGER.warn(pwmSession, info);
this.forwardToJSP(pwmRequest, guestRegistrationBean);
} catch (PwmOperationalException e) {
LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr());
setLastError(pwmRequest, e.getErrorInformation());
this.forwardToJSP(pwmRequest, guestRegistrationBean);
}
}
Aggregations