diff --git a/CHANGES.md b/CHANGES.md index b2240dc96..0f0307fae 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -57,8 +57,11 @@ - **New passwords can't be the external-login placeholder.** Registration, the profile page and user administration refuse `users.passwords.externalAuthValue` (by default ``) as a - password, and it never works as one. An administrator can set a new password - for an account that used it (#304). + password, and it never works as one. When you change that setting, list its + earlier values in the new `users.passwords.externalAuthValue.previous` + (comma-separated) so they're treated the same. A login refused for this + reason is logged, and an administrator can set a new password for an + account that used one (#304, #364). - **Roller UI stylesheets, scripts and images don't start a session** (#310). - **The LDAP comment authenticator escapes the commenter's user name** when it builds the bind name (#322). diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java index 3e1886af3..94e07cf97 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java @@ -19,9 +19,12 @@ import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.Map; +import java.util.Set; import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.config.WebloggerConfig; @@ -57,14 +60,33 @@ public static String externalLoginMarker() { } /** - * Whether a password is the configured external-login marker or the - * default one, which accounts may still have stored from before the - * setting changed. Neither matches at login, so neither can be chosen as a - * Roller password. + * Whether a password is the configured external-login marker, the default + * one, or one listed in users.passwords.externalAuthValue.previous, which + * accounts may still have stored from before the setting changed. None of + * them matches at login, so none can be chosen as a Roller password. */ public static boolean isExternalLoginMarker(CharSequence password) { - return password != null && (externalLoginMarker().contentEquals(password) - || DEFAULT_EXTERNAL_LOGIN_MARKER.contentEquals(password)); + return password != null && externalLoginMarkers().contains(password.toString()); + } + + /** + * The configured marker, the default one and the previous ones. The + * previous ones are a comma-separated list, so a marker that contains a + * comma can't be listed there. + */ + private static Set externalLoginMarkers() { + Set markers = new LinkedHashSet<>(); + markers.add(externalLoginMarker()); + markers.add(DEFAULT_EXTERNAL_LOGIN_MARKER); + String previous = WebloggerConfig.getProperty("users.passwords.externalAuthValue.previous"); + for (String marker : StringUtils.split(StringUtils.defaultString(previous), ',')) { + // an empty entry is never a marker, so an empty password isn't one + String trimmed = marker.trim(); + if (!trimmed.isEmpty()) { + markers.add(trimmed); + } + } + return markers; } @SuppressWarnings("deprecation") @@ -119,6 +141,11 @@ public static PasswordEncoder create() { log.info("Password Encryption Algorithm set to '" + algorithm + "'"); + if (externalLoginMarker().contains(",")) { + log.warn("users.passwords.externalAuthValue contains a comma, so it can't be listed in" + + " users.passwords.externalAuthValue.previous if the setting changes later."); + } + return new ExternalLoginAware(new DelegatingPasswordEncoder(algorithm, encoders)); } @@ -126,7 +153,8 @@ public static PasswordEncoder create() { * Users who log in through LDAP or the servlet container have no Roller * password; Roller stores users.passwords.externalAuthValue in its place. * That placeholder is not a password, so it never matches, and neither do - * the default placeholder and an empty password. + * the default or a previous placeholder, a password the delegate treats as + * equal to one of them, and an empty password. */ private record ExternalLoginAware(PasswordEncoder delegate) implements PasswordEncoder { @@ -137,13 +165,39 @@ public String encode(CharSequence rawPassword) { @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { + if (rawPassword == null || rawPassword.length() == 0) { + return false; + } + Set markers = externalLoginMarkers(); // a stored marker is checked before the delegate sees it, since a // marker such as {noop}secret would otherwise match its own suffix - if (rawPassword == null || rawPassword.length() == 0 || isExternalLoginMarker(rawPassword) - || isExternalLoginMarker(encodedPassword)) { + if (markers.contains(encodedPassword)) { + return false; + } + if (markers.contains(rawPassword.toString())) { + logRefusal(); + return false; + } + if (!delegate.matches(rawPassword, encodedPassword)) { return false; } - return delegate.matches(rawPassword, encodedPassword); + // BCrypt, for one, treats some other passwords as equal to a + // marker, so refuse any password whose stored value a marker + // matches too + for (String marker : markers) { + if (delegate.matches(marker, encodedPassword)) { + logRefusal(); + return false; + } + } + return true; + } + + private static void logRefusal() { + // the password itself is never logged + log.info("Refused a password that Roller treats as an external-login marker" + + " (users.passwords.externalAuthValue or its .previous list). An" + + " administrator can set a new password for an account that uses one."); } @Override diff --git a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties index 970dac6f4..c72d50fc6 100644 --- a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties +++ b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties @@ -360,6 +360,14 @@ weblog.inlineImages.maxFieldBytes=60000 # Empty value used for passphrase in roller_user table when LDAP, CMA, or OIDC used. users.passwords.externalAuthValue= +# Comma-separated values that users.passwords.externalAuthValue had before. +# Accounts created then still have them stored, so list them here when changing +# that setting, in the same restart; none of them is accepted as a password. +# A value that contains a comma can't be listed, and an account that has logged +# in with an earlier value, or whose own password is one of them, needs an +# administrator to set a new password. +users.passwords.externalAuthValue.previous= + # OIDC provider configuration. To configure a provider, set all three required # properties using the pattern oidc.{registrationId}.{property}. # Multiple providers can be configured with different registration IDs. diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginPlaceholderTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginPlaceholderTest.java index 8f83b8857..a4d0249de 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginPlaceholderTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginPlaceholderTest.java @@ -33,6 +33,7 @@ import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -139,6 +140,51 @@ void theDefaultPlaceholderIsNotAPasswordUnderAnotherConfiguredValue() throws Exc assertFalse(RollerPasswordEncoders.create().matches("", "")); } + @Test + void aPreviousEncodedPlaceholderIsNotAPasswordAfterTheSettingChanges() throws Exception { + setProperty("authentication.method", "cma"); + // as Register stored it for container-managed sign-ups + User user = TestUtils.setupUser("oldcmauser"); + userName = user.getUserName(); + user.setPassword(RollerPasswordEncoders.create().encode("")); + WebloggerFactory.getWeblogger().getUserManager().saveUser(user); + TestUtils.endSession(true); + + setProperty("users.passwords.externalAuthValue", ""); + setProperty("users.passwords.externalAuthValue.previous", ","); + + assertThrows(AuthenticationException.class, () -> provider().authenticate( + UsernamePasswordAuthenticationToken.unauthenticated(userName, ""))); + assertFalse(RollerPasswordEncoders.create().matches("", user.getPassword())); + } + + @Test + void aPreviousUnencodedPlaceholderIsNotAPasswordAfterTheSettingChanges() throws Exception { + setProperty("authentication.method", "ldap"); + setProperty("users.passwords.externalAuthValue", ""); + setProperty("users.passwords.externalAuthValue.previous", "{noop}secret"); + // as CustomUserRegistry stored it before the setting changed + User user = TestUtils.setupUser("oldldapuser"); + userName = user.getUserName(); + user.setPassword("{noop}secret"); + WebloggerFactory.getWeblogger().getUserManager().saveUser(user); + TestUtils.endSession(true); + + assertThrows(AuthenticationException.class, () -> provider().authenticate( + UsernamePasswordAuthenticationToken.unauthenticated(userName, "secret"))); + assertFalse(RollerPasswordEncoders.create().matches("secret", "{noop}secret")); + } + + @Test + void emptyEntriesInThePreviousPlaceholdersAreIgnored() throws Exception { + setProperty("users.passwords.externalAuthValue.previous", ", ,, ,"); + + assertTrue(RollerPasswordEncoders.isExternalLoginMarker("")); + assertTrue(RollerPasswordEncoders.isExternalLoginMarker("")); + assertFalse(RollerPasswordEncoders.isExternalLoginMarker("")); + assertFalse(RollerPasswordEncoders.isExternalLoginMarker(" ")); + } + @Test void anEmptyConfiguredPlaceholderIsNotAPassword() throws Exception { setProperty("authentication.method", "db"); @@ -210,6 +256,23 @@ void theEncoderDoesNotMatchThePlaceholder() { assertTrue(encoder.matches("secret", encoder.encode("secret"))); } + @Test + void aPasswordThatBcryptTreatsAsEqualToThePlaceholderNeverMatches() throws Exception { + setProperty("users.passwords.externalAuthValue", ""); + setProperty("users.passwords.externalAuthValue.previous", ""); + PasswordEncoder encoder = RollerPasswordEncoders.create(); + for (String marker : new String[] {"", "", ""}) { + String stored = encoder.encode(marker); + // BCrypt repeats its key, a NUL byte after each copy, so this + // password gives the same hash as the placeholder + String sameKey = marker + '\0' + marker; + assertTrue(new BCryptPasswordEncoder().matches(sameKey, stored.substring("{bcrypt}".length()))); + assertFalse(encoder.matches(sameKey, stored), marker); + } + // a password that only starts like a placeholder still matches + assertTrue(encoder.matches("x", encoder.encode("x"))); + } + private static DaoAuthenticationProvider provider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(new RollerUserDetailsService()); provider.setPasswordEncoder(RollerPasswordEncoders.create()); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java index a76f131f5..ec4220276 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java @@ -75,15 +75,20 @@ void setUp() throws Exception { @AfterEach void tearDown() throws Exception { - factory.close(); - Properties config = config(); - savedProperties.forEach((k, v) -> { - if (v == null) { - config.remove(k); - } else { - config.setProperty(k, v); + try { + if (factory != null) { + factory.close(); } - }); + } finally { + Properties config = config(); + savedProperties.forEach((k, v) -> { + if (v == null) { + config.remove(k); + } else { + config.setProperty(k, v); + } + }); + } } @Test @@ -192,6 +197,42 @@ void anAdministratorCannotCreateAUserWithTheMarker() throws Exception { verify(users, never()).addUser(any()); } + @Test + void theFormsRejectAPreviousMarker() throws Exception { + setProperty("users.passwords.externalAuthValue.previous", ", "); + + Register register = withText(new Register()); + register.getBean().setUserName("newuser"); + register.getBean().setPasswordText(""); + register.getBean().setPasswordConfirm(""); + register.myValidate(); + assertTrue(register.getActionErrors().contains(RESERVED)); + + User user = new User(); + user.setUserName("dbuser"); + user.setPassword("{bcrypt}existing"); + Profile profile = withText(new Profile()); + profile.setAuthenticatedUser(user); + profile.getBean().setPasswordText(""); + profile.getBean().setPasswordConfirm(""); + assertEquals(UIAction.INPUT, profile.save()); + assertTrue(profile.getActionErrors().contains(RESERVED)); + + User admin = new User(); + admin.setUserName("admin"); + UserEdit userEdit = withText(new UserEdit()); + userEdit.setActionName("createUser"); + userEdit.setAuthenticatedUser(admin); + userEdit.myPrepare(); + userEdit.getBean().setUserName("newuser"); + userEdit.getBean().setPassword(""); + assertEquals(UIAction.INPUT, userEdit.save()); + assertTrue(userEdit.getActionErrors().contains(RESERVED)); + + verify(users, never()).saveUser(any()); + verify(users, never()).addUser(any()); + } + private static T withText(T action) { T spied = spy(action); doAnswer(call -> call.getArgument(0)).when(spied).getText(anyString());