use of password.pwm.ldap.auth.SessionAuthenticator in project pwm by pwm-project.
the class ForgottenPasswordServlet method handleUserVerificationBadAttempt.
private void handleUserVerificationBadAttempt(final PwmRequest pwmRequest, final ForgottenPasswordBean forgottenPasswordBean, final ErrorInformation errorInformation) throws PwmUnrecoverableException {
LOGGER.debug(pwmRequest, errorInformation);
setLastError(pwmRequest, errorInformation);
final UserIdentity userIdentity = forgottenPasswordBean == null ? null : forgottenPasswordBean.getUserIdentity();
if (userIdentity != null) {
final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmRequest.getPwmApplication(), pwmRequest.getPwmSession(), PwmAuthenticationSource.FORGOTTEN_PASSWORD);
sessionAuthenticator.simulateBadPassword(userIdentity);
pwmRequest.getPwmApplication().getIntruderManager().convenience().markUserIdentity(userIdentity, pwmRequest.getPwmSession());
}
pwmRequest.getPwmApplication().getIntruderManager().convenience().markAddressAndSession(pwmRequest.getPwmSession());
StatisticsManager.incrementStat(pwmRequest, Statistic.RECOVERY_FAILURES);
}
use of password.pwm.ldap.auth.SessionAuthenticator in project pwm by pwm-project.
the class LoginServlet method handleLoginRequest.
private void handleLoginRequest(final PwmRequest pwmRequest, final Map<String, String> valueMap, final boolean passwordOnly) throws PwmOperationalException, ChaiUnavailableException, PwmUnrecoverableException, IOException, ServletException {
final String username = valueMap.get(PwmConstants.PARAM_USERNAME);
final String passwordStr = valueMap.get(PwmConstants.PARAM_PASSWORD);
final PasswordData password = passwordStr != null && passwordStr.length() > 0 ? new PasswordData(passwordStr) : null;
final String context = valueMap.get(PwmConstants.PARAM_CONTEXT);
final String ldapProfile = valueMap.get(PwmConstants.PARAM_LDAP_PROFILE);
final String recaptchaResponse = valueMap.get("g-recaptcha-response");
if (!passwordOnly && (username == null || username.isEmpty())) {
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_MISSING_PARAMETER, "missing username parameter"));
}
if (password == null) {
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_MISSING_PARAMETER, "missing password parameter"));
}
if (CaptchaUtility.captchaEnabledForRequest(pwmRequest)) {
if (!CaptchaUtility.verifyReCaptcha(pwmRequest, recaptchaResponse)) {
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_BAD_CAPTCHA_RESPONSE, "captcha incorrect"));
}
}
final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmRequest.getPwmApplication(), pwmRequest.getPwmSession(), PwmAuthenticationSource.LOGIN_FORM);
if (passwordOnly) {
final UserIdentity userIdentity = pwmRequest.getPwmSession().getUserInfo().getUserIdentity();
sessionAuthenticator.authenticateUser(userIdentity, password);
} else {
sessionAuthenticator.searchAndAuthenticateUser(username, password, context, ldapProfile);
}
// if here then login was successful
// recycle the session to prevent session fixation attack.
pwmRequest.getPwmSession().getSessionStateBean().setSessionIdRecycleNeeded(true);
}
use of password.pwm.ldap.auth.SessionAuthenticator in project pwm by pwm-project.
the class NewUserUtils method createUser.
@SuppressWarnings("checkstyle:MethodLength")
static void createUser(final NewUserForm newUserForm, final PwmRequest pwmRequest, final String newUserDN) throws PwmUnrecoverableException, ChaiUnavailableException, PwmOperationalException {
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final PwmSession pwmSession = pwmRequest.getPwmSession();
final long startTime = System.currentTimeMillis();
// re-perform verification before proceeding
{
final PasswordUtility.PasswordCheckInfo passwordCheckInfo = NewUserServlet.verifyForm(pwmRequest, newUserForm, false);
passwordCheckInfoToException(passwordCheckInfo);
}
NewUserUtils.LOGGER.debug(pwmSession, "beginning createUser process for " + newUserDN);
final NewUserProfile newUserProfile = NewUserServlet.getNewUserProfile(pwmRequest);
final boolean promptForPassword = newUserProfile.readSettingAsBoolean(PwmSetting.NEWUSER_PROMPT_FOR_PASSWORD);
final PasswordData userPassword;
if (promptForPassword) {
userPassword = newUserForm.getNewUserPassword();
} else {
final PwmPasswordPolicy pwmPasswordPolicy = newUserProfile.getNewUserPasswordPolicy(pwmRequest.getPwmApplication(), pwmRequest.getLocale());
userPassword = RandomPasswordGenerator.createRandomPassword(pwmRequest.getSessionLabel(), pwmPasswordPolicy, pwmRequest.getPwmApplication());
}
// set up the user creation attributes
final Map<String, String> createAttributes = NewUserFormUtils.getLdapDataFromNewUserForm(NewUserServlet.getNewUserProfile(pwmRequest), newUserForm);
// read the creation object classes from configuration
final Set<String> createObjectClasses = new LinkedHashSet<>(pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.DEFAULT_OBJECT_CLASSES));
// add the auto-add object classes
{
final LdapProfile defaultLDAPProfile = pwmApplication.getConfig().getDefaultLdapProfile();
createObjectClasses.addAll(defaultLDAPProfile.readSettingAsStringArray(PwmSetting.AUTO_ADD_OBJECT_CLASSES));
}
final ChaiProvider chaiProvider = pwmApplication.getConfig().getDefaultLdapProfile().getProxyChaiProvider(pwmApplication);
try {
// create the ldap entry
chaiProvider.createEntry(newUserDN, createObjectClasses, createAttributes);
NewUserUtils.LOGGER.info(pwmSession, "created user entry: " + newUserDN);
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error creating user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
final ChaiUser theUser = chaiProvider.getEntryFactory().newChaiUser(newUserDN);
final boolean useTempPw;
{
final String settingValue = pwmApplication.getConfig().readAppProperty(AppProperty.NEWUSER_LDAP_USE_TEMP_PW);
if ("auto".equalsIgnoreCase(settingValue)) {
useTempPw = chaiProvider.getDirectoryVendor() == DirectoryVendor.ACTIVE_DIRECTORY;
} else {
useTempPw = Boolean.parseBoolean(settingValue);
}
}
if (useTempPw) {
NewUserUtils.LOGGER.trace(pwmSession, "will use temporary password process for new user entry: " + newUserDN);
final PasswordData temporaryPassword;
{
final RandomPasswordGenerator.RandomGeneratorConfig randomGeneratorConfig = RandomPasswordGenerator.RandomGeneratorConfig.builder().passwordPolicy(newUserProfile.getNewUserPasswordPolicy(pwmApplication, pwmRequest.getLocale())).build();
temporaryPassword = RandomPasswordGenerator.createRandomPassword(pwmSession.getLabel(), randomGeneratorConfig, pwmApplication);
}
final ChaiUser proxiedUser = chaiProvider.getEntryFactory().newChaiUser(newUserDN);
try {
// set password as admin
proxiedUser.setPassword(temporaryPassword.getStringValue());
NewUserUtils.LOGGER.debug(pwmSession, "set temporary password for new user entry: " + newUserDN);
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error setting temporary password for new user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
// add AD-specific attributes
if (DirectoryVendor.ACTIVE_DIRECTORY == chaiProvider.getDirectoryVendor()) {
try {
NewUserUtils.LOGGER.debug(pwmSession, "setting userAccountControl attribute to enable account " + theUser.getEntryDN());
theUser.writeStringAttribute("userAccountControl", "512");
} catch (ChaiOperationException e) {
final String errorMsg = "error enabling AD account when writing userAccountControl attribute: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, errorMsg);
throw new PwmOperationalException(errorInformation);
}
}
try {
// bind as user
NewUserUtils.LOGGER.debug(pwmSession, "attempting bind as user to then allow changing to requested password for new user entry: " + newUserDN);
final ChaiConfiguration chaiConfiguration = ChaiConfiguration.builder(chaiProvider.getChaiConfiguration()).setSetting(ChaiSetting.BIND_DN, newUserDN).setSetting(ChaiSetting.BIND_PASSWORD, temporaryPassword.getStringValue()).build();
final ChaiProvider bindAsProvider = pwmApplication.getLdapConnectionService().getChaiProviderFactory().newProvider(chaiConfiguration);
final ChaiUser bindAsUser = bindAsProvider.getEntryFactory().newChaiUser(newUserDN);
bindAsUser.changePassword(temporaryPassword.getStringValue(), userPassword.getStringValue());
NewUserUtils.LOGGER.debug(pwmSession, "changed to user requested password for new user entry: " + newUserDN);
bindAsProvider.close();
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error setting user password for new user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
} else {
try {
// set password
theUser.setPassword(userPassword.getStringValue());
NewUserUtils.LOGGER.debug(pwmSession, "set user requested password for new user entry: " + newUserDN);
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error setting password for new user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
// add AD-specific attributes
if (DirectoryVendor.ACTIVE_DIRECTORY == chaiProvider.getDirectoryVendor()) {
try {
theUser.writeStringAttribute("userAccountControl", "512");
} catch (ChaiOperationException e) {
final String errorMsg = "error enabling AD account when writing userAccountControl attribute: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, errorMsg);
throw new PwmOperationalException(errorInformation);
}
}
}
NewUserUtils.LOGGER.trace(pwmSession, "new user ldap creation process complete, now authenticating user");
// write data to remote web service
remoteWriteFormData(pwmRequest, newUserForm);
// authenticate the user to pwm
final UserIdentity userIdentity = new UserIdentity(newUserDN, pwmApplication.getConfig().getDefaultLdapProfile().getIdentifier());
final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.NEW_USER_REGISTRATION);
sessionAuthenticator.authenticateUser(userIdentity, userPassword);
{
// execute configured actions
final List<ActionConfiguration> actions = newUserProfile.readSettingAsAction(PwmSetting.NEWUSER_WRITE_ATTRIBUTES);
if (actions != null && !actions.isEmpty()) {
NewUserUtils.LOGGER.debug(pwmSession, "executing configured actions to user " + theUser.getEntryDN());
final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, userIdentity).setExpandPwmMacros(true).setMacroMachine(pwmSession.getSessionManager().getMacroMachine(pwmApplication)).createActionExecutor();
actionExecutor.executeActions(actions, pwmSession.getLabel());
}
}
// send user email
sendNewUserEmailConfirmation(pwmRequest);
// add audit record
pwmApplication.getAuditManager().submit(AuditEvent.CREATE_USER, pwmSession.getUserInfo(), pwmSession);
// increment the new user creation statistics
pwmApplication.getStatisticsManager().incrementValue(Statistic.NEW_USERS);
NewUserUtils.LOGGER.debug(pwmSession, "completed createUser process for " + newUserDN + " (" + TimeDuration.fromCurrent(startTime).asCompactString() + ")");
}
use of password.pwm.ldap.auth.SessionAuthenticator in project pwm by pwm-project.
the class CASFilterAuthenticationProvider method authUserUsingCASClearPass.
private static boolean authUserUsingCASClearPass(final PwmRequest pwmRequest) throws UnsupportedEncodingException, PwmUnrecoverableException, ChaiUnavailableException, PwmOperationalException {
final PwmSession pwmSession = pwmRequest.getPwmSession();
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final HttpSession session = pwmRequest.getHttpServletRequest().getSession();
// make sure user session isn't already authenticated
if (pwmSession.isAuthenticated()) {
return false;
}
// read CAS assertion out of the header (if it exists);
final Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
if (assertion == null) {
LOGGER.trace(pwmSession, "no CAS assertion header present, skipping CAS authentication attempt");
return false;
}
final String username = assertion.getPrincipal().getName();
PasswordData password = null;
final AttributePrincipal attributePrincipal = assertion.getPrincipal();
final Map<String, Object> casAttributes = attributePrincipal.getAttributes();
final String encodedPsw = (String) casAttributes.get("credential");
if (encodedPsw == null) {
LOGGER.trace("No credential");
} else {
final Map<FileInformation, FileContent> privatekey = pwmRequest.getConfig().readSettingAsFile(PwmSetting.CAS_CLEARPASS_KEY);
final String alg = pwmRequest.getConfig().readSettingAsString(PwmSetting.CAS_CLEARPASS_ALGORITHM);
password = decryptPassword(alg, privatekey, encodedPsw);
}
// If using the old method
final String clearPassUrl = pwmRequest.getConfig().readSettingAsString(PwmSetting.CAS_CLEAR_PASS_URL);
if ((clearPassUrl != null && clearPassUrl.length() > 0) && (password == null || password.getStringValue().length() < 1)) {
LOGGER.trace(pwmSession, "Using CAS clearpass via proxy");
// read cas proxy ticket
final String proxyTicket = assertion.getPrincipal().getProxyTicketFor(clearPassUrl);
if (proxyTicket == null) {
LOGGER.trace(pwmSession, "no CAS proxy ticket available, skipping CAS authentication attempt");
return false;
}
final String clearPassRequestUrl = clearPassUrl + "?" + "ticket=" + proxyTicket + "&" + "service=" + StringUtil.urlEncode(clearPassUrl);
try {
final String response = CommonUtils.getResponseFromServer(new URL(clearPassRequestUrl), new HttpsURLConnectionFactory(), "UTF-8");
password = new PasswordData(XmlUtils.getTextForElement(response, "credentials"));
} catch (MalformedURLException e) {
LOGGER.error(pwmSession, "Invalid CAS clearPassUrl");
}
}
if (password == null || password.getStringValue().length() < 1) {
final String errorMsg = "CAS server did not return credentials for user '" + username + "'";
LOGGER.trace(pwmSession, errorMsg);
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_WRONGPASSWORD, errorMsg);
throw new PwmOperationalException(errorInformation);
}
// user isn't already authenticated and has CAS assertion and password, so try to auth them.
LOGGER.debug(pwmSession, "attempting to authenticate user '" + username + "' using CAS assertion and password");
final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.CAS);
sessionAuthenticator.searchAndAuthenticateUser(username, password, null, null);
return true;
}
use of password.pwm.ldap.auth.SessionAuthenticator in project pwm by pwm-project.
the class CryptoCookieLoginImpl method importRemoteCookie.
private static void importRemoteCookie(final PwmRequest pwmRequest, final LoginInfoBean remoteLoginCookie) throws PwmUnrecoverableException {
if (remoteLoginCookie == null) {
return;
}
final LoginInfoBean localLoginCookie = pwmRequest.getPwmSession().getLoginInfoBean();
if (remoteLoginCookie.isAuthenticated()) {
if (localLoginCookie.isAuthenticated()) {
// should never get here unless one of container session and app session key are swapped between users.
final UserIdentity remoteIdentity = remoteLoginCookie.getUserIdentity();
final UserIdentity localIdentity = localLoginCookie.getUserIdentity();
if (remoteIdentity != null && localIdentity != null && !remoteIdentity.equals(localIdentity)) {
throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_BAD_SESSION, "remote and local session identities differ"));
}
} else {
LOGGER.debug(pwmRequest, "triggering authentication because request contains an authenticated session but local session is unauthenticated");
final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmRequest.getPwmApplication(), pwmRequest.getPwmSession(), remoteLoginCookie.getAuthSource());
try {
if (remoteLoginCookie.getUserIdentity() == null) {
sessionAuthenticator.authUserWithUnknownPassword(remoteLoginCookie.getUserIdentity(), remoteLoginCookie.getType());
} else {
sessionAuthenticator.authenticateUser(remoteLoginCookie.getUserIdentity(), remoteLoginCookie.getUserCurrentPassword());
}
remoteLoginCookie.getAuthFlags().add(AuthenticationType.AUTH_FROM_REQ_COOKIE);
LOGGER.debug(pwmRequest, "logged in using encrypted request cookie = " + JsonUtil.serialize(remoteLoginCookie));
} catch (Exception e) {
final String errorMsg = "unexpected error reading session cookie: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
LOGGER.error(pwmRequest, errorInformation);
throw new PwmUnrecoverableException(errorInformation);
}
}
}
if (pwmRequest.getConfig().isDevDebugMode()) {
LOGGER.trace(pwmRequest, "imported LoginInfoBean=" + remoteLoginCookie.toDebugString());
}
pwmRequest.getPwmSession().setLoginInfoBean(remoteLoginCookie);
}
Aggregations