Skip to content

Commit 722fdd5

Browse files
authored
Don't fallback to anonymous for tokens/apikeys (#51042)
This commit changes our behavior so that when we receive a request with an invalid/expired/wrong access token or API Key we do not fallback to authenticating as the anonymous user even if anonymous access is enabled for Elasticsearch.
1 parent 394f09c commit 722fdd5

File tree

2 files changed

+70
-1
lines changed

2 files changed

+70
-1
lines changed

x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/AuthenticationService.java

+16-1
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,7 @@ private List<Realm> getRealmList(String principal) {
460460
* <ul>
461461
* <li>this is an initial request from a client without preemptive authentication, so we must return an authentication
462462
* challenge</li>
463+
* <li>this is a request that contained an Authorization Header that we can't validate </li>
463464
* <li>this is a request made internally within a node and there is a fallback user, which is typically the
464465
* {@link SystemUser}</li>
465466
* <li>anonymous access is enabled and this will be considered an anonymous request</li>
@@ -475,7 +476,7 @@ void handleNullToken() {
475476
RealmRef authenticatedBy = new RealmRef("__fallback", "__fallback", nodeName);
476477
authentication = new Authentication(fallbackUser, authenticatedBy, null, Version.CURRENT, AuthenticationType.INTERNAL,
477478
Collections.emptyMap());
478-
} else if (isAnonymousUserEnabled) {
479+
} else if (isAnonymousUserEnabled && shouldFallbackToAnonymous()) {
479480
logger.trace("No valid credentials found in request [{}], using anonymous [{}]", request, anonymousUser.principal());
480481
RealmRef authenticatedBy = new RealmRef("__anonymous", "__anonymous", nodeName);
481482
authentication = new Authentication(anonymousUser, authenticatedBy, null, Version.CURRENT, AuthenticationType.ANONYMOUS,
@@ -499,6 +500,20 @@ void handleNullToken() {
499500
action.run();
500501
}
501502

503+
/**
504+
* When an API Key or an Elasticsearch Token Service token is used for authentication and authentication fails (as indicated by
505+
* a null AuthenticationToken) we should not fallback to the anonymous user.
506+
*/
507+
boolean shouldFallbackToAnonymous(){
508+
String header = threadContext.getHeader("Authorization");
509+
if (Strings.hasText(header) &&
510+
((header.regionMatches(true, 0, "Bearer ", 0, "Bearer ".length()) && header.length() > "Bearer ".length()) ||
511+
(header.regionMatches(true, 0, "ApiKey ", 0, "ApiKey ".length()) && header.length() > "ApiKey ".length()))) {
512+
return false;
513+
}
514+
return true;
515+
}
516+
502517
/**
503518
* Consumes the {@link User} that resulted from attempting to authenticate a token against the {@link Realms}. When the user is
504519
* {@code null}, authentication fails and does not proceed. When there is a user, the request is inspected to see if the run as

x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java

+54
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@
9999
import java.util.concurrent.atomic.AtomicBoolean;
100100
import java.util.function.Consumer;
101101

102+
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
102103
import static org.elasticsearch.test.SecurityTestsUtils.assertAuthenticationException;
103104
import static org.elasticsearch.xpack.core.security.support.Exceptions.authenticationError;
104105
import static org.elasticsearch.xpack.security.authc.TokenServiceTests.mockGetTokenFromId;
@@ -743,6 +744,59 @@ public void testAuthenticateTamperedUser() throws Exception {
743744
}
744745
}
745746

747+
public void testWrongTokenDoesNotFallbackToAnonymous() {
748+
String username = randomBoolean() ? AnonymousUser.DEFAULT_ANONYMOUS_USERNAME : "user1";
749+
Settings.Builder builder = Settings.builder()
750+
.putList(AnonymousUser.ROLES_SETTING.getKey(), "r1", "r2", "r3");
751+
if (username.equals(AnonymousUser.DEFAULT_ANONYMOUS_USERNAME) == false) {
752+
builder.put(AnonymousUser.USERNAME_SETTING.getKey(), username);
753+
}
754+
Settings anonymousEnabledSettings = builder.build();
755+
final AnonymousUser anonymousUser = new AnonymousUser(anonymousEnabledSettings);
756+
service = new AuthenticationService(anonymousEnabledSettings, realms, auditTrail,
757+
new DefaultAuthenticationFailureHandler(Collections.emptyMap()), threadPool, anonymousUser, tokenService, apiKeyService);
758+
759+
try (ThreadContext.StoredContext ignore = threadContext.stashContext()) {
760+
final String reqId = AuditUtil.getOrGenerateRequestId(threadContext);
761+
threadContext.putHeader("Authorization", "Bearer thisisaninvalidtoken");
762+
ElasticsearchSecurityException e =
763+
expectThrows(ElasticsearchSecurityException.class, () -> authenticateBlocking("_action", message, null));
764+
verify(auditTrail).anonymousAccessDenied(reqId, "_action", message);
765+
verifyNoMoreInteractions(auditTrail);
766+
assertAuthenticationException(e);
767+
}
768+
}
769+
770+
public void testWrongApiKeyDoesNotFallbackToAnonymous() {
771+
String username = randomBoolean() ? AnonymousUser.DEFAULT_ANONYMOUS_USERNAME : "user1";
772+
Settings.Builder builder = Settings.builder()
773+
.putList(AnonymousUser.ROLES_SETTING.getKey(), "r1", "r2", "r3");
774+
if (username.equals(AnonymousUser.DEFAULT_ANONYMOUS_USERNAME) == false) {
775+
builder.put(AnonymousUser.USERNAME_SETTING.getKey(), username);
776+
}
777+
Settings anonymousEnabledSettings = builder.build();
778+
final AnonymousUser anonymousUser = new AnonymousUser(anonymousEnabledSettings);
779+
service = new AuthenticationService(anonymousEnabledSettings, realms, auditTrail,
780+
new DefaultAuthenticationFailureHandler(Collections.emptyMap()), threadPool, anonymousUser, tokenService, apiKeyService);
781+
doAnswer(invocationOnMock -> {
782+
final GetRequest request = (GetRequest) invocationOnMock.getArguments()[0];
783+
final ActionListener<GetResponse> listener = (ActionListener<GetResponse>) invocationOnMock.getArguments()[1];
784+
listener.onResponse(new GetResponse(new GetResult(request.index(), request.id(),
785+
SequenceNumbers.UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, -1L, false, null,
786+
Collections.emptyMap(), Collections.emptyMap())));
787+
return Void.TYPE;
788+
}).when(client).get(any(GetRequest.class), any(ActionListener.class));
789+
try (ThreadContext.StoredContext ignore = threadContext.stashContext()) {
790+
final String reqId = AuditUtil.getOrGenerateRequestId(threadContext);
791+
threadContext.putHeader("Authorization", "ApiKey dGhpc2lzYW5pbnZhbGlkaWQ6dGhpc2lzYW5pbnZhbGlkc2VjcmV0");
792+
ElasticsearchSecurityException e =
793+
expectThrows(ElasticsearchSecurityException.class, () -> authenticateBlocking("_action", message, null));
794+
verify(auditTrail).anonymousAccessDenied(reqId, "_action", message);
795+
verifyNoMoreInteractions(auditTrail);
796+
assertAuthenticationException(e);
797+
}
798+
}
799+
746800
public void testAnonymousUserRest() throws Exception {
747801
String username = randomBoolean() ? AnonymousUser.DEFAULT_ANONYMOUS_USERNAME : "user1";
748802
Settings.Builder builder = Settings.builder()

0 commit comments

Comments
 (0)