Skip to content

Commit

Permalink
Polish gh-15554
Browse files Browse the repository at this point in the history
Closes gh-15398
  • Loading branch information
sjohnr committed Nov 13, 2024
1 parent 33976d0 commit 909dcc6
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 33 deletions.
12 changes: 8 additions & 4 deletions docs/modules/ROOT/pages/servlet/authentication/architecture.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,11 @@ image::{figures}/providermanagers-parent.png[]
By default, `ProviderManager` tries to clear any sensitive credentials information from the `Authentication` object that is returned by a successful authentication request.
This prevents information, such as passwords, being retained longer than necessary in the `HttpSession`.

> **Note:** The `CredentialsContainer` interface plays a critical role in the authentication process. It allows for the erasure of credential information once it is no longer needed, thereby enhancing security by ensuring sensitive data is not retained longer than necessary.
[NOTE]
====
The `CredentialsContainer` interface plays a critical role in the authentication process.
It allows for the erasure of credential information once it is no longer needed, thereby enhancing security by ensuring sensitive data is not retained longer than necessary.
====

This may cause issues when you use a cache of user objects, for example, to improve performance in a stateless application.
If the `Authentication` contains a reference to an object in the cache (such as a `UserDetails` instance) and this has its credentials removed, it is no longer possible to authenticate against the cached value.
Expand Down Expand Up @@ -249,21 +253,21 @@ image:{icondir}/number_3.png[] If authentication fails, then __Failure__.
* The <<servlet-authentication-securitycontextholder>> is cleared out.
* `RememberMeServices.loginFail` is invoked.
If remember me is not configured, this is a no-op.
See the javadoc:org.springframework.security.web.authentication.rememberme.package-summary[] package.
See the javadoc:org.springframework.security.web.authentication.rememberme.package-summary[rememberme] package.
* `AuthenticationFailureHandler` is invoked.
See the javadoc:org.springframework.security.web.authentication.AuthenticationFailureHandler[] interface.

image:{icondir}/number_4.png[] If authentication is successful, then __Success__.

* `SessionAuthenticationStrategy` is notified of a new login.
See the {security-api-url}org/springframework/security/web/authentication/session/SessionAuthenticationStrategy.html[`SessionAuthenticationStrategy`] interface.
See the javadoc:org.springframework.security.web.authentication.session.SessionAuthenticationStrategy[] interface.
* The <<servlet-authentication-authentication>> is set on the <<servlet-authentication-securitycontextholder>>.
Later, if you need to save the `SecurityContext` so that it can be automatically set on future requests, `SecurityContextRepository#saveContext` must be explicitly invoked.
See the javadoc:org.springframework.security.web.context.SecurityContextHolderFilter[] class.

* `RememberMeServices.loginSuccess` is invoked.
If remember me is not configured, this is a no-op.
See the javadoc:org.springframework.security.web.authentication.rememberme.package-summary[] package.
See the javadoc:org.springframework.security.web.authentication.rememberme.package-summary[rememberme] package.
* `ApplicationEventPublisher` publishes an `InteractiveAuthenticationSuccessEvent`.
* `AuthenticationSuccessHandler` is invoked.
See the javadoc:org.springframework.security.web.authentication.AuthenticationSuccessHandler[] interface.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,40 +1,41 @@
== Password Erasure

After successful authentication, it's a security best practice to erase credentials from memory to prevent them from being exposed to potential memory dump attacks. `ProviderManager` and most `AuthenticationProvider` implementations in Spring Security support this practice through the `eraseCredentials` method, which should be invoked after the authentication process completes.
After successful authentication, it is a security best practice to erase credentials from memory to prevent them from being exposed to potential memory dump attacks.
`ProviderManager` in Spring Security supports this practice through the `eraseCredentials` method, which should be invoked after the authentication process is complete.

=== Best Practices

. *Immediate Erasure*: Credentials should be erased immediately after they are no longer needed. This minimizes the window during which the credentials are exposed in memory.
. *Automatic Erasure*: Configure `ProviderManager` to automatically erase credentials post-authentication by setting `eraseCredentialsAfterAuthentication` to `true`.
. *Custom Erasure Strategies*: Implement custom erasure strategies in custom `AuthenticationProvider` implementations if the default erasure behavior does not meet specific security requirements.
* *Immediate Erasure*: Credentials should be erased immediately after they are no longer needed, which minimizes the window during which the credentials are exposed in memory.
* *Automatic Erasure*: Configure `ProviderManager` to automatically erase credentials post-authentication by setting `eraseCredentialsAfterAuthentication` to `true` (the default).
* *Custom Erasure Strategies*: Implement custom erasure strategies in custom `AuthenticationManager` implementations if the default erasure behavior does not meet specific security requirements.

=== Risk Assessment

Failure to properly erase credentials can lead to several risks:

. *Memory Access Attacks*: Attackers can access raw credentials from memory through exploits like buffer overflow attacks or memory dumps.
. *Insider Threats*: Malicious insiders with access to systems could potentially extract credentials from application memory.
. *Accidental Exposure*: In multi-tenant environments, lingering credentials in memory could accidentally be exposed to other tenants.
* *Memory Access Attacks*: Attackers can access raw credentials from memory through exploits like buffer overflow attacks or memory dumps.
* *Insider Threats*: Malicious insiders with access to systems could potentially extract credentials from application memory.
* *Accidental Exposure*: In multi-tenant environments, lingering credentials in memory could accidentally be exposed to other tenants.

=== Implementation

[source,java]
----
public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
// Perform authentication checks
if (!passwordEncoder.matches(authentication.getCredentials().toString(), userDetails.getPassword())) {
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
// Erase credentials post-check
authentication.eraseCredentials();
}
public class CustomAuthenticationManager implements AuthenticationManager {
@Override
public Authentication authenticate(Authentication authenticationRequest)
throws AuthenticationException {
Authentication authenticationResult;
// TODO: Perform authentication checks...
// Erase credentials post-check
if (authenticationResult instanceof CredentialsContainer container) {
container.eraseCredentials();
}
}
}
----

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,50 @@ The xref:servlet/authentication/passwords/dao-authentication-provider.adoc#servl

== Credentials Management

Implementing the `CredentialsContainer` interface in classes that store user credentials, such as those extending or implementing `UserDetails`, is strongly recommended, especially in applications where user details are not cached. This practice enhances security by ensuring that sensitive data, such as passwords, are not retained in memory longer than necessary.
Implementing the `CredentialsContainer` interface in classes that store user credentials, such as those extending or implementing `UserDetails`, is strongly recommended, especially in applications where user details are not cached.
This practice enhances security by ensuring that sensitive data, such as passwords, are not retained in memory longer than necessary.

=== When to Implement CredentialsContainer
[TIP]
====
In cases where user details are cached, consider creating a copy of the `UserDetails` that does not include credentials and returning the copy in the response from a custom `AuthenticationProvider` instead of the original object.
This can help prevent the cached instance containing credentials from being referenced by the rest of the application once the authentication process is complete.
====

Applications that do not employ caching mechanisms for `UserDetails` should particularly consider implementing `CredentialsContainer`. This approach helps in mitigating the risk associated with retaining sensitive information in memory, which can be vulnerable to attack vectors such as memory dumps.
=== When to Implement `CredentialsContainer`

Applications that do not employ caching mechanisms for `UserDetails` should particularly consider implementing `CredentialsContainer`.
This approach helps in mitigating the risk associated with retaining sensitive information in memory, which can be vulnerable to attack vectors such as memory dumps.

[source,java]
----
public class MyUserDetails implements UserDetails, CredentialsContainer {
private String username;
private String password;
// UserDetails implementation...
@Override
public void eraseCredentials() {
this.password = null; // Securely erase the password field
this.password = null; // Securely dereference the password field
}
}
----

=== Implementation Guidelines

* *Immediate Erasure*: Credentials should be erased immediately after they are no longer needed, typically post-authentication.
* *Automatic Invocation*: Ensure that `eraseCredentials()` is automatically called by your authentication framework, such as `AuthenticationManager` or `AuthenticationProvider`, once the authentication process is complete.
* *Automatic Invocation*: Ensure that `eraseCredentials()` is automatically called by your authentication framework, such as `AuthenticationManager`, once the authentication process is complete.
* *Consistency*: Apply this practice uniformly across all applications to prevent security lapses that could lead to data breaches.

=== Beyond Basic Interface Implementation

While interfaces like `CredentialsContainer` provide a framework for credential management, the practical implementation often depends on specific classes and their interactions. For example, the `DaoAuthenticationProvider` class, adhering to the `AuthenticationProvider`'s contract, does not perform credential erasure within its own `authenticate` method.
While interfaces like `CredentialsContainer` provide a framework for credential management, the practical implementation often depends on specific classes and their interactions.

Instead, it relies on `ProviderManager`—Spring Security's default implementation of `AuthenticationManager`—to handle the erasure of credentials and other sensitive data post-authentication. This separation emphasizes the principle that the authentication process itself should not assume the responsibility for credential management. It is worth noting that the `AuthenticationManager` API documentation specifies that the implementation should return "a fully authenticated object including credentials" via the `authenticate` method, underscoring the distinction between authentication and credential management.
For example, the `DaoAuthenticationProvider` class, adhering to the contract of `AuthenticationProvider`, does not perform credential erasure within its own `authenticate` method.
Instead, it relies on `ProviderManager`—Spring Security's default implementation of `AuthenticationManager`—to handle the erasure of credentials and other sensitive data post-authentication.
This separation emphasizes the principle that the `AuthenticationProvider` should not assume the responsibility for credentials management.

Incorporating `CredentialsContainer` into your `UserDetails` implementation aligns with security best practices, reducing potential exposure to data breaches by minimizing the lifespan of sensitive data in memory.

0 comments on commit 909dcc6

Please sign in to comment.