mirror of
https://github.com/google/nomulus.git
synced 2025-05-19 10:49:35 +02:00
Add XSRF protection to legacy authentication mechanism
------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=148689952
This commit is contained in:
parent
a5932c0fc3
commit
c7a62e9b98
12 changed files with 227 additions and 56 deletions
|
@ -42,6 +42,7 @@ abstract class Route {
|
|||
}
|
||||
|
||||
boolean shouldXsrfProtect(Action.Method requestMethod) {
|
||||
return action().xsrfProtection() && requestMethod != Action.Method.GET;
|
||||
return action().xsrfProtection()
|
||||
&& (requestMethod != Action.Method.GET) && (requestMethod != Action.Method.HEAD);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,6 +17,7 @@ package google.registry.request.auth;
|
|||
import static google.registry.request.auth.AuthLevel.APP;
|
||||
import static google.registry.request.auth.AuthLevel.NONE;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
|
@ -56,6 +57,9 @@ public class AppEngineInternalAuthenticationMechanism implements AuthenticationM
|
|||
// As defined in the App Engine request header documentation.
|
||||
private static final String QUEUE_NAME_HEADER = "X-AppEngine-QueueName";
|
||||
|
||||
@Inject
|
||||
public AppEngineInternalAuthenticationMechanism() {}
|
||||
|
||||
@Override
|
||||
public AuthResult authenticate(HttpServletRequest request) {
|
||||
if (request.getHeader(QUEUE_NAME_HEADER) == null) {
|
||||
|
|
|
@ -16,12 +16,9 @@ package google.registry.request.auth;
|
|||
|
||||
import com.google.appengine.api.oauth.OAuthService;
|
||||
import com.google.appengine.api.oauth.OAuthServiceFactory;
|
||||
import com.google.appengine.api.users.UserService;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import dagger.Module;
|
||||
import dagger.Provides;
|
||||
import google.registry.config.RegistryConfig.Config;
|
||||
|
||||
/**
|
||||
* Dagger module for authentication routines.
|
||||
|
@ -29,28 +26,12 @@ import google.registry.config.RegistryConfig.Config;
|
|||
@Module
|
||||
public class AuthModule {
|
||||
|
||||
/** Provides the internal authentication mechanism. */
|
||||
@Provides
|
||||
AppEngineInternalAuthenticationMechanism provideAppEngineInternalAuthenticationMechanism() {
|
||||
return new AppEngineInternalAuthenticationMechanism();
|
||||
}
|
||||
|
||||
/** Provides the custom authentication mechanisms (including OAuth). */
|
||||
@Provides
|
||||
ImmutableList<AuthenticationMechanism> provideApiAuthenticationMechanisms(
|
||||
OAuthService oauthService,
|
||||
@Config("availableOauthScopes") ImmutableSet<String> availableOauthScopes,
|
||||
@Config("requiredOauthScopes") ImmutableSet<String> requiredOauthScopes,
|
||||
@Config("allowedOauthClientIds") ImmutableSet<String> allowedOauthClientIds) {
|
||||
OAuthAuthenticationMechanism oauthAuthenticationMechanism) {
|
||||
return ImmutableList.<AuthenticationMechanism>of(
|
||||
new OAuthAuthenticationMechanism(
|
||||
oauthService, availableOauthScopes, requiredOauthScopes, allowedOauthClientIds));
|
||||
}
|
||||
|
||||
/** Provides the legacy authentication mechanism. */
|
||||
@Provides
|
||||
LegacyAuthenticationMechanism provideLegacyAuthenticationMechanism(UserService userService) {
|
||||
return new LegacyAuthenticationMechanism(userService);
|
||||
oauthAuthenticationMechanism);
|
||||
}
|
||||
|
||||
/** Provides the OAuthService instance. */
|
||||
|
|
|
@ -9,6 +9,7 @@ java_library(
|
|||
srcs = glob(["*.java"]),
|
||||
deps = [
|
||||
"//java/google/registry/config",
|
||||
"//java/google/registry/security",
|
||||
"//java/google/registry/util",
|
||||
"@com_google_appengine_api_1_0_sdk",
|
||||
"@com_google_auto_value",
|
||||
|
|
|
@ -14,11 +14,15 @@
|
|||
|
||||
package google.registry.request.auth;
|
||||
|
||||
import static com.google.common.base.Strings.nullToEmpty;
|
||||
import static google.registry.request.auth.AuthLevel.NONE;
|
||||
import static google.registry.request.auth.AuthLevel.USER;
|
||||
import static google.registry.security.XsrfTokenManager.X_CSRF_TOKEN;
|
||||
|
||||
import com.google.appengine.api.users.UserService;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import google.registry.security.XsrfTokenManager;
|
||||
import javax.inject.Inject;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
|
@ -27,25 +31,36 @@ import javax.servlet.http.HttpServletRequest;
|
|||
*
|
||||
* <p>Just use the values returned by UserService.
|
||||
*/
|
||||
// TODO(mountford) Add XSRF protection here or elsewhere, from RequestHandler
|
||||
public class LegacyAuthenticationMechanism implements AuthenticationMechanism {
|
||||
|
||||
private final UserService userService;
|
||||
private final XsrfTokenManager xsrfTokenManager;
|
||||
|
||||
/** HTTP methods which are considered safe, and do not require XSRF protection. */
|
||||
private static final ImmutableSet<String> SAFE_METHODS = ImmutableSet.of("GET", "HEAD");
|
||||
|
||||
@VisibleForTesting
|
||||
@Inject
|
||||
public LegacyAuthenticationMechanism(UserService userService) {
|
||||
public LegacyAuthenticationMechanism(UserService userService, XsrfTokenManager xsrfTokenManager) {
|
||||
this.userService = userService;
|
||||
this.xsrfTokenManager = xsrfTokenManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthResult authenticate(HttpServletRequest request) {
|
||||
if (!userService.isUserLoggedIn()) {
|
||||
return AuthResult.create(NONE);
|
||||
} else {
|
||||
return AuthResult.create(
|
||||
USER,
|
||||
UserAuthInfo.create(userService.getCurrentUser(), userService.isUserAdmin()));
|
||||
}
|
||||
|
||||
if (!SAFE_METHODS.contains(request.getMethod())
|
||||
&& !xsrfTokenManager.validateToken(
|
||||
nullToEmpty(request.getHeader(X_CSRF_TOKEN)),
|
||||
"console")) { // hard-coded for now; in the long run, this will be removed
|
||||
return AuthResult.create(NONE);
|
||||
}
|
||||
|
||||
return AuthResult.create(
|
||||
USER,
|
||||
UserAuthInfo.create(userService.getCurrentUser(), userService.isUserAdmin()));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -25,6 +25,7 @@ import com.google.common.hash.Hashing;
|
|||
import google.registry.util.Clock;
|
||||
import google.registry.util.FormattingLogger;
|
||||
import java.util.List;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.Duration;
|
||||
|
@ -32,6 +33,8 @@ import org.joda.time.Duration;
|
|||
/** Helper class for generating and validate XSRF tokens. */
|
||||
public final class XsrfTokenManager {
|
||||
|
||||
// TODO(b/35388772): remove the scope parameter
|
||||
|
||||
/** HTTP header used for transmitting XSRF tokens. */
|
||||
public static final String X_CSRF_TOKEN = "X-CSRF-Token";
|
||||
|
||||
|
@ -48,8 +51,16 @@ public final class XsrfTokenManager {
|
|||
this.userService = userService;
|
||||
}
|
||||
|
||||
private static String encodeToken(long creationTime, String scope, String userEmail) {
|
||||
String token = Joiner.on('\t').join(getServerSecret(), userEmail, scope, creationTime);
|
||||
/**
|
||||
* Encode a token.
|
||||
*
|
||||
* <p>The token is a Base64-encoded SHA-256 hash of a string containing the secret, email, scope
|
||||
* and creation time, separated by tabs. If the scope is null, the string is secret, email,
|
||||
* creation time. In the future, the scope option will be removed.
|
||||
*/
|
||||
private static String encodeToken(long creationTime, @Nullable String scope, String userEmail) {
|
||||
String token =
|
||||
Joiner.on('\t').skipNulls().join(getServerSecret(), userEmail, scope, creationTime);
|
||||
return base64Url().encode(Hashing.sha256()
|
||||
.newHasher(token.length())
|
||||
.putString(token, UTF_8)
|
||||
|
@ -58,28 +69,69 @@ public final class XsrfTokenManager {
|
|||
}
|
||||
|
||||
/**
|
||||
* Generate an xsrf token for a given scope using the logged in user or else no user.
|
||||
* Generate an xsrf token for a given scope using the email of the logged in user or else no user.
|
||||
*
|
||||
* <p>If there is no user, the entire xsrf check becomes basically a no-op, but that's ok because
|
||||
* any callback that doesn't have a user shouldn't be able to access any per-user resources
|
||||
* anyways.
|
||||
*
|
||||
* <p>The scope (or lack thereof) is passed to {@link #encodeToken}. Use of a scope in xsrf tokens
|
||||
* is deprecated; instead, use the no-argument version.
|
||||
*/
|
||||
public String generateToken(String scope) {
|
||||
return generateToken(scope, getLoggedInEmailOrEmpty());
|
||||
@Deprecated
|
||||
public String generateTokenWithCurrentUser(@Nullable String scope) {
|
||||
return generateTokenSub(scope, getLoggedInEmailOrEmpty());
|
||||
}
|
||||
|
||||
/** Generate an xsrf token for a given scope and user. */
|
||||
public String generateToken(String scope, String email) {
|
||||
/**
|
||||
* Generate an xsrf token for a given scope and user.
|
||||
*
|
||||
* <p>The scope (or lack thereof) is passed to {@link #encodeToken}. Use of a scope in xsrf tokens
|
||||
* is deprecated; instead, use the no-argument version.
|
||||
*/
|
||||
@Deprecated
|
||||
public String generateToken(@Nullable String scope, String email) {
|
||||
long now = clock.nowUtc().getMillis();
|
||||
return Joiner.on(':').join(encodeToken(now, scope, email), now);
|
||||
}
|
||||
|
||||
/** Generate an xsrf token for a given user. */
|
||||
public String generateToken(String email) {
|
||||
return generateTokenSub(null, email);
|
||||
}
|
||||
|
||||
private String getLoggedInEmailOrEmpty() {
|
||||
return userService.isUserLoggedIn() ? userService.getCurrentUser().getEmail() : "";
|
||||
}
|
||||
|
||||
/** Validate an xsrf token, given the scope it was used for. */
|
||||
public boolean validateToken(String token, String scope) {
|
||||
private String generateTokenSub(@Nullable String scope, String email) {
|
||||
long now = clock.nowUtc().getMillis();
|
||||
return Joiner.on(':').join(encodeToken(now, scope, email), now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an xsrf token, given the scope it was used for.
|
||||
*
|
||||
* <p>We plan to remove the scope parameter. As a first step, the method first checks for the
|
||||
* existence of a token with no scope. If that is not found, it then looks for the existence of a
|
||||
* token with the specified scope. Our next step will be to have clients pass in a null scope.
|
||||
* Finally, we will remove scopes from this code altogether.
|
||||
*/
|
||||
@Deprecated
|
||||
public boolean validateToken(String token, @Nullable String scope) {
|
||||
return validateTokenSub(token, scope);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an xsrf token.
|
||||
*
|
||||
* <p>This is the non-scoped version to which we will transition in the future.
|
||||
*/
|
||||
public boolean validateToken(String token) {
|
||||
return validateTokenSub(token, null);
|
||||
}
|
||||
|
||||
private boolean validateTokenSub(String token, @Nullable String scope) {
|
||||
List<String> tokenParts = Splitter.on(':').splitToList(token);
|
||||
if (tokenParts.size() != 2) {
|
||||
logger.warningfmt("Malformed XSRF token: %s", token);
|
||||
|
@ -98,11 +150,21 @@ public final class XsrfTokenManager {
|
|||
logger.infofmt("Expired timestamp in XSRF token: %s", token);
|
||||
return false;
|
||||
}
|
||||
String reconstructedToken = encodeToken(creationTime, scope, getLoggedInEmailOrEmpty());
|
||||
if (!reconstructedToken.equals(encodedPart)) {
|
||||
logger.warningfmt("Reconstructed XSRF mismatch: %s ≠ %s", encodedPart, reconstructedToken);
|
||||
return false;
|
||||
// First, check for a scopeless token, because that's the token of the future.
|
||||
String reconstructedToken = encodeToken(creationTime, null, getLoggedInEmailOrEmpty());
|
||||
if (reconstructedToken.equals(encodedPart)) {
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
|
||||
// If we don't find one, look for one with the specified scope.
|
||||
if (scope != null) {
|
||||
reconstructedToken = encodeToken(creationTime, scope, getLoggedInEmailOrEmpty());
|
||||
if (reconstructedToken.equals(encodedPart)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
logger.warningfmt("Reconstructed XSRF mismatch: %s ≠ %s", encodedPart, reconstructedToken);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -105,7 +105,10 @@ public final class ConsoleUiAction implements Runnable {
|
|||
return;
|
||||
}
|
||||
Registrar registrar = Registrar.loadByClientId(sessionUtils.getRegistrarClientId(req));
|
||||
data.put("xsrfToken", xsrfTokenManager.generateToken(EppConsoleAction.XSRF_SCOPE));
|
||||
data.put(
|
||||
"xsrfToken",
|
||||
xsrfTokenManager.generateToken(
|
||||
EppConsoleAction.XSRF_SCOPE, userService.getCurrentUser().getEmail()));
|
||||
data.put("clientId", registrar.getClientId());
|
||||
data.put("showPaymentLink", registrar.getBillingMethod() == Registrar.BillingMethod.BRAINTREE);
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue