From 64482719a9c4a331aea13ae79ccf1f4e42fd0be8 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Wed, 23 Jan 2019 11:04:36 +0200 Subject: [PATCH 01/20] Implement code and implicit flows - Use nimbus oidc sdk - JWE not handled - UserInfo requests not handled --- .../oidc/OpenIdConnectRealmSettings.java | 144 +++++++- x-pack/plugin/security/build.gradle | 10 + .../xpack/security/authc/InternalRealms.java | 2 +- .../oidc/OpenIdConnectAuthenticator.java | 213 ++++++++++++ .../OpenIdConnectProviderConfiguration.java | 33 +- .../authc/oidc/OpenIdConnectRealm.java | 325 ++++++++++++++---- .../authc/oidc/OpenIdConnectToken.java | 23 +- .../authc/oidc/RelyingPartyConfiguration.java | 45 ++- .../RestOpenIdConnectAuthenticateAction.java | 1 - .../authc/oidc/OpenIdConnectRealmTests.java | 111 +++++- 10 files changed, 795 insertions(+), 112 deletions(-) create mode 100644 x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java index 5d51d23c3c69a..98baeeb796bf1 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java @@ -8,9 +8,17 @@ import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.util.set.Sets; +import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.RealmSettings; import org.elasticsearch.xpack.core.security.authc.support.DelegatedAuthorizationSettings; +import org.elasticsearch.xpack.core.ssl.SSLConfigurationSettings; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; @@ -24,34 +32,146 @@ private OpenIdConnectRealmSettings() { public static final String TYPE = "oidc"; - public static final Setting.AffixSetting OP_NAME - = RealmSettings.simpleString(TYPE, "op.name", Setting.Property.NodeScope); public static final Setting.AffixSetting RP_CLIENT_ID = RealmSettings.simpleString(TYPE, "rp.client_id", Setting.Property.NodeScope); public static final Setting.AffixSetting RP_CLIENT_SECRET = RealmSettings.secureString(TYPE, "rp.client_secret"); public static final Setting.AffixSetting RP_REDIRECT_URI - = RealmSettings.simpleString(TYPE, "rp.redirect_uri", Setting.Property.NodeScope); + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "rp.redirect_uri", + key -> Setting.simpleString(key, v -> { + try { + new URI(v); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid value [" + v + "] for [" + key + "]. Not a valid URI.", e); + } + }, Setting.Property.NodeScope)); public static final Setting.AffixSetting RP_RESPONSE_TYPE - = RealmSettings.simpleString(TYPE, "rp.response_type", Setting.Property.NodeScope); + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "rp.response_type", + key -> Setting.simpleString(key, v -> { + List responseTypes = Arrays.asList("code", "id_token"); + if (responseTypes.contains(v) == false) { + throw new IllegalArgumentException("Invalid value [" + v + "] for [" + key + "]. Allowed values are " + responseTypes + ""); + } + }, Setting.Property.NodeScope)); + public static final Setting.AffixSetting RP_SIGNATURE_VERIFICATION_ALGORITHM + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "rp.signature_verification_algorithm", + key -> new Setting<>(key, "RS256", Function.identity(), v -> { + List sigAlgo = Arrays.asList("HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "ES256", "ES384", + "ES512", "PS256", "PS384", "PS512"); + if (sigAlgo.contains(v) == false) { + throw new IllegalArgumentException( + "Invalid value [" + v + "] for [" + key + "]. Allowed values are " + sigAlgo + "}]"); + } + }, Setting.Property.NodeScope)); + public static final Setting.AffixSetting> RP_REQUESTED_SCOPES = Setting.affixKeySetting( + RealmSettings.realmSettingPrefix(TYPE), "rp.requested_scopes", + key -> Setting.listSetting(key, Collections.singletonList("openid"), Function.identity(), Setting.Property.NodeScope)); + + public static final Setting.AffixSetting OP_NAME + = RealmSettings.simpleString(TYPE, "op.name", Setting.Property.NodeScope); public static final Setting.AffixSetting OP_AUTHORIZATION_ENDPOINT - = RealmSettings.simpleString(TYPE, "op.authorization_endpoint", Setting.Property.NodeScope); + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "op.authorization_endpoint", + key -> Setting.simpleString(key, v -> { + try { + new URI(v); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid value [" + v + "] for [" + key + "]. Not a valid URI.", e); + } + }, Setting.Property.NodeScope)); public static final Setting.AffixSetting OP_TOKEN_ENDPOINT - = RealmSettings.simpleString(TYPE, "op.token_endpoint", Setting.Property.NodeScope); + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "op.token_endpoint", + key -> Setting.simpleString(key, v -> { + try { + new URI(v); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid value [" + v + "] for [" + key + "]. Not a valid URI.", e); + } + }, Setting.Property.NodeScope)); public static final Setting.AffixSetting OP_USERINFO_ENDPOINT - = RealmSettings.simpleString(TYPE, "op.userinfo_endpoint", Setting.Property.NodeScope); + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "op.token_endpoint", + key -> Setting.simpleString(key, v -> { + try { + new URI(v); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid value [" + v + "] for [" + key + "]. Not a valid URI.", e); + } + }, Setting.Property.NodeScope)); public static final Setting.AffixSetting OP_ISSUER = RealmSettings.simpleString(TYPE, "op.issuer", Setting.Property.NodeScope); - public static final Setting.AffixSetting> RP_REQUESTED_SCOPES = Setting.affixKeySetting( - RealmSettings.realmSettingPrefix(TYPE), "rp.requested_scopes", - key -> Setting.listSetting(key, Collections.singletonList("openid"), Function.identity(), Setting.Property.NodeScope)); + public static final Setting.AffixSetting OP_JWKSET_URL + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "op.jwkset_url", + key -> Setting.simpleString(key, v -> { + try { + new URL(v); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("Invalid value [" + v + "] for [" + key + "]. Not a valid URL.", e); + } + }, Setting.Property.NodeScope)); + + public static final Setting.AffixSetting POPULATE_USER_METADATA = Setting.affixKeySetting( + RealmSettings.realmSettingPrefix(TYPE), "populate_user_metadata", + key -> Setting.boolSetting(key, true, Setting.Property.NodeScope)); + + public static final ClaimSetting PRINCIPAL_CLAIM = new ClaimSetting("principal"); + public static final ClaimSetting GROUPS_CLAIM = new ClaimSetting("groups"); + public static final ClaimSetting NAME_CLAIM = new ClaimSetting("name"); + public static final ClaimSetting DN_CLAIM = new ClaimSetting("dn"); + public static final ClaimSetting MAIL_CLAIM = new ClaimSetting("mail"); public static Set> getSettings() { final Set> set = Sets.newHashSet( - OP_NAME, RP_CLIENT_ID, RP_REDIRECT_URI, RP_RESPONSE_TYPE, RP_REQUESTED_SCOPES, RP_CLIENT_SECRET, - OP_AUTHORIZATION_ENDPOINT, OP_TOKEN_ENDPOINT, OP_USERINFO_ENDPOINT, OP_ISSUER); + RP_CLIENT_ID, RP_REDIRECT_URI, RP_RESPONSE_TYPE, RP_REQUESTED_SCOPES, RP_CLIENT_SECRET, RP_SIGNATURE_VERIFICATION_ALGORITHM, + OP_NAME, OP_AUTHORIZATION_ENDPOINT, OP_TOKEN_ENDPOINT, OP_USERINFO_ENDPOINT, OP_ISSUER, OP_JWKSET_URL); set.addAll(DelegatedAuthorizationSettings.getSettings(TYPE)); set.addAll(RealmSettings.getStandardSettings(TYPE)); + set.addAll(SSLConfigurationSettings.getRealmSettings(TYPE)); + set.addAll(PRINCIPAL_CLAIM.settings()); + set.addAll(GROUPS_CLAIM.settings()); + set.addAll(DN_CLAIM.settings()); + set.addAll(NAME_CLAIM.settings()); + set.addAll(MAIL_CLAIM.settings()); return set; } + + + /** + * The OIDC realm offers a number of settings that rely on claim values that are populated by the OP in the ID Token or the User Info + * response. + * Each claim has 2 settings: + *
    + *
  • The name of the OpenID Connect claim to use
  • + *
  • An optional java pattern (regex) to apply to that claim value in order to extract the substring that should be used.
  • + *
+ * For example, the Elasticsearch User Principal could be configured to come from the OpenID Connect standard claim "email", + * and extract only the local-port of the user's email address (i.e. the name before the '@'). + * This class encapsulates those 2 settings. + */ + public static final class ClaimSetting { + public static final String CLAIMS_PREFIX = "claims."; + public static final String CLAIM_PATTERNS_PREFIX = "claim_patterns."; + + private final Setting.AffixSetting claim; + private final Setting.AffixSetting pattern; + + public ClaimSetting(String name) { + claim = RealmSettings.simpleString(TYPE, CLAIMS_PREFIX + name, Setting.Property.NodeScope); + pattern = RealmSettings.simpleString(TYPE, CLAIM_PATTERNS_PREFIX + name, Setting.Property.NodeScope); + } + + public Collection> settings() { + return Arrays.asList(getClaim(), getPattern()); + } + + public String name(RealmConfig config) { + return getClaim().getConcreteSettingForNamespace(config.name()).getKey(); + } + + public Setting.AffixSetting getClaim() { + return claim; + } + + public Setting.AffixSetting getPattern() { + return pattern; + } + } } diff --git a/x-pack/plugin/security/build.gradle b/x-pack/plugin/security/build.gradle index afc39d5df5010..8e22bff50ac93 100644 --- a/x-pack/plugin/security/build.gradle +++ b/x-pack/plugin/security/build.gradle @@ -56,6 +56,16 @@ dependencies { compile "org.apache.httpcomponents:httpclient-cache:${versions.httpclient}" compile 'com.google.guava:guava:19.0' + // Dependencies for oidc + compile "com.nimbusds:oauth2-oidc-sdk:6.5" + compile "com.nimbusds:nimbus-jose-jwt:4.41.2" + compile "com.nimbusds:lang-tag:1.4.4" + compile "com.sun.mail:javax.mail:1.6.2" + compile "net.jcip:jcip-annotations:1.0" + compile "net.minidev:json-smart:2.3" + compile "net.minidev:accessors-smart:1.2" + + testCompile 'org.elasticsearch:securemock:1.2' testCompile "org.elasticsearch:mocksocket:${versions.mocksocket}" //testCompile "org.yaml:snakeyaml:${versions.snakeyaml}" diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java index 6d1087e1b95ee..d8ce9316c117d 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java @@ -113,7 +113,7 @@ public static Map getFactories(ThreadPool threadPool, Res map.put(PkiRealmSettings.TYPE, config -> new PkiRealm(config, resourceWatcherService, nativeRoleMappingStore)); map.put(SamlRealmSettings.TYPE, config -> SamlRealm.create(config, sslService, resourceWatcherService, nativeRoleMappingStore)); map.put(KerberosRealmSettings.TYPE, config -> new KerberosRealm(config, nativeRoleMappingStore, threadPool)); - map.put(OpenIdConnectRealmSettings.TYPE, config -> new OpenIdConnectRealm(config)); + map.put(OpenIdConnectRealmSettings.TYPE, config -> new OpenIdConnectRealm(config, sslService, nativeRoleMappingStore)); return Collections.unmodifiableMap(map); } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java new file mode 100644 index 0000000000000..083e480ca172d --- /dev/null +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java @@ -0,0 +1,213 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.security.authc.oidc; + +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.util.DefaultResourceRetriever; +import com.nimbusds.jose.util.Resource; +import com.nimbusds.jwt.JWT; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.oauth2.sdk.AuthorizationCode; +import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; +import com.nimbusds.oauth2.sdk.AuthorizationGrant; +import com.nimbusds.oauth2.sdk.ErrorObject; +import com.nimbusds.oauth2.sdk.ParseException; +import com.nimbusds.oauth2.sdk.TokenErrorResponse; +import com.nimbusds.oauth2.sdk.TokenRequest; +import com.nimbusds.oauth2.sdk.TokenResponse; +import com.nimbusds.oauth2.sdk.auth.ClientAuthentication; +import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic; +import com.nimbusds.oauth2.sdk.auth.Secret; +import com.nimbusds.oauth2.sdk.http.HTTPRequest; +import com.nimbusds.oauth2.sdk.http.HTTPResponse; +import com.nimbusds.oauth2.sdk.id.State; +import com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse; +import com.nimbusds.openid.connect.sdk.AuthenticationResponse; +import com.nimbusds.openid.connect.sdk.AuthenticationResponseParser; +import com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse; +import com.nimbusds.openid.connect.sdk.Nonce; +import com.nimbusds.openid.connect.sdk.OIDCTokenResponse; +import com.nimbusds.openid.connect.sdk.OIDCTokenResponseParser; +import com.nimbusds.openid.connect.sdk.validators.IDTokenValidator; +import org.apache.http.conn.ssl.DefaultHostnameVerifier; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.elasticsearch.ElasticsearchSecurityException; +import org.elasticsearch.SpecialPermission; +import org.elasticsearch.xpack.core.security.authc.RealmConfig; +import org.elasticsearch.xpack.core.security.authc.RealmSettings; +import org.elasticsearch.xpack.core.ssl.SSLConfiguration; +import org.elasticsearch.xpack.core.ssl.SSLService; + +import javax.net.ssl.HostnameVerifier; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; + +/** + * Handles an OpenID Connect Authentication response as received by the facilitator. In the case of an implicit flow, validates + * the ID Token and extracts the elasticsearch user properties from it. In the case of an authorization code flow, it first + * exchanges the code in the authentication response for an ID Token at the token endpoint of the OpenID Connect Provider. + */ +public class OpenIdConnectAuthenticator { + + private final RealmConfig realmConfig; + private final OpenIdConnectProviderConfiguration opConfig; + private final RelyingPartyConfiguration rpConfig; + private final SSLService sslService; + + protected final Logger logger = LogManager.getLogger(getClass()); + + OpenIdConnectAuthenticator(RealmConfig realmConfig, OpenIdConnectProviderConfiguration opConfig, RelyingPartyConfiguration rpConfig, + SSLService sslService) { + this.realmConfig = realmConfig; + this.opConfig = opConfig; + this.rpConfig = rpConfig; + this.sslService = sslService; + } + + public JWTClaimsSet authenticate(OpenIdConnectToken token) { + try { + AuthenticationResponse authenticationResponse = AuthenticationResponseParser.parse(new URI(token.getRedirectUrl())); + Nonce expectedNonce = new Nonce(token.getNonce()); + State expectedState = new State(token.getState()); + if (logger.isTraceEnabled()) { + logger.trace("OpenID Connect Provider redirected user to [{}]. Expected Nonce is [{}] and expected State is [{}]", + token.getRedirectUrl(), expectedNonce, expectedState); + } + if (authenticationResponse instanceof AuthenticationErrorResponse) { + ErrorObject error = ((AuthenticationErrorResponse) authenticationResponse).getErrorObject(); + throw new ElasticsearchSecurityException("OpenID Connect Provider response indicates authentication failure." + + "Code=[{}], Description=[{}]", error.getCode(), error.getDescription()); + } + final AuthenticationSuccessResponse response = authenticationResponse.toSuccessResponse(); + validateState(expectedState, response.getState()); + validateResponseType(response); + JWT idToken; + if (rpConfig.getResponseType().impliesCodeFlow()) { + final AuthorizationCode code = response.getAuthorizationCode(); + idToken = exchangeCodeForToken(code); + } else { + idToken = response.getIDToken(); + } + + return validateAndParseIdToken(idToken, expectedNonce); + + } catch (URISyntaxException | ParseException e) { + logger.debug("Failed to parse the response that was sent to the redirect_uri", e); + throw new ElasticsearchSecurityException("Failed to parse the response that was sent to the redirect_uri"); + } + } + + private JWTClaimsSet validateAndParseIdToken(JWT idToken, Nonce expectedNonce) { + Secret clientSecret = null; + try { + final IDTokenValidator validator; + final JWSAlgorithm requestedAlgorithm = rpConfig.getSignatureVerificationAlgorithm(); + if (JWSAlgorithm.Family.HMAC_SHA.contains(requestedAlgorithm)) { + clientSecret = new Secret(rpConfig.getClientSecret().toString()); + validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, clientSecret); + } else { + validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, + opConfig.getJwkSetUrl(), new PrivilegedResourceRetriever()); + } + JWTClaimsSet verifiedIdTokenClaims = validator.validate(idToken, expectedNonce).toJWTClaimsSet(); + if (logger.isTraceEnabled()) { + logger.trace("Received the Id Token for the user: [{}]", verifiedIdTokenClaims); + } + return verifiedIdTokenClaims; + + } catch (Exception e) { + logger.debug("Failed to parse or validate the ID Token. ", e); + throw new ElasticsearchSecurityException("Failed to parse or validate the ID Token"); + } finally { + if (null != clientSecret) { + clientSecret.erase(); + } + } + } + + private void validateResponseType(AuthenticationSuccessResponse response) { + if (rpConfig.getResponseType().equals(response.impliedResponseType()) == false) { + logger.debug("Unexpected response type [{}], while [{}] is configured", response.impliedResponseType(), + rpConfig.getResponseType()); + throw new ElasticsearchSecurityException("Received a response with an unexpected response type"); + } + } + + private void validateState(State expectedState, State state) { + if (state.equals(expectedState) == false) { + logger.debug("Invalid state parameter [{}], while [{}] was expected", state, expectedState); + throw new ElasticsearchSecurityException("Received a response with an invalid state parameter"); + } + } + + private JWT exchangeCodeForToken(AuthorizationCode code) { + Secret clientSecret = null; + try { + clientSecret = new Secret(rpConfig.getClientSecret().toString()); + final ClientAuthentication clientAuth = new ClientSecretBasic(rpConfig.getClientId(), clientSecret); + final AuthorizationGrant codeGrant = new AuthorizationCodeGrant(code, rpConfig.getRedirectUri()); + final TokenRequest request = new TokenRequest(opConfig.getTokenEndpoint(), clientAuth, codeGrant); + + final String sslKey = RealmSettings.realmSslPrefix(realmConfig.identifier()); + final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration(sslKey); + boolean isHostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); + final HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; + final HTTPRequest httpRequest = request.toHTTPRequest(); + httpRequest.setSSLSocketFactory(sslService.sslSocketFactory(sslConfiguration)); + httpRequest.setHostnameVerifier(verifier); + + SpecialPermission.check(); + final HTTPResponse httpResponse = + AccessController.doPrivileged((PrivilegedExceptionAction) httpRequest::send); + + final TokenResponse tokenResponse = OIDCTokenResponseParser.parse(httpResponse); + if (tokenResponse.indicatesSuccess() == false) { + TokenErrorResponse errorResponse = (TokenErrorResponse) tokenResponse; + throw new ElasticsearchSecurityException("Failed to exchange code for Id Token. Code=[{}], Description=[{}]", + errorResponse.getErrorObject().getCode(), errorResponse.getErrorObject().getDescription()); + } + OIDCTokenResponse successResponse = (OIDCTokenResponse) tokenResponse.toSuccessResponse(); + if (logger.isTraceEnabled()) { + logger.trace("Successfully exchanged code for ID Token: [{}]", successResponse.toJSONObject().toJSONString()); + } + + return successResponse.getOIDCTokens().getIDToken(); + } catch (Exception e) { + logger.debug("Failed to exchange code for Id Token using the Token Endpoint. ", e); + throw new ElasticsearchSecurityException("Failed to exchange code for Id Token."); + } finally { + if (null != clientSecret) { + clientSecret.erase(); + } + } + } + + private static final class PrivilegedResourceRetriever extends DefaultResourceRetriever { + + PrivilegedResourceRetriever() { + super(); + } + + @Override + public Resource retrieveResource(final URL url) throws IOException { + try { + return AccessController.doPrivileged( + (PrivilegedExceptionAction) () -> PrivilegedResourceRetriever.super.retrieveResource(url)); + } catch (final PrivilegedActionException e) { + throw (IOException) e.getCause(); + } + + } + + } +} diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectProviderConfiguration.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectProviderConfiguration.java index 0bfab29e626f2..635d962a92c37 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectProviderConfiguration.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectProviderConfiguration.java @@ -5,8 +5,11 @@ */ package org.elasticsearch.xpack.security.authc.oidc; +import com.nimbusds.oauth2.sdk.id.Issuer; import org.elasticsearch.common.Nullable; +import java.net.URI; +import java.net.URL; import java.util.Objects; /** @@ -14,37 +17,43 @@ */ public class OpenIdConnectProviderConfiguration { private final String providerName; - private final String authorizationEndpoint; - private final String tokenEndpoint; - private final String userinfoEndpoint; - private final String issuer; - - public OpenIdConnectProviderConfiguration(String providerName, String issuer, String authorizationEndpoint, - @Nullable String tokenEndpoint, @Nullable String userinfoEndpoint) { + private final URI authorizationEndpoint; + private final URI tokenEndpoint; + private final URI userinfoEndpoint; + private final Issuer issuer; + private final URL jwkSetUrl; + + public OpenIdConnectProviderConfiguration(String providerName, Issuer issuer, URL jwkSetUrl, URI authorizationEndpoint, + URI tokenEndpoint, @Nullable URI userinfoEndpoint) { this.providerName = Objects.requireNonNull(providerName, "OP Name must be provided"); this.authorizationEndpoint = Objects.requireNonNull(authorizationEndpoint, "Authorization Endpoint must be provided"); - this.tokenEndpoint = tokenEndpoint; + this.tokenEndpoint = Objects.requireNonNull(tokenEndpoint, "Token Endpoint must be provided"); this.userinfoEndpoint = userinfoEndpoint; this.issuer = Objects.requireNonNull(issuer, "OP Issuer must be provided"); + this.jwkSetUrl = Objects.requireNonNull(jwkSetUrl, "jwkSetUrl must be provided"); } public String getProviderName() { return providerName; } - public String getAuthorizationEndpoint() { + public URI getAuthorizationEndpoint() { return authorizationEndpoint; } - public String getTokenEndpoint() { + public URI getTokenEndpoint() { return tokenEndpoint; } - public String getUserinfoEndpoint() { + public URI getUserinfoEndpoint() { return userinfoEndpoint; } - public String getIssuer() { + public Issuer getIssuer() { return issuer; } + + public URL getJwkSetUrl() { + return jwkSetUrl; + } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index 0e6c35456cf9a..18c36472eeaba 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -5,9 +5,21 @@ */ package org.elasticsearch.xpack.security.authc.oidc; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jwt.JWTClaimsSet; + +import com.nimbusds.oauth2.sdk.ResponseType; +import com.nimbusds.oauth2.sdk.Scope; +import com.nimbusds.oauth2.sdk.id.ClientID; +import com.nimbusds.oauth2.sdk.id.Issuer; +import com.nimbusds.oauth2.sdk.id.State; +import com.nimbusds.openid.connect.sdk.AuthenticationRequest; +import com.nimbusds.openid.connect.sdk.Nonce; +import org.apache.logging.log4j.Logger; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.Strings; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.SettingsException; import org.elasticsearch.common.util.concurrent.ThreadContext; @@ -17,41 +29,93 @@ import org.elasticsearch.xpack.core.security.authc.Realm; import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.RealmSettings; +import org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings; import org.elasticsearch.xpack.core.security.user.User; +import org.elasticsearch.xpack.core.ssl.SSLService; +import org.elasticsearch.xpack.security.authc.support.UserRoleMapper; +import org.elasticsearch.xpack.security.authc.support.mapper.NativeRoleMappingStore; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.security.SecureRandom; -import java.util.Base64; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.DN_CLAIM; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.GROUPS_CLAIM; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.MAIL_CLAIM; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.NAME_CLAIM; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_ISSUER; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_JWKSET_URL; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_NAME; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_USERINFO_ENDPOINT; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.POPULATE_USER_METADATA; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.PRINCIPAL_CLAIM; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_CLIENT_ID; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_CLIENT_SECRET; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_REDIRECT_URI; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_RESPONSE_TYPE; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_SIGNATURE_VERIFICATION_ALGORITHM; public class OpenIdConnectRealm extends Realm { public static final String CONTEXT_TOKEN_DATA = "_oidc_tokendata"; - private static final SecureRandom RANDOM_INSTANCE = new SecureRandom(); private final OpenIdConnectProviderConfiguration opConfiguration; private final RelyingPartyConfiguration rpConfiguration; + private final OpenIdConnectAuthenticator openIdConnectAuthenticator; + private final ClaimParser principalAttribute; + private final ClaimParser groupsAttribute; + private final ClaimParser dnAttribute; + private final ClaimParser nameAttribute; + private final ClaimParser mailAttribute; + private final Boolean populateUserMetadata; + private final UserRoleMapper roleMapper; + + + public OpenIdConnectRealm(RealmConfig config, SSLService sslService, NativeRoleMappingStore roleMapper) { + super(config); + this.roleMapper = roleMapper; + this.rpConfiguration = buildRelyingPartyConfiguration(config); + this.opConfiguration = buildOpenIdConnectProviderConfiguration(config); + this.openIdConnectAuthenticator = new OpenIdConnectAuthenticator(config, opConfiguration, rpConfiguration, sslService); + this.principalAttribute = ClaimParser.forSetting(logger, PRINCIPAL_CLAIM, config, true); + this.groupsAttribute = ClaimParser.forSetting(logger, GROUPS_CLAIM, config, false); + this.dnAttribute = ClaimParser.forSetting(logger, DN_CLAIM, config, false); + this.nameAttribute = ClaimParser.forSetting(logger, NAME_CLAIM, config, false); + this.mailAttribute = ClaimParser.forSetting(logger, MAIL_CLAIM, config, false); + this.populateUserMetadata = config.getSetting(POPULATE_USER_METADATA); + } - public OpenIdConnectRealm(RealmConfig config) { + OpenIdConnectRealm(RealmConfig config) { super(config); + this.roleMapper = null; this.rpConfiguration = buildRelyingPartyConfiguration(config); this.opConfiguration = buildOpenIdConnectProviderConfiguration(config); + this.openIdConnectAuthenticator = new OpenIdConnectAuthenticator(config, opConfiguration, rpConfiguration, null); + this.principalAttribute = ClaimParser.forSetting(logger, PRINCIPAL_CLAIM, config, true); + this.groupsAttribute = ClaimParser.forSetting(logger, GROUPS_CLAIM, config, false); + this.dnAttribute = ClaimParser.forSetting(logger, DN_CLAIM, config, false); + this.nameAttribute = ClaimParser.forSetting(logger, NAME_CLAIM, config, false); + this.mailAttribute = ClaimParser.forSetting(logger, MAIL_CLAIM, config, false); + this.populateUserMetadata = config.getSetting(POPULATE_USER_METADATA); } @Override public boolean supports(AuthenticationToken token) { - return false; + return token instanceof OpenIdConnectToken; } @Override @@ -61,38 +125,114 @@ public AuthenticationToken token(ThreadContext context) { @Override public void authenticate(AuthenticationToken token, ActionListener listener) { + if (token instanceof OpenIdConnectToken) { + OpenIdConnectToken oidcToken = (OpenIdConnectToken) token; + JWTClaimsSet claims = openIdConnectAuthenticator.authenticate(oidcToken); + buildUserFromClaims(claims, listener); + } else { + listener.onResponse(AuthenticationResult.notHandled()); + } } @Override public void lookupUser(String username, ActionListener listener) { + listener.onResponse(null); + } + + + private void buildUserFromClaims(JWTClaimsSet claims, ActionListener authResultListener) { + final String principal = principalAttribute.getClaimValue(claims); + if (Strings.isNullOrEmpty(principal)) { + authResultListener.onResponse(AuthenticationResult.unsuccessful( + principalAttribute + "not found in " + claims.toJSONObject(), null)); + return; + } + final Map userMetadata = new HashMap<>(); + if (populateUserMetadata) { + Map claimsMap = claims.getClaims(); + /* + * We whitelist the Types that we want to parse as metadata from the Claims, explicitly filtering out {@link Date}s + */ + Set allowedEntries = claimsMap.entrySet().stream().filter(entry -> { + Object v = entry.getValue(); + return (v instanceof String || v instanceof Boolean || v instanceof Number || v instanceof Collections); + }).collect(Collectors.toSet()); + for (Map.Entry entry : allowedEntries) { + userMetadata.put("oidc(" + entry.getKey() + ")", entry.getValue()); + } + } + final List groups = groupsAttribute.getClaimValues(claims); + final String dn = dnAttribute.getClaimValue(claims); + final String mail = mailAttribute.getClaimValue(claims); + final String name = nameAttribute.getClaimValue(claims); + UserRoleMapper.UserData userData = new UserRoleMapper.UserData(principal, dn, groups, userMetadata, config); + roleMapper.resolveRoles(userData, ActionListener.wrap(roles -> { + final User user = new User(principal, roles.toArray(new String[0]), name, mail, userMetadata, true); + authResultListener.onResponse(AuthenticationResult.success(user)); + }, authResultListener::onFailure)); } + private RelyingPartyConfiguration buildRelyingPartyConfiguration(RealmConfig config) { - String redirectUri = require(config, RP_REDIRECT_URI); - String clientId = require(config, RP_CLIENT_ID); - String responseType = require(config, RP_RESPONSE_TYPE); - if (responseType.equals("id_token") == false && responseType.equals("code") == false) { - throw new SettingsException("The configuration setting [" + RealmSettings.getFullSettingKey(config, RP_RESPONSE_TYPE) - + "] value can only be code or id_token"); + final String redirectUriString = require(config, RP_REDIRECT_URI); + final URI redirectUri; + try { + redirectUri = new URI(redirectUriString); + } catch (URISyntaxException e) { + // This should never happen as it's already validated in the settings + throw new SettingsException("Invalid URI:" + RP_REDIRECT_URI.getKey(), e); } - List requestedScopes = config.getSetting(RP_REQUESTED_SCOPES); + final ClientID clientId = new ClientID(require(config, RP_CLIENT_ID)); + final SecureString clientSecret = config.getSetting(RP_CLIENT_SECRET); + final ResponseType responseType = new ResponseType(require(config, RP_RESPONSE_TYPE)); + final Scope requestedScope = new Scope(config.getSetting(RP_REQUESTED_SCOPES).toArray(new String[0])); + final JWSAlgorithm signatureVerificationAlgorithm = JWSAlgorithm.parse(require(config, RP_SIGNATURE_VERIFICATION_ALGORITHM)); - return new RelyingPartyConfiguration(clientId, redirectUri, responseType, requestedScopes); + return new RelyingPartyConfiguration(clientId, clientSecret, redirectUri, responseType, requestedScope, + signatureVerificationAlgorithm); } private OpenIdConnectProviderConfiguration buildOpenIdConnectProviderConfiguration(RealmConfig config) { String providerName = require(config, OP_NAME); - String authorizationEndpoint = require(config, OP_AUTHORIZATION_ENDPOINT); - String issuer = require(config, OP_ISSUER); - String tokenEndpoint = config.getSetting(OP_TOKEN_ENDPOINT, () -> null); - String userinfoEndpoint = config.getSetting(OP_USERINFO_ENDPOINT, () -> null); + Issuer issuer = new Issuer(require(config, OP_ISSUER)); + URL jwkSetUrl; + try { + jwkSetUrl = new URL(require(config, OP_JWKSET_URL)); + } catch (MalformedURLException e) { + // This should never happen as it's already validated in the settings + throw new SettingsException("Invalid URL: " + OP_JWKSET_URL.getKey(), e); + } + URI authorizationEndpoint; + try { + authorizationEndpoint = new URI(require(config, OP_AUTHORIZATION_ENDPOINT)); + } catch (URISyntaxException e) { + // This should never happen as it's already validated in the settings + throw new SettingsException("Invalid URI: " + OP_AUTHORIZATION_ENDPOINT.getKey(), e); + } + URI tokenEndpoint; + try { + tokenEndpoint = new URI(require(config, OP_TOKEN_ENDPOINT)); + } catch (URISyntaxException e) { + // This should never happen as it's already validated in the settings + throw new SettingsException("Invalid URL: " + OP_TOKEN_ENDPOINT.getKey(), e); + } + URI userinfoEndpoint; + try { + userinfoEndpoint = (config.getSetting(OP_USERINFO_ENDPOINT, () -> null) == null) ? null : + new URI(config.getSetting(OP_USERINFO_ENDPOINT, () -> null)); + } catch (URISyntaxException e) { + // This should never happen as it's already validated in the settings + throw new SettingsException("Invalid URI: " + OP_USERINFO_ENDPOINT.getKey(), e); + } + - return new OpenIdConnectProviderConfiguration(providerName, issuer, authorizationEndpoint, tokenEndpoint, userinfoEndpoint); + return new OpenIdConnectProviderConfiguration(providerName, issuer, jwkSetUrl, authorizationEndpoint, tokenEndpoint, + userinfoEndpoint); } - static String require(RealmConfig config, Setting.AffixSetting setting) { + private static String require(RealmConfig config, Setting.AffixSetting setting) { final String value = config.getSetting(setting); if (value.isEmpty()) { throw new SettingsException("The configuration setting [" + RealmSettings.getFullSettingKey(config, setting) @@ -109,46 +249,115 @@ static String require(RealmConfig config, Setting.AffixSetting setting) * @return an {@link OpenIdConnectPrepareAuthenticationResponse} */ public OpenIdConnectPrepareAuthenticationResponse buildAuthenticationRequestUri() throws ElasticsearchException { - try { - final String state = createNonceValue(); - final String nonce = createNonceValue(); - StringBuilder builder = new StringBuilder(); - builder.append(opConfiguration.getAuthorizationEndpoint()); - addParameter(builder, "response_type", rpConfiguration.getResponseType(), true); - addParameter(builder, "scope", Strings.collectionToDelimitedString(rpConfiguration.getRequestedScopes(), " ")); - addParameter(builder, "client_id", rpConfiguration.getClientId()); - addParameter(builder, "state", state); - if (Strings.hasText(nonce)) { - addParameter(builder, "nonce", nonce); + final State state = new State(); + final Nonce nonce = new Nonce(); + final AuthenticationRequest authenticationRequest = new AuthenticationRequest( + opConfiguration.getAuthorizationEndpoint(), + rpConfiguration.getResponseType(), + rpConfiguration.getRequestedScope(), + rpConfiguration.getClientId(), + rpConfiguration.getRedirectUri(), + state, + nonce); + + return new OpenIdConnectPrepareAuthenticationResponse(authenticationRequest.toURI().toString(), + state.getValue(), nonce.getValue()); + } + + static final class ClaimParser { + private final String name; + private final Function> parser; + + ClaimParser(String name, Function> parser) { + this.name = name; + this.parser = parser; + } + + List getClaimValues(JWTClaimsSet claims) { + return parser.apply(claims); + } + + String getClaimValue(JWTClaimsSet claims) { + List claimValues = parser.apply(claims); + if (claimValues == null || claimValues.isEmpty()) { + return null; + } else { + return claimValues.get(0); } - addParameter(builder, "redirect_uri", rpConfiguration.getRedirectUri()); - return new OpenIdConnectPrepareAuthenticationResponse(builder.toString(), state, nonce); - } catch (UnsupportedEncodingException e) { - throw new ElasticsearchException("Cannot build OpenID Connect Authentication Request", e); } - } - private void addParameter(StringBuilder builder, String parameter, String value, boolean isFirstParameter) - throws UnsupportedEncodingException { - char prefix = isFirstParameter ? '?' : '&'; - builder.append(prefix).append(parameter).append("="); - builder.append(URLEncoder.encode(value, StandardCharsets.UTF_8.name())); - } + @Override + public String toString() { + return name; + } - private void addParameter(StringBuilder builder, String parameter, String value) throws UnsupportedEncodingException { - addParameter(builder, parameter, value, false); - } + static ClaimParser forSetting(Logger logger, OpenIdConnectRealmSettings.ClaimSetting setting, RealmConfig realmConfig, + boolean required) { - /** - * Creates a cryptographically secure alphanumeric string to be used as a nonce or state. It adheres to the - * specification's requirements by using 180 bits for the random value. - * The random string is encoded in a URL safe manner. - * - * @return an alphanumeric string - */ - private static String createNonceValue() { - final byte[] randomBytes = new byte[20]; - RANDOM_INSTANCE.nextBytes(randomBytes); - return Base64.getUrlEncoder().withoutPadding().encodeToString(randomBytes); + if (realmConfig.hasSetting(setting.getClaim())) { + String claimName = realmConfig.getSetting(setting.getClaim()); + if (realmConfig.hasSetting(setting.getPattern())) { + Pattern regex = Pattern.compile(realmConfig.getSetting(setting.getPattern())); + return new ClaimParser( + "OpenID Connect Claim [" + claimName + "] with pattern [" + regex.pattern() + "] for [" + + setting.name(realmConfig) + "]", + claims -> { + Object claimValueObject = claims.getClaim(claimName); + List values; + if (claimValueObject == null) { + values = Collections.emptyList(); + } else if (claimValueObject instanceof String) { + values = Collections.singletonList((String) claimValueObject); + } else if (claimValueObject instanceof List == false) { + throw new SettingsException("Setting [" + RealmSettings.getFullSettingKey(realmConfig, setting.getClaim()) + + " expects a claim with String or a String Array value but found a " + claimValueObject.getClass().getName()); + } else { + values = (List) claimValueObject; + } + return values.stream().map(s -> { + final Matcher matcher = regex.matcher(s); + if (matcher.find() == false) { + logger.debug("OpenID Connect Claim [{}] is [{}], which does not match [{}]", claimName, s, regex.pattern()); + return null; + } + final String value = matcher.group(1); + if (Strings.isNullOrEmpty(value)) { + logger.debug("OpenID Connect Claim [{}] is [{}], which does match [{}] but group(1) is empty", + claimName, s, regex.pattern()); + return null; + } + return value; + }).filter(Objects::nonNull).collect(Collectors.toList()); + }); + } else { + return new ClaimParser( + "OpenID Connect Claim [" + claimName + "] for [" + setting.name(realmConfig) + "]", + claims -> { + Object claimValueObject = claims.getClaim(claimName); + if (claimValueObject == null) { + return Collections.emptyList(); + } else if (claimValueObject instanceof String) { + return Collections.singletonList((String) claimValueObject); + } else if (claimValueObject instanceof List == false) { + throw new SettingsException("Setting [" + RealmSettings.getFullSettingKey(realmConfig, setting.getClaim()) + + " expects a claim with String or a String Array value but found a " + claimValueObject.getClass().getName()); + } + return (List) claimValueObject; + }); + } + } else if (required) { + throw new SettingsException("Setting [" + RealmSettings.getFullSettingKey(realmConfig, setting.getClaim()) + + "] is required"); + } else if (realmConfig.hasSetting(setting.getPattern())) { + throw new SettingsException("Setting [" + RealmSettings.getFullSettingKey(realmConfig, setting.getPattern()) + + "] cannot be set unless [" + RealmSettings.getFullSettingKey(realmConfig, setting.getClaim()) + + "] is also set"); + } else { + return new ClaimParser("No OpenID Connect Claim for [" + setting.name(realmConfig) + "]", + attributes -> Collections.emptyList()); + } + } } + } + diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java index 9fa04090fec63..ac5a686a88249 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.xpack.security.authc.oidc; -import org.elasticsearch.common.Nullable; import org.elasticsearch.xpack.core.security.authc.AuthenticationToken; /** @@ -15,21 +14,21 @@ */ public class OpenIdConnectToken implements AuthenticationToken { - private String redirectUri; + private String redirectUrl; private String state; - @Nullable private String nonce; /** - * @param redirectUri The URI where the OP redirected the browser after the authentication event at the OP. This is passed as is from - * the facilitator entity (i.e. Kibana), so it is URL Encoded. + * @param redirectUrl The URI where the OP redirected the browser after the authentication event at the OP. This is passed as is from + * the facilitator entity (i.e. Kibana), so it is URL Encoded. It contains either the code or the id_token itself + * depending on the flow used * @param state The state value that we generated for this specific flow and should be stored at the user's session with the * facilitator. * @param nonce The nonce value that we generated for this specific flow and should be stored at the user's session with the * facilitator. */ - public OpenIdConnectToken(String redirectUri, String state, String nonce) { - this.redirectUri = redirectUri; + public OpenIdConnectToken(String redirectUrl, String state, String nonce) { + this.redirectUrl = redirectUrl; this.state = state; this.nonce = nonce; } @@ -41,12 +40,12 @@ public String principal() { @Override public Object credentials() { - return redirectUri; + return redirectUrl; } @Override public void clearCredentials() { - this.redirectUri = null; + this.redirectUrl = null; } public String getState() { @@ -57,7 +56,11 @@ public String getNonce() { return nonce; } + public String getRedirectUrl() { + return redirectUrl; + } + public String toString() { - return getClass().getSimpleName() + "{ redirectUri=" + redirectUri + ", state=" + state + ", nonce=" + nonce + "}"; + return getClass().getSimpleName() + "{ redirectUrl=" + redirectUrl + ", state=" + state + ", nonce=" + nonce + "}"; } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java index 516f787d0efeb..6e1cb35a6ad7e 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java @@ -5,38 +5,59 @@ */ package org.elasticsearch.xpack.security.authc.oidc; -import java.util.List; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.oauth2.sdk.ResponseType; +import com.nimbusds.oauth2.sdk.Scope; +import com.nimbusds.oauth2.sdk.auth.Secret; +import com.nimbusds.oauth2.sdk.id.ClientID; +import org.elasticsearch.common.settings.SecureString; + +import java.net.URI; import java.util.Objects; /** * A Class that contains all the OpenID Connect Relying Party configuration */ public class RelyingPartyConfiguration { - private final String clientId; - private final String redirectUri; - private final String responseType; - private final List requestedScopes; + private final ClientID clientId; + private final SecureString clientSecret; + private final URI redirectUri; + private final ResponseType responseType; + private final Scope requestedScope; + private final JWSAlgorithm signatureVerificationAlgorithm; - public RelyingPartyConfiguration(String clientId, String redirectUri, String responseType, List requestedScopes) { + public RelyingPartyConfiguration(ClientID clientId, SecureString clientSecret, URI redirectUri, ResponseType responseType, + Scope requestedScope, + JWSAlgorithm algorithm) { this.clientId = Objects.requireNonNull(clientId, "clientId must be provided"); + this.clientSecret = Objects.requireNonNull(clientSecret, "clientSecret must be provided"); this.redirectUri = Objects.requireNonNull(redirectUri, "redirectUri must be provided"); this.responseType = Objects.requireNonNull(responseType, "responseType must be provided"); - this.requestedScopes = Objects.requireNonNull(requestedScopes, "responseType must be provided"); + this.requestedScope = Objects.requireNonNull(requestedScope, "responseType must be provided"); + this.signatureVerificationAlgorithm = Objects.requireNonNull(algorithm, "algorithm must be provided"); } - public String getClientId() { + public ClientID getClientId() { return clientId; } - public String getRedirectUri() { + public SecureString getClientSecret() { + return clientSecret; + } + + public URI getRedirectUri() { return redirectUri; } - public String getResponseType() { + public ResponseType getResponseType() { return responseType; } - public List getRequestedScopes() { - return requestedScopes; + public Scope getRequestedScope() { + return requestedScope; + } + + public JWSAlgorithm getSignatureVerificationAlgorithm() { + return signatureVerificationAlgorithm; } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectAuthenticateAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectAuthenticateAction.java index d7130da64530a..2ac75872b7c8a 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectAuthenticateAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectAuthenticateAction.java @@ -55,7 +55,6 @@ protected RestChannelConsumer innerPrepareRequest(RestRequest request, NodeClien @Override public RestResponse buildResponse(OpenIdConnectAuthenticateResponse response, XContentBuilder builder) throws Exception { - builder.startObject(); builder.startObject() .field("username", response.getPrincipal()) .field("access_token", response.getAccessTokenString()) diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java index 1b8cbea8dde53..df0f85c223459 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java @@ -40,21 +40,26 @@ public void setupEnv() { public void testIncorrectResponseTypeThrowsError() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "hybrid"); - SettingsException exception = expectThrows(SettingsException.class, () -> { + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); }); - assertThat(exception.getMessage(), Matchers.containsString("value can only be code or id_token")); + assertThat(exception.getMessage(), Matchers.containsString("[xpack.security.authc.realms.oidc.oidc1-realm.rp.response_type]." + + " Allowed values are [code, id_token]")); } public void testMissingAuthorizationEndpointThrowsError() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -65,10 +70,94 @@ public void testMissingAuthorizationEndpointThrowsError() { Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT))); } + public void testInvalidAuthorizationEndpointThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "this is not a URI") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT))); + } + + public void testMissingTokenEndpointThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT))); + } + + public void testInvalidTokenEndpointThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "This is not a uri") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT))); + } + + public void testMissingJwksUrlThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL))); + } + + public void testInvalidJwksUrlThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "this is not a url") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "This is not a uri") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL))); + } + public void testMissingIssuerThrowsError() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -82,7 +171,9 @@ public void testMissingIssuerThrowsError() { public void testMissingNameTypeThrowsError() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -96,7 +187,9 @@ public void testMissingNameTypeThrowsError() { public void testMissingRedirectUriThrowsError() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -110,8 +203,10 @@ public void testMissingRedirectUriThrowsError() { public void testMissingClientIdThrowsError() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { @@ -124,8 +219,10 @@ public void testMissingClientIdThrowsError() { public void testBuilidingAuthenticationRequest() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") @@ -136,16 +233,18 @@ public void testBuilidingAuthenticationRequest() { final String state = response.getState(); final String nonce = response.getNonce(); assertThat(response.getAuthenticationRequestUrl(), - equalTo("https://op.example.com/login?response_type=code&scope=openid+scope1+scope2&client_id=rp-my&state=" + state - + "&nonce=" + nonce + "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb")); + equalTo("https://op.example.com/login?scope=openid+scope1+scope2&response_type=code" + + "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state=" + state + "&nonce=" + nonce + "&client_id=rp-my")); } public void testBuilidingAuthenticationRequestWithDefaultScope() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -153,8 +252,8 @@ public void testBuilidingAuthenticationRequestWithDefaultScope() { final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(); final String state = response.getState(); final String nonce = response.getNonce(); - assertThat(response.getAuthenticationRequestUrl(), equalTo("https://op.example.com/login?response_type=code&scope=openid" - + "&client_id=rp-my&state=" + state + "&nonce=" + nonce + "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb")); + assertThat(response.getAuthenticationRequestUrl(), equalTo("https://op.example.com/login?scope=openid&response_type=code" + + "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state=" + state + "&nonce=" + nonce + "&client_id=rp-my")); } private RealmConfig buildConfig(Settings realmSettings) { From 92f63ef26119c4f2b7b250286dded9a6ba6ebd20 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Wed, 23 Jan 2019 23:23:29 +0200 Subject: [PATCH 02/20] fix licenses and SHAs for introduced dependencies --- x-pack/plugin/security/build.gradle | 14 +- .../licenses/accessors-smart-1.2.jar.sha1 | 1 + .../licenses/accessors-smart-LICENSE.txt | 202 +++++ .../licenses/accessors-smart-NOTICE.txt | 0 .../licenses/javax.mail-1.6.2.jar.sha1 | 1 + .../security/licenses/javax.mail-LICENSE.txt | 759 ++++++++++++++++++ .../security/licenses/javax.mail-NOTICE.txt | 0 .../licenses/jcip-annotations-1.0.jar.sha1 | 1 + .../licenses/jcip-annotations-LICENSE.txt | 202 +++++ .../licenses/jcip-annotations-NOTICE.txt | 0 .../security/licenses/json-smart-2.3.jar.sha1 | 1 + .../security/licenses/json-smart-LICENSE.txt | 202 +++++ .../security/licenses/json-smart-NOTICE.txt | 0 .../security/licenses/lang-tag-1.4.4.jar.sha1 | 1 + .../security/licenses/lang-tag-LICENSE.txt | 202 +++++ .../security/licenses/lang-tag-NOTICE.txt | 14 + .../licenses/nimbus-jose-jwt-4.41.2.jar.sha1 | 1 + .../licenses/nimbus-jose-jwt-LICENSE.txt | 202 +++++ .../licenses/nimbus-jose-jwt-NOTICE.txt | 14 + .../licenses/oauth2-oidc-sdk-6.5.jar.sha1 | 1 + .../licenses/oauth2-oidc-sdk-LICENSE.txt | 202 +++++ .../licenses/oauth2-oidc-sdk-NOTICE.txt | 14 + 22 files changed, 2033 insertions(+), 1 deletion(-) create mode 100644 x-pack/plugin/security/licenses/accessors-smart-1.2.jar.sha1 create mode 100644 x-pack/plugin/security/licenses/accessors-smart-LICENSE.txt create mode 100644 x-pack/plugin/security/licenses/accessors-smart-NOTICE.txt create mode 100644 x-pack/plugin/security/licenses/javax.mail-1.6.2.jar.sha1 create mode 100644 x-pack/plugin/security/licenses/javax.mail-LICENSE.txt create mode 100644 x-pack/plugin/security/licenses/javax.mail-NOTICE.txt create mode 100644 x-pack/plugin/security/licenses/jcip-annotations-1.0.jar.sha1 create mode 100644 x-pack/plugin/security/licenses/jcip-annotations-LICENSE.txt create mode 100644 x-pack/plugin/security/licenses/jcip-annotations-NOTICE.txt create mode 100644 x-pack/plugin/security/licenses/json-smart-2.3.jar.sha1 create mode 100644 x-pack/plugin/security/licenses/json-smart-LICENSE.txt create mode 100644 x-pack/plugin/security/licenses/json-smart-NOTICE.txt create mode 100644 x-pack/plugin/security/licenses/lang-tag-1.4.4.jar.sha1 create mode 100644 x-pack/plugin/security/licenses/lang-tag-LICENSE.txt create mode 100644 x-pack/plugin/security/licenses/lang-tag-NOTICE.txt create mode 100644 x-pack/plugin/security/licenses/nimbus-jose-jwt-4.41.2.jar.sha1 create mode 100644 x-pack/plugin/security/licenses/nimbus-jose-jwt-LICENSE.txt create mode 100644 x-pack/plugin/security/licenses/nimbus-jose-jwt-NOTICE.txt create mode 100644 x-pack/plugin/security/licenses/oauth2-oidc-sdk-6.5.jar.sha1 create mode 100644 x-pack/plugin/security/licenses/oauth2-oidc-sdk-LICENSE.txt create mode 100644 x-pack/plugin/security/licenses/oauth2-oidc-sdk-NOTICE.txt diff --git a/x-pack/plugin/security/build.gradle b/x-pack/plugin/security/build.gradle index 8e22bff50ac93..4857a66560edd 100644 --- a/x-pack/plugin/security/build.gradle +++ b/x-pack/plugin/security/build.gradle @@ -267,7 +267,19 @@ thirdPartyAudit { 'net.sf.ehcache.Ehcache', 'net.sf.ehcache.Element', // [missing classes] SLF4j includes an optional class that depends on an extension class (!) - 'org.slf4j.ext.EventData' + 'org.slf4j.ext.EventData', + 'javax.activation.ActivationDataFlavor', + 'javax.activation.DataContentHandler', + 'javax.activation.DataHandler', + 'javax.activation.DataSource', + 'javax.activation.FileDataSource', + 'javax.activation.FileTypeMap', + 'org.cryptomator.siv.SivMode', + 'org.objectweb.asm.ClassWriter', + 'org.objectweb.asm.Label', + 'org.objectweb.asm.MethodVisitor', + 'org.objectweb.asm.Type' + ) ignoreViolations ( diff --git a/x-pack/plugin/security/licenses/accessors-smart-1.2.jar.sha1 b/x-pack/plugin/security/licenses/accessors-smart-1.2.jar.sha1 new file mode 100644 index 0000000000000..e8e174c88c7a4 --- /dev/null +++ b/x-pack/plugin/security/licenses/accessors-smart-1.2.jar.sha1 @@ -0,0 +1 @@ +c592b500269bfde36096641b01238a8350f8aa31 \ No newline at end of file diff --git a/x-pack/plugin/security/licenses/accessors-smart-LICENSE.txt b/x-pack/plugin/security/licenses/accessors-smart-LICENSE.txt new file mode 100644 index 0000000000000..d645695673349 --- /dev/null +++ b/x-pack/plugin/security/licenses/accessors-smart-LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/x-pack/plugin/security/licenses/accessors-smart-NOTICE.txt b/x-pack/plugin/security/licenses/accessors-smart-NOTICE.txt new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/x-pack/plugin/security/licenses/javax.mail-1.6.2.jar.sha1 b/x-pack/plugin/security/licenses/javax.mail-1.6.2.jar.sha1 new file mode 100644 index 0000000000000..1c865d47f57c9 --- /dev/null +++ b/x-pack/plugin/security/licenses/javax.mail-1.6.2.jar.sha1 @@ -0,0 +1 @@ +935151eb71beff17a2ffac15dd80184a99a0514f \ No newline at end of file diff --git a/x-pack/plugin/security/licenses/javax.mail-LICENSE.txt b/x-pack/plugin/security/licenses/javax.mail-LICENSE.txt new file mode 100644 index 0000000000000..5ad62c442b336 --- /dev/null +++ b/x-pack/plugin/security/licenses/javax.mail-LICENSE.txt @@ -0,0 +1,759 @@ +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.1 + +1. Definitions. + + 1.1. "Contributor" means each individual or entity that creates or + contributes to the creation of Modifications. + + 1.2. "Contributor Version" means the combination of the Original + Software, prior Modifications used by a Contributor (if any), and + the Modifications made by that particular Contributor. + + 1.3. "Covered Software" means (a) the Original Software, or (b) + Modifications, or (c) the combination of files containing Original + Software with files containing Modifications, in each case including + portions thereof. + + 1.4. "Executable" means the Covered Software in any form other than + Source Code. + + 1.5. "Initial Developer" means the individual or entity that first + makes Original Software available under this License. + + 1.6. "Larger Work" means a work which combines Covered Software or + portions thereof with code not governed by the terms of this License. + + 1.7. "License" means this document. + + 1.8. "Licensable" means having the right to grant, to the maximum + extent possible, whether at the time of the initial grant or + subsequently acquired, any and all of the rights conveyed herein. + + 1.9. "Modifications" means the Source Code and Executable form of + any of the following: + + A. Any file that results from an addition to, deletion from or + modification of the contents of a file containing Original Software + or previous Modifications; + + B. Any new file that contains any part of the Original Software or + previous Modification; or + + C. Any new file that is contributed or otherwise made available + under the terms of this License. + + 1.10. "Original Software" means the Source Code and Executable form + of computer software code that is originally released under this + License. + + 1.11. "Patent Claims" means any patent claim(s), now owned or + hereafter acquired, including without limitation, method, process, + and apparatus claims, in any patent Licensable by grantor. + + 1.12. "Source Code" means (a) the common form of computer software + code in which modifications are made and (b) associated + documentation included in or with such code. + + 1.13. "You" (or "Your") means an individual or a legal entity + exercising rights under, and complying with all of the terms of, + this License. For legal entities, "You" includes any entity which + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants. + + 2.1. The Initial Developer Grant. + + Conditioned upon Your compliance with Section 3.1 below and subject + to third party intellectual property claims, the Initial Developer + hereby grants You a world-wide, royalty-free, non-exclusive license: + + (a) under intellectual property rights (other than patent or + trademark) Licensable by Initial Developer, to use, reproduce, + modify, display, perform, sublicense and distribute the Original + Software (or portions thereof), with or without Modifications, + and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, using or selling of + Original Software, to make, have made, use, practice, sell, and + offer for sale, and/or otherwise dispose of the Original Software + (or portions thereof). + + (c) The licenses granted in Sections 2.1(a) and (b) are effective on + the date Initial Developer first distributes or otherwise makes the + Original Software available to a third party under the terms of this + License. + + (d) Notwithstanding Section 2.1(b) above, no patent license is + granted: (1) for code that You delete from the Original Software, or + (2) for infringements caused by: (i) the modification of the + Original Software, or (ii) the combination of the Original Software + with other software or devices. + + 2.2. Contributor Grant. + + Conditioned upon Your compliance with Section 3.1 below and subject + to third party intellectual property claims, each Contributor hereby + grants You a world-wide, royalty-free, non-exclusive license: + + (a) under intellectual property rights (other than patent or + trademark) Licensable by Contributor to use, reproduce, modify, + display, perform, sublicense and distribute the Modifications + created by such Contributor (or portions thereof), either on an + unmodified basis, with other Modifications, as Covered Software + and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, using, or selling + of Modifications made by that Contributor either alone and/or in + combination with its Contributor Version (or portions of such + combination), to make, use, sell, offer for sale, have made, and/or + otherwise dispose of: (1) Modifications made by that Contributor (or + portions thereof); and (2) the combination of Modifications made by + that Contributor with its Contributor Version (or portions of such + combination). + + (c) The licenses granted in Sections 2.2(a) and 2.2(b) are effective + on the date Contributor first distributes or otherwise makes the + Modifications available to a third party. + + (d) Notwithstanding Section 2.2(b) above, no patent license is + granted: (1) for any code that Contributor has deleted from the + Contributor Version; (2) for infringements caused by: (i) third + party modifications of Contributor Version, or (ii) the combination + of Modifications made by that Contributor with other software + (except as part of the Contributor Version) or other devices; or (3) + under Patent Claims infringed by Covered Software in the absence of + Modifications made by that Contributor. + +3. Distribution Obligations. + + 3.1. Availability of Source Code. + + Any Covered Software that You distribute or otherwise make available + in Executable form must also be made available in Source Code form + and that Source Code form must be distributed only under the terms + of this License. You must include a copy of this License with every + copy of the Source Code form of the Covered Software You distribute + or otherwise make available. You must inform recipients of any such + Covered Software in Executable form as to how they can obtain such + Covered Software in Source Code form in a reasonable manner on or + through a medium customarily used for software exchange. + + 3.2. Modifications. + + The Modifications that You create or to which You contribute are + governed by the terms of this License. You represent that You + believe Your Modifications are Your original creation(s) and/or You + have sufficient rights to grant the rights conveyed by this License. + + 3.3. Required Notices. + + You must include a notice in each of Your Modifications that + identifies You as the Contributor of the Modification. You may not + remove or alter any copyright, patent or trademark notices contained + within the Covered Software, or any notices of licensing or any + descriptive text giving attribution to any Contributor or the + Initial Developer. + + 3.4. Application of Additional Terms. + + You may not offer or impose any terms on any Covered Software in + Source Code form that alters or restricts the applicable version of + this License or the recipients' rights hereunder. You may choose to + offer, and to charge a fee for, warranty, support, indemnity or + liability obligations to one or more recipients of Covered Software. + However, you may do so only on Your own behalf, and not on behalf of + the Initial Developer or any Contributor. You must make it + absolutely clear that any such warranty, support, indemnity or + liability obligation is offered by You alone, and You hereby agree + to indemnify the Initial Developer and every Contributor for any + liability incurred by the Initial Developer or such Contributor as a + result of warranty, support, indemnity or liability terms You offer. + + 3.5. Distribution of Executable Versions. + + You may distribute the Executable form of the Covered Software under + the terms of this License or under the terms of a license of Your + choice, which may contain terms different from this License, + provided that You are in compliance with the terms of this License + and that the license for the Executable form does not attempt to + limit or alter the recipient's rights in the Source Code form from + the rights set forth in this License. If You distribute the Covered + Software in Executable form under a different license, You must make + it absolutely clear that any terms which differ from this License + are offered by You alone, not by the Initial Developer or + Contributor. You hereby agree to indemnify the Initial Developer and + every Contributor for any liability incurred by the Initial + Developer or such Contributor as a result of any such terms You offer. + + 3.6. Larger Works. + + You may create a Larger Work by combining Covered Software with + other code not governed by the terms of this License and distribute + the Larger Work as a single product. In such a case, You must make + sure the requirements of this License are fulfilled for the Covered + Software. + +4. Versions of the License. + + 4.1. New Versions. + + Oracle is the initial license steward and may publish revised and/or + new versions of this License from time to time. Each version will be + given a distinguishing version number. Except as provided in Section + 4.3, no one other than the license steward has the right to modify + this License. + + 4.2. Effect of New Versions. + + You may always continue to use, distribute or otherwise make the + Covered Software available under the terms of the version of the + License under which You originally received the Covered Software. If + the Initial Developer includes a notice in the Original Software + prohibiting it from being distributed or otherwise made available + under any subsequent version of the License, You must distribute and + make the Covered Software available under the terms of the version + of the License under which You originally received the Covered + Software. Otherwise, You may also choose to use, distribute or + otherwise make the Covered Software available under the terms of any + subsequent version of the License published by the license steward. + + 4.3. Modified Versions. + + When You are an Initial Developer and You want to create a new + license for Your Original Software, You may create and use a + modified version of this License if You: (a) rename the license and + remove any references to the name of the license steward (except to + note that the license differs from this License); and (b) otherwise + make it clear that the license contains terms which differ from this + License. + +5. DISCLAIMER OF WARRANTY. + + COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, + INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE + IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR + NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF + THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE + DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY + OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, + REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN + ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS + AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. + +6. TERMINATION. + + 6.1. This License and the rights granted hereunder will terminate + automatically if You fail to comply with terms herein and fail to + cure such breach within 30 days of becoming aware of the breach. + Provisions which, by their nature, must remain in effect beyond the + termination of this License shall survive. + + 6.2. If You assert a patent infringement claim (excluding + declaratory judgment actions) against Initial Developer or a + Contributor (the Initial Developer or Contributor against whom You + assert such claim is referred to as "Participant") alleging that the + Participant Software (meaning the Contributor Version where the + Participant is a Contributor or the Original Software where the + Participant is the Initial Developer) directly or indirectly + infringes any patent, then any and all rights granted directly or + indirectly to You by such Participant, the Initial Developer (if the + Initial Developer is not the Participant) and all Contributors under + Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice + from Participant terminate prospectively and automatically at the + expiration of such 60 day notice period, unless if within such 60 + day period You withdraw Your claim with respect to the Participant + Software against such Participant either unilaterally or pursuant to + a written agreement with Participant. + + 6.3. If You assert a patent infringement claim against Participant + alleging that the Participant Software directly or indirectly + infringes any patent where such claim is resolved (such as by + license or settlement) prior to the initiation of patent + infringement litigation, then the reasonable value of the licenses + granted by such Participant under Sections 2.1 or 2.2 shall be taken + into account in determining the amount or value of any payment or + license. + + 6.4. In the event of termination under Sections 6.1 or 6.2 above, + all end user licenses that have been validly granted by You or any + distributor hereunder prior to termination (excluding licenses + granted to You by any distributor) shall survive termination. + +7. LIMITATION OF LIABILITY. + + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT + (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE + INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF + COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE + TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT + LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER + FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR + LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE + POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT + APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH + PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH + LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR + LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION + AND LIMITATION MAY NOT APPLY TO YOU. + +8. U.S. GOVERNMENT END USERS. + + The Covered Software is a "commercial item," as that term is defined + in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer + software" (as that term is defined at 48 C.F.R. § + 252.227-7014(a)(1)) and "commercial computer software documentation" + as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent + with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 + (June 1995), all U.S. Government End Users acquire Covered Software + with only those rights set forth herein. This U.S. Government Rights + clause is in lieu of, and supersedes, any other FAR, DFAR, or other + clause or provision that addresses Government rights in computer + software under this License. + +9. MISCELLANEOUS. + + This License represents the complete agreement concerning subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. This License shall be governed by + the law of the jurisdiction specified in a notice contained within + the Original Software (except to the extent applicable law, if any, + provides otherwise), excluding such jurisdiction's conflict-of-law + provisions. Any litigation relating to this License shall be subject + to the jurisdiction of the courts located in the jurisdiction and + venue specified in a notice contained within the Original Software, + with the losing party responsible for costs, including, without + limitation, court costs and reasonable attorneys' fees and expenses. + The application of the United Nations Convention on Contracts for + the International Sale of Goods is expressly excluded. Any law or + regulation which provides that the language of a contract shall be + construed against the drafter shall not apply to this License. You + agree that You alone are responsible for compliance with the United + States export administration regulations (and the export control + laws and regulation of any other countries) when You use, distribute + or otherwise make available any Covered Software. + +10. RESPONSIBILITY FOR CLAIMS. + + As between Initial Developer and the Contributors, each party is + responsible for claims and damages arising, directly or indirectly, + out of its utilization of rights under this License and You agree to + work with Initial Developer and Contributors to distribute such + responsibility on an equitable basis. Nothing herein is intended or + shall be deemed to constitute any admission of liability. + +------------------------------------------------------------------------ + +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION +LICENSE (CDDL) + +The code released under the CDDL shall be governed by the laws of the +State of California (excluding conflict-of-law provisions). Any +litigation relating to this License shall be subject to the jurisdiction +of the Federal Courts of the Northern District of California and the +state courts of the State of California, with venue lying in Santa Clara +County, California. + + + + The GNU General Public License (GPL) Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor +Boston, MA 02110-1335 +USA + +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to +share and change it. By contrast, the GNU General Public License is +intended to guarantee your freedom to share and change free software--to +make sure the software is free for all its users. This General Public +License applies to most of the Free Software Foundation's software and +to any other program whose authors commit to using it. (Some other Free +Software Foundation software is covered by the GNU Library General +Public License instead.) You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. +Our General Public Licenses are designed to make sure that you have the +freedom to distribute copies of free software (and charge for this +service if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs; and that you know you can do these things. + +To protect your rights, we need to make restrictions that forbid anyone +to deny you these rights or to ask you to surrender the rights. These +restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis +or for a fee, you must give the recipients all the rights that you have. +You must make sure that they, too, receive or can get the source code. +And you must show them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + +Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + +Finally, any free program is threatened constantly by software patents. +We wish to avoid the danger that redistributors of a free program will +individually obtain patent licenses, in effect making the program +proprietary. To prevent this, we have made it clear that any patent must +be licensed for everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and +modification follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a +notice placed by the copyright holder saying it may be distributed under +the terms of this General Public License. The "Program", below, refers +to any such program or work, and a "work based on the Program" means +either the Program or any derivative work under copyright law: that is +to say, a work containing the Program or a portion of it, either +verbatim or with modifications and/or translated into another language. +(Hereinafter, translation is included without limitation in the term +"modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of running +the Program is not restricted, and the output from the Program is +covered only if its contents constitute a work based on the Program +(independent of having been made by running the Program). Whether that +is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source +code as you receive it, in any medium, provided that you conspicuously +and appropriately publish on each copy an appropriate copyright notice +and disclaimer of warranty; keep intact all the notices that refer to +this License and to the absence of any warranty; and give any other +recipients of the Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of +it, thus forming a work based on the Program, and copy and distribute +such modifications or work under the terms of Section 1 above, provided +that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any part + thereof, to be licensed as a whole at no charge to all third parties + under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a notice + that there is no warranty (or else, saying that you provide a + warranty) and that users may redistribute the program under these + conditions, and telling the user how to view a copy of this License. + (Exception: if the Program itself is interactive but does not + normally print such an announcement, your work based on the Program + is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, and +can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based on +the Program, the distribution of the whole must be on the terms of this +License, whose permissions for other licensees extend to the entire +whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of a +storage or distribution medium does not bring the other work under the +scope of this License. + +3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections 1 + and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your cost + of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer to + distribute corresponding source code. (This alternative is allowed + only for noncommercial distribution and only if you received the + program in object code or executable form with such an offer, in + accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source code +means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to control +compilation and installation of the executable. However, as a special +exception, the source code distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies the +executable. + +If distribution of executable or object code is made by offering access +to copy from a designated place, then offering equivalent access to copy +the source code from the same place counts as distribution of the source +code, even though third parties are not compelled to copy the source +along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt otherwise +to copy, modify, sublicense or distribute the Program is void, and will +automatically terminate your rights under this License. However, parties +who have received copies, or rights, from you under this License will +not have their licenses terminated so long as such parties remain in +full compliance. + +5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and all +its terms and conditions for copying, distributing or modifying the +Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further restrictions +on the recipients' exercise of the rights granted herein. You are not +responsible for enforcing compliance by third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot distribute +so as to satisfy simultaneously your obligations under this License and +any other pertinent obligations, then as a consequence you may not +distribute the Program at all. For example, if a patent license would +not permit royalty-free redistribution of the Program by all those who +receive copies directly or indirectly through you, then the only way you +could satisfy both it and this License would be to refrain entirely from +distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is implemented +by public license practices. Many people have made generous +contributions to the wide range of software distributed through that +system in reliance on consistent application of that system; it is up to +the author/donor to decide if he or she is willing to distribute +software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be +a consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License may +add an explicit geographical distribution limitation excluding those +countries, so that distribution is permitted only in or among countries +not thus excluded. In such case, this License incorporates the +limitation as if written in the body of this License. + +9. The Free Software Foundation may publish revised and/or new +versions of the General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Program does not specify a version +number of this License, you may choose any version ever published by the +Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the +author to ask for permission. For software which is copyrighted by the +Free Software Foundation, write to the Free Software Foundation; we +sometimes make exceptions for this. Our decision will be guided by the +two goals of preserving the free status of all derivatives of our free +software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, +EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE +ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH +YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL +NECESSARY SERVICING, REPAIR OR CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR +DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL +DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM +(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED +INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF +THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR +OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively convey +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + One line to give the program's name and a brief idea of what it does. + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type + `show w'. This is free software, and you are welcome to redistribute + it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the +appropriate parts of the General Public License. Of course, the commands +you use may be called something other than `show w' and `show c'; they +could even be mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + program `Gnomovision' (which makes passes at compilers) written by + James Hacker. + + signature of Ty Coon, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications +with the library. If this is what you want to do, use the GNU Library +General Public License instead of this License. + +# + +Certain source files distributed by Oracle America, Inc. and/or its +affiliates are subject to the following clarification and special +exception to the GPLv2, based on the GNU Project exception for its +Classpath libraries, known as the GNU Classpath Exception, but only +where Oracle has expressly included in the particular source file's +header the words "Oracle designates this particular file as subject to +the "Classpath" exception as provided by Oracle in the LICENSE file +that accompanied this code." + +You should also note that Oracle includes multiple, independent +programs in this software package. Some of those programs are provided +under licenses deemed incompatible with the GPLv2 by the Free Software +Foundation and others. For example, the package includes programs +licensed under the Apache License, Version 2.0. Such programs are +licensed to you under their original licenses. + +Oracle facilitates your further distribution of this package by adding +the Classpath Exception to the necessary parts of its GPLv2 code, which +permits you to use that code in combination with other independent +modules not licensed under the GPLv2. However, note that this would +not permit you to commingle code under an incompatible license with +Oracle's GPLv2 licensed code by, for example, cutting and pasting such +code into a file also containing Oracle's GPLv2 licensed code and then +distributing the result. Additionally, if you were to remove the +Classpath Exception from any of the files to which it applies and +distribute the result, you would likely be required to license some or +all of the other code in that distribution under the GPLv2 as well, and +since the GPLv2 is incompatible with the license terms of some items +included in the distribution by Oracle, removing the Classpath +Exception could therefore effectively compromise your ability to +further distribute the package. + +Proceed with caution and we recommend that you obtain the advice of a +lawyer skilled in open source matters before removing the Classpath +Exception or making modifications to this package which may +subsequently be redistributed and/or involve the use of third party +software. + +CLASSPATH EXCEPTION +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License version 2 cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from or +based on this library. If you modify this library, you may extend this +exception to your version of the library, but you are not obligated to +do so. If you do not wish to do so, delete this exception statement +from your version. diff --git a/x-pack/plugin/security/licenses/javax.mail-NOTICE.txt b/x-pack/plugin/security/licenses/javax.mail-NOTICE.txt new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/x-pack/plugin/security/licenses/jcip-annotations-1.0.jar.sha1 b/x-pack/plugin/security/licenses/jcip-annotations-1.0.jar.sha1 new file mode 100644 index 0000000000000..9eaed5270992b --- /dev/null +++ b/x-pack/plugin/security/licenses/jcip-annotations-1.0.jar.sha1 @@ -0,0 +1 @@ +afba4942caaeaf46aab0b976afd57cc7c181467e \ No newline at end of file diff --git a/x-pack/plugin/security/licenses/jcip-annotations-LICENSE.txt b/x-pack/plugin/security/licenses/jcip-annotations-LICENSE.txt new file mode 100644 index 0000000000000..d645695673349 --- /dev/null +++ b/x-pack/plugin/security/licenses/jcip-annotations-LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/x-pack/plugin/security/licenses/jcip-annotations-NOTICE.txt b/x-pack/plugin/security/licenses/jcip-annotations-NOTICE.txt new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/x-pack/plugin/security/licenses/json-smart-2.3.jar.sha1 b/x-pack/plugin/security/licenses/json-smart-2.3.jar.sha1 new file mode 100644 index 0000000000000..8c5c1588c150f --- /dev/null +++ b/x-pack/plugin/security/licenses/json-smart-2.3.jar.sha1 @@ -0,0 +1 @@ +007396407491352ce4fa30de92efb158adb76b5b \ No newline at end of file diff --git a/x-pack/plugin/security/licenses/json-smart-LICENSE.txt b/x-pack/plugin/security/licenses/json-smart-LICENSE.txt new file mode 100644 index 0000000000000..d645695673349 --- /dev/null +++ b/x-pack/plugin/security/licenses/json-smart-LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/x-pack/plugin/security/licenses/json-smart-NOTICE.txt b/x-pack/plugin/security/licenses/json-smart-NOTICE.txt new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/x-pack/plugin/security/licenses/lang-tag-1.4.4.jar.sha1 b/x-pack/plugin/security/licenses/lang-tag-1.4.4.jar.sha1 new file mode 100644 index 0000000000000..9f21e84c8af3f --- /dev/null +++ b/x-pack/plugin/security/licenses/lang-tag-1.4.4.jar.sha1 @@ -0,0 +1 @@ +1db9a709239ae473a69b5424c7e78d0b7108229d \ No newline at end of file diff --git a/x-pack/plugin/security/licenses/lang-tag-LICENSE.txt b/x-pack/plugin/security/licenses/lang-tag-LICENSE.txt new file mode 100644 index 0000000000000..d645695673349 --- /dev/null +++ b/x-pack/plugin/security/licenses/lang-tag-LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/x-pack/plugin/security/licenses/lang-tag-NOTICE.txt b/x-pack/plugin/security/licenses/lang-tag-NOTICE.txt new file mode 100644 index 0000000000000..37a85f6850d57 --- /dev/null +++ b/x-pack/plugin/security/licenses/lang-tag-NOTICE.txt @@ -0,0 +1,14 @@ +Nimbus Language Tags + +Copyright 2012-2016, Connect2id Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. diff --git a/x-pack/plugin/security/licenses/nimbus-jose-jwt-4.41.2.jar.sha1 b/x-pack/plugin/security/licenses/nimbus-jose-jwt-4.41.2.jar.sha1 new file mode 100644 index 0000000000000..7713379f35a6c --- /dev/null +++ b/x-pack/plugin/security/licenses/nimbus-jose-jwt-4.41.2.jar.sha1 @@ -0,0 +1 @@ +3981d32ddfa2919a7af46eb5e484f8dc064da665 \ No newline at end of file diff --git a/x-pack/plugin/security/licenses/nimbus-jose-jwt-LICENSE.txt b/x-pack/plugin/security/licenses/nimbus-jose-jwt-LICENSE.txt new file mode 100644 index 0000000000000..d645695673349 --- /dev/null +++ b/x-pack/plugin/security/licenses/nimbus-jose-jwt-LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/x-pack/plugin/security/licenses/nimbus-jose-jwt-NOTICE.txt b/x-pack/plugin/security/licenses/nimbus-jose-jwt-NOTICE.txt new file mode 100644 index 0000000000000..cb9ad94f662a6 --- /dev/null +++ b/x-pack/plugin/security/licenses/nimbus-jose-jwt-NOTICE.txt @@ -0,0 +1,14 @@ +Nimbus JOSE + JWT + +Copyright 2012 - 2018, Connect2id Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. diff --git a/x-pack/plugin/security/licenses/oauth2-oidc-sdk-6.5.jar.sha1 b/x-pack/plugin/security/licenses/oauth2-oidc-sdk-6.5.jar.sha1 new file mode 100644 index 0000000000000..12e6376c4db32 --- /dev/null +++ b/x-pack/plugin/security/licenses/oauth2-oidc-sdk-6.5.jar.sha1 @@ -0,0 +1 @@ +422759fc195f65345e8da3265c69dea3c6cf56a5 \ No newline at end of file diff --git a/x-pack/plugin/security/licenses/oauth2-oidc-sdk-LICENSE.txt b/x-pack/plugin/security/licenses/oauth2-oidc-sdk-LICENSE.txt new file mode 100644 index 0000000000000..d645695673349 --- /dev/null +++ b/x-pack/plugin/security/licenses/oauth2-oidc-sdk-LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/x-pack/plugin/security/licenses/oauth2-oidc-sdk-NOTICE.txt b/x-pack/plugin/security/licenses/oauth2-oidc-sdk-NOTICE.txt new file mode 100644 index 0000000000000..5e111b04cfc45 --- /dev/null +++ b/x-pack/plugin/security/licenses/oauth2-oidc-sdk-NOTICE.txt @@ -0,0 +1,14 @@ +Nimbus OAuth 2.0 SDK with OpenID Connect extensions + +Copyright 2012-2018, Connect2id Ltd and contributors. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. From 19034ce715b1e3a60ac9a036a3cb48a4dc045e5e Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Wed, 23 Jan 2019 23:24:14 +0200 Subject: [PATCH 03/20] Support userinfo requests --- .../oidc/OpenIdConnectAuthenticator.java | 220 +++++++++++++++--- .../authc/oidc/OpenIdConnectRealm.java | 34 ++- .../authc/oidc/RelyingPartyConfiguration.java | 1 - .../authc/oidc/OpenIdConnectRealmTests.java | 55 +++++ 4 files changed, 277 insertions(+), 33 deletions(-) diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java index 083e480ca172d..bd06602db0e0b 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java @@ -7,6 +7,7 @@ import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.util.DefaultResourceRetriever; +import com.nimbusds.jose.util.IOUtils; import com.nimbusds.jose.util.Resource; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; @@ -14,7 +15,6 @@ import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; import com.nimbusds.oauth2.sdk.AuthorizationGrant; import com.nimbusds.oauth2.sdk.ErrorObject; -import com.nimbusds.oauth2.sdk.ParseException; import com.nimbusds.oauth2.sdk.TokenErrorResponse; import com.nimbusds.oauth2.sdk.TokenRequest; import com.nimbusds.oauth2.sdk.TokenResponse; @@ -24,6 +24,8 @@ import com.nimbusds.oauth2.sdk.http.HTTPRequest; import com.nimbusds.oauth2.sdk.http.HTTPResponse; import com.nimbusds.oauth2.sdk.id.State; +import com.nimbusds.oauth2.sdk.token.AccessToken; +import com.nimbusds.oauth2.sdk.token.BearerAccessToken; import com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse; import com.nimbusds.openid.connect.sdk.AuthenticationResponse; import com.nimbusds.openid.connect.sdk.AuthenticationResponseParser; @@ -31,23 +33,38 @@ import com.nimbusds.openid.connect.sdk.Nonce; import com.nimbusds.openid.connect.sdk.OIDCTokenResponse; import com.nimbusds.openid.connect.sdk.OIDCTokenResponseParser; +import com.nimbusds.openid.connect.sdk.UserInfoErrorResponse; +import com.nimbusds.openid.connect.sdk.UserInfoRequest; +import com.nimbusds.openid.connect.sdk.UserInfoResponse; +import com.nimbusds.openid.connect.sdk.UserInfoSuccessResponse; +import com.nimbusds.openid.connect.sdk.claims.AccessTokenHash; +import com.nimbusds.openid.connect.sdk.token.OIDCTokens; +import com.nimbusds.openid.connect.sdk.validators.AccessTokenValidator; import com.nimbusds.openid.connect.sdk.validators.IDTokenValidator; +import net.minidev.json.JSONObject; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.protocol.BasicHttpContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.SpecialPermission; +import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.RealmSettings; import org.elasticsearch.xpack.core.ssl.SSLConfiguration; import org.elasticsearch.xpack.core.ssl.SSLService; import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; import java.io.IOException; import java.net.URI; -import java.net.URISyntaxException; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; @@ -74,6 +91,16 @@ public class OpenIdConnectAuthenticator { this.sslService = sslService; } + /** + * Processes an OpenID Connect Response to an Authentication Request that comes in the form of a URL with the necessary parameters, that + * is contained in the provided Token. If the response is valid, it returns a set of OpenID Connect claims that identify the + * authenticated user. If the UserInfo endpoint is specified in the configuration, we attempt to make a UserInfo request and add + * the returned claims. + * + * @param token The OpenIdConnectToken to consume + * @return a {@link JWTClaimsSet} with the OP claims for the user + * @throws ElasticsearchSecurityException if the response is invalid in any way + */ public JWTClaimsSet authenticate(OpenIdConnectToken token) { try { AuthenticationResponse authenticationResponse = AuthenticationResponseParser.parse(new URI(token.getRedirectUrl())); @@ -92,21 +119,73 @@ public JWTClaimsSet authenticate(OpenIdConnectToken token) { validateState(expectedState, response.getState()); validateResponseType(response); JWT idToken; + AccessToken accessToken; if (rpConfig.getResponseType().impliesCodeFlow()) { final AuthorizationCode code = response.getAuthorizationCode(); - idToken = exchangeCodeForToken(code); + Tuple tokens = exchangeCodeForToken(code); + accessToken = tokens.v1(); + idToken = tokens.v2(); + validateAccessToken(accessToken, idToken, true); } else { idToken = response.getIDToken(); + accessToken = response.getAccessToken(); + validateAccessToken(accessToken, idToken, false); + } + final JWTClaimsSet idTokenClaims = validateAndParseIdToken(idToken, expectedNonce); + if (opConfig.getAuthorizationEndpoint() != null) { + final JWTClaimsSet userInfoClaims = getUserInfo(accessToken); + final JSONObject combinedClaims = idTokenClaims.toJSONObject(); + combinedClaims.merge(userInfoClaims.toJSONObject()); + return (JWTClaimsSet.parse(combinedClaims)); + } else { + return idTokenClaims; } - return validateAndParseIdToken(idToken, expectedNonce); + } catch (Exception e) { + logger.debug("Failed to consume the OpenID connect response", e); + throw new ElasticsearchSecurityException("Failed to consume the OpenID connect response"); + } + } - } catch (URISyntaxException | ParseException e) { - logger.debug("Failed to parse the response that was sent to the redirect_uri", e); - throw new ElasticsearchSecurityException("Failed to parse the response that was sent to the redirect_uri"); + /** + * Validates an access token according to the + * specification + * + * @param accessToken The Access Token to validate + * @param idToken The Id Token that was received in the same response + * @param optional When using the authorization code flow the OP might not provide the at_hash parameter in the + * Id Token as allowed in the specification. In such a case we can't validate the access token + * but this is considered safe as it was received in a back channel communication that was protected + * by TLS. + */ + private void validateAccessToken(AccessToken accessToken, JWT idToken, boolean optional) { + try { + // only "bearer" is defined in the specification but check just in case + if (accessToken.getType().equals("bearer") == false) { + logger.debug("Invalid access token type [{}], while [bearer] was expected", accessToken.getType()); + throw new ElasticsearchSecurityException("Received a response with an invalid state parameter"); + } + AccessTokenHash atHash = new AccessTokenHash(idToken.getJWTClaimsSet().getStringClaim("at_hash")); + if (null == atHash && optional == false) { + logger.debug("Failed to verify access token. at_hash claim is missing from the ID Token"); + throw new ElasticsearchSecurityException("Failed to verify access token"); + } + JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(idToken.getHeader().getAlgorithm().getName()); + AccessTokenValidator.validate(accessToken, jwsAlgorithm, atHash); + } catch (Exception e) { + logger.debug("Failed to verify access token.", e); + throw new ElasticsearchSecurityException("Failed to verify access token."); } } + /** + * Parses and validates an OpenID Connect Id Token to a set of claims + * + * @param idToken The Id Token to parse and validate + * @param expectedNonce The nonce that was generated in the beginning of this authentication attempt and was stored at the user's + * session with the facilitator + * @return a {@link JWTClaimsSet} with the OP claims that were contained in the Id Token + */ private JWTClaimsSet validateAndParseIdToken(JWT idToken, Nonce expectedNonce) { Secret clientSecret = null; try { @@ -117,7 +196,7 @@ private JWTClaimsSet validateAndParseIdToken(JWT idToken, Nonce expectedNonce) { validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, clientSecret); } else { validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, - opConfig.getJwkSetUrl(), new PrivilegedResourceRetriever()); + opConfig.getJwkSetUrl(), getPrivilegedResourceRetriever()); } JWTClaimsSet verifiedIdTokenClaims = validator.validate(idToken, expectedNonce).toJWTClaimsSet(); if (logger.isTraceEnabled()) { @@ -135,6 +214,12 @@ private JWTClaimsSet validateAndParseIdToken(JWT idToken, Nonce expectedNonce) { } } + /** + * Validate that the response we received corresponds to the response type we requested + * + * @param response The {@link AuthenticationSuccessResponse} we received + * @throws ElasticsearchSecurityException if the response is not the expected one for the configured response type + */ private void validateResponseType(AuthenticationSuccessResponse response) { if (rpConfig.getResponseType().equals(response.impliedResponseType()) == false) { logger.debug("Unexpected response type [{}], while [{}] is configured", response.impliedResponseType(), @@ -143,6 +228,13 @@ private void validateResponseType(AuthenticationSuccessResponse response) { } } + /** + * Validate that the state parameter the response contained corresponds to the one that we generated in the + * beginning of this authentication attempt and was stored with the user's session at the facilitator + * + * @param expectedState The state that was originally generated + * @param state The state that was contained in the response + */ private void validateState(State expectedState, State state) { if (state.equals(expectedState) == false) { logger.debug("Invalid state parameter [{}], while [{}] was expected", state, expectedState); @@ -150,38 +242,55 @@ private void validateState(State expectedState, State state) { } } - private JWT exchangeCodeForToken(AuthorizationCode code) { + /** + * Makes a {@link HTTPRequest} using the appropriate TLS configuration and returns the associated {@link HTTPResponse} + */ + private HTTPResponse getResponse(HTTPRequest httpRequest) throws PrivilegedActionException { + final String sslKey = RealmSettings.realmSslPrefix(realmConfig.identifier()); + final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration(sslKey); + boolean isHostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); + final HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; + httpRequest.setSSLSocketFactory(sslService.sslSocketFactory(sslConfiguration)); + httpRequest.setHostnameVerifier(verifier); + + SpecialPermission.check(); + return AccessController.doPrivileged((PrivilegedExceptionAction) httpRequest::send); + } + + /** + * Completes the Authorization Code Grant authentication flow of OpenId Connect by exchanging the received + * authorization code for an Id Token and an access token. + * + * @param code the authorization code that was received as a response to the authentication request + * @return a {@link Tuple} containing the received (yet not validated) {@link AccessToken} and {@link JWT} + */ + private Tuple exchangeCodeForToken(AuthorizationCode code) { Secret clientSecret = null; try { clientSecret = new Secret(rpConfig.getClientSecret().toString()); final ClientAuthentication clientAuth = new ClientSecretBasic(rpConfig.getClientId(), clientSecret); final AuthorizationGrant codeGrant = new AuthorizationCodeGrant(code, rpConfig.getRedirectUri()); final TokenRequest request = new TokenRequest(opConfig.getTokenEndpoint(), clientAuth, codeGrant); - - final String sslKey = RealmSettings.realmSslPrefix(realmConfig.identifier()); - final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration(sslKey); - boolean isHostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); - final HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; - final HTTPRequest httpRequest = request.toHTTPRequest(); - httpRequest.setSSLSocketFactory(sslService.sslSocketFactory(sslConfiguration)); - httpRequest.setHostnameVerifier(verifier); - - SpecialPermission.check(); - final HTTPResponse httpResponse = - AccessController.doPrivileged((PrivilegedExceptionAction) httpRequest::send); - + final HTTPResponse httpResponse = getResponse(request.toHTTPRequest()); final TokenResponse tokenResponse = OIDCTokenResponseParser.parse(httpResponse); if (tokenResponse.indicatesSuccess() == false) { TokenErrorResponse errorResponse = (TokenErrorResponse) tokenResponse; - throw new ElasticsearchSecurityException("Failed to exchange code for Id Token. Code=[{}], Description=[{}]", + logger.debug("Failed to exchange code for Id Token. Code=[{}], Description=[{}]", errorResponse.getErrorObject().getCode(), errorResponse.getErrorObject().getDescription()); + throw new ElasticsearchSecurityException("Failed to exchange code for Id Token."); } OIDCTokenResponse successResponse = (OIDCTokenResponse) tokenResponse.toSuccessResponse(); if (logger.isTraceEnabled()) { logger.trace("Successfully exchanged code for ID Token: [{}]", successResponse.toJSONObject().toJSONString()); } - - return successResponse.getOIDCTokens().getIDToken(); + final OIDCTokens oidcTokens = successResponse.getOIDCTokens(); + final AccessToken accessToken = oidcTokens.getAccessToken(); + final JWT idToken = oidcTokens.getIDToken(); + if (idToken == null) { + logger.debug("Failed to parse the received Id Token to a JWT"); + throw new ElasticsearchSecurityException("Failed to exchange code for Id Token."); + } + return new Tuple<>(accessToken, idToken); } catch (Exception e) { logger.debug("Failed to exchange code for Id Token using the Token Endpoint. ", e); throw new ElasticsearchSecurityException("Failed to exchange code for Id Token."); @@ -192,17 +301,74 @@ private JWT exchangeCodeForToken(AuthorizationCode code) { } } + /** + * Makes a request to the UserInfo Endpoint of the OP + * + * @param accessToken the access token to authenticate + * @return a {@link JWTClaimsSet} with the claims returned + */ + private JWTClaimsSet getUserInfo(AccessToken accessToken) { + try { + final BearerAccessToken bearerToken = new BearerAccessToken(accessToken.getValue()); + final HTTPRequest httpRequest = new UserInfoRequest(opConfig.getUserinfoEndpoint(), bearerToken).toHTTPRequest(); + final HTTPResponse httpResponse = getResponse(httpRequest); + final UserInfoResponse response = UserInfoResponse.parse(httpResponse); + if (response.indicatesSuccess() == false) { + UserInfoErrorResponse errorResponse = response.toErrorResponse(); + logger.debug("Failed to get user information from the UserInfo endpoint. Code=[{}], " + + "Description=[{}]", errorResponse.getErrorObject().getCode(), errorResponse.getErrorObject().getDescription()); + throw new ElasticsearchSecurityException("Failed to get user information from the UserInfo endpoint"); + } + UserInfoSuccessResponse successResponse = response.toSuccessResponse(); + if (logger.isTraceEnabled()) { + logger.trace("Successfully retrieved user information: [{}]", successResponse.getUserInfo().toJSONObject().toJSONString()); + } + return successResponse.getUserInfoJWT().getJWTClaimsSet(); + } catch (Exception e) { + logger.debug("FFailed to get user information from the UserInfo endpoint. ", e); + throw new ElasticsearchSecurityException("Failed to get user information from the UserInfo endpoint."); + } + } + + /** + * Creates a new {@link PrivilegedResourceRetriever} to be used with the {@link IDTokenValidator} by passing the + * necessary client SSLContext and hostname verification configuration + */ + private PrivilegedResourceRetriever getPrivilegedResourceRetriever() { + final String sslKey = RealmSettings.realmSslPrefix(realmConfig.identifier()); + final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration(sslKey); + boolean isHostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); + final HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; + return new PrivilegedResourceRetriever(sslService.sslContext(sslConfiguration), verifier); + } + private static final class PrivilegedResourceRetriever extends DefaultResourceRetriever { + private SSLContext clientContext; + private HostnameVerifier verifier; - PrivilegedResourceRetriever() { + PrivilegedResourceRetriever(final SSLContext clientContext, final HostnameVerifier verifier) { super(); + this.clientContext = clientContext; + this.verifier = verifier; } @Override public Resource retrieveResource(final URL url) throws IOException { + SpecialPermission.check(); try { return AccessController.doPrivileged( - (PrivilegedExceptionAction) () -> PrivilegedResourceRetriever.super.retrieveResource(url)); + (PrivilegedExceptionAction) () -> { + final BasicHttpContext context = new BasicHttpContext(); + try (CloseableHttpClient client = HttpClients.custom() + .setSSLContext(clientContext) + .setSSLHostnameVerifier(verifier) + .build()) { + HttpGet get = new HttpGet(url.toURI()); + HttpResponse response = client.execute(get, context); + return new Resource(IOUtils.readInputStreamToString(response.getEntity().getContent(), + StandardCharsets.UTF_8), response.getEntity().getContentType().getValue()); + } + }); } catch (final PrivilegedActionException e) { throw (IOException) e.getCause(); } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index 18c36472eeaba..664a7b78725c4 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -23,6 +23,7 @@ import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.SettingsException; import org.elasticsearch.common.util.concurrent.ThreadContext; +import org.elasticsearch.license.XPackLicenseState; import org.elasticsearch.xpack.core.security.action.oidc.OpenIdConnectPrepareAuthenticationResponse; import org.elasticsearch.xpack.core.security.authc.AuthenticationResult; import org.elasticsearch.xpack.core.security.authc.AuthenticationToken; @@ -32,6 +33,7 @@ import org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings; import org.elasticsearch.xpack.core.security.user.User; import org.elasticsearch.xpack.core.ssl.SSLService; +import org.elasticsearch.xpack.security.authc.support.DelegatedAuthorizationSupport; import org.elasticsearch.xpack.security.authc.support.UserRoleMapper; import org.elasticsearch.xpack.security.authc.support.mapper.NativeRoleMappingStore; @@ -83,6 +85,7 @@ public class OpenIdConnectRealm extends Realm { private final ClaimParser mailAttribute; private final Boolean populateUserMetadata; private final UserRoleMapper roleMapper; + private DelegatedAuthorizationSupport delegatedRealms; public OpenIdConnectRealm(RealmConfig config, SSLService sslService, NativeRoleMappingStore roleMapper) { @@ -113,6 +116,14 @@ public OpenIdConnectRealm(RealmConfig config, SSLService sslService, NativeRoleM this.populateUserMetadata = config.getSetting(POPULATE_USER_METADATA); } + @Override + public void initialize(Iterable realms, XPackLicenseState licenseState) { + if (delegatedRealms != null) { + throw new IllegalStateException("Realm has already been initialized"); + } + delegatedRealms = new DelegatedAuthorizationSupport(realms, config, licenseState); + } + @Override public boolean supports(AuthenticationToken token) { return token instanceof OpenIdConnectToken; @@ -127,8 +138,12 @@ public AuthenticationToken token(ThreadContext context) { public void authenticate(AuthenticationToken token, ActionListener listener) { if (token instanceof OpenIdConnectToken) { OpenIdConnectToken oidcToken = (OpenIdConnectToken) token; - JWTClaimsSet claims = openIdConnectAuthenticator.authenticate(oidcToken); - buildUserFromClaims(claims, listener); + try { + JWTClaimsSet claims = openIdConnectAuthenticator.authenticate(oidcToken); + buildUserFromClaims(claims, listener); + } catch (ElasticsearchException e) { + listener.onResponse(AuthenticationResult.unsuccessful("Failed to authenticate user", e)); + } } else { listener.onResponse(AuthenticationResult.notHandled()); } @@ -148,6 +163,12 @@ private void buildUserFromClaims(JWTClaimsSet claims, ActionListener userMetadata = new HashMap<>(); if (populateUserMetadata) { Map claimsMap = claims.getClaims(); @@ -310,14 +331,16 @@ static ClaimParser forSetting(Logger logger, OpenIdConnectRealmSettings.ClaimSet values = Collections.singletonList((String) claimValueObject); } else if (claimValueObject instanceof List == false) { throw new SettingsException("Setting [" + RealmSettings.getFullSettingKey(realmConfig, setting.getClaim()) - + " expects a claim with String or a String Array value but found a " + claimValueObject.getClass().getName()); + + " expects a claim with String or a String Array value but found a " + + claimValueObject.getClass().getName()); } else { values = (List) claimValueObject; } return values.stream().map(s -> { final Matcher matcher = regex.matcher(s); if (matcher.find() == false) { - logger.debug("OpenID Connect Claim [{}] is [{}], which does not match [{}]", claimName, s, regex.pattern()); + logger.debug("OpenID Connect Claim [{}] is [{}], which does not match [{}]", + claimName, s, regex.pattern()); return null; } final String value = matcher.group(1); @@ -340,7 +363,8 @@ static ClaimParser forSetting(Logger logger, OpenIdConnectRealmSettings.ClaimSet return Collections.singletonList((String) claimValueObject); } else if (claimValueObject instanceof List == false) { throw new SettingsException("Setting [" + RealmSettings.getFullSettingKey(realmConfig, setting.getClaim()) - + " expects a claim with String or a String Array value but found a " + claimValueObject.getClass().getName()); + + " expects a claim with String or a String Array value but found a " + + claimValueObject.getClass().getName()); } return (List) claimValueObject; }); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java index 6e1cb35a6ad7e..18fa984d05dec 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java @@ -8,7 +8,6 @@ import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.oauth2.sdk.ResponseType; import com.nimbusds.oauth2.sdk.Scope; -import com.nimbusds.oauth2.sdk.auth.Secret; import com.nimbusds.oauth2.sdk.id.ClientID; import org.elasticsearch.common.settings.SecureString; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java index df0f85c223459..17e499a1eeac4 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java @@ -44,6 +44,7 @@ public void testIncorrectResponseTypeThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "hybrid"); @@ -60,6 +61,7 @@ public void testMissingAuthorizationEndpointThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -77,6 +79,7 @@ public void testInvalidAuthorizationEndpointThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -93,6 +96,7 @@ public void testMissingTokenEndpointThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -110,6 +114,7 @@ public void testInvalidTokenEndpointThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "This is not a uri") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -125,6 +130,7 @@ public void testMissingJwksUrlThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -142,6 +148,7 @@ public void testInvalidJwksUrlThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "this is not a url") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "This is not a uri") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -158,6 +165,7 @@ public void testMissingIssuerThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -174,6 +182,7 @@ public void testMissingNameTypeThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); @@ -191,6 +200,7 @@ public void testMissingRedirectUriThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { @@ -207,6 +217,7 @@ public void testMissingClientIdThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { @@ -216,6 +227,48 @@ public void testMissingClientIdThrowsError() { Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID))); } + public void testMissingPrincipalClaimThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") + .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), + Arrays.asList("openid", "scope1", "scope2")); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()))); + } + + public void testPatternWithoutSettingThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getPattern()), "^(.*)$") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") + .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), + Arrays.asList("openid", "scope1", "scope2")); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getClaim()))); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getPattern()))); + } + public void testBuilidingAuthenticationRequest() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") @@ -223,6 +276,7 @@ public void testBuilidingAuthenticationRequest() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") @@ -245,6 +299,7 @@ public void testBuilidingAuthenticationRequestWithDefaultScope() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); From 66140577f8bd3841782c999f12a78107ed18184c Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Thu, 24 Jan 2019 20:21:24 +0200 Subject: [PATCH 04/20] Add few tests --- .../oidc/OpenIdConnectAuthenticator.java | 11 +- .../authc/oidc/OpenIdConnectRealm.java | 17 +- .../oidc/OpenIdConnectAuthenticatorTests.java | 117 ++++++ .../oidc/OpenIdConnectRealmSettingsTests.java | 279 +++++++++++++ .../authc/oidc/OpenIdConnectRealmTests.java | 395 ++++++++---------- 5 files changed, 592 insertions(+), 227 deletions(-) create mode 100644 x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java create mode 100644 x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java index bd06602db0e0b..fb66bc7a9e0e9 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java @@ -141,6 +141,9 @@ public JWTClaimsSet authenticate(OpenIdConnectToken token) { return idTokenClaims; } + } catch (ElasticsearchSecurityException e) { + // Don't wrap in a new ElasticsearchSecurityException + throw e; } catch (Exception e) { logger.debug("Failed to consume the OpenID connect response", e); throw new ElasticsearchSecurityException("Failed to consume the OpenID connect response"); @@ -236,9 +239,13 @@ private void validateResponseType(AuthenticationSuccessResponse response) { * @param state The state that was contained in the response */ private void validateState(State expectedState, State state) { - if (state.equals(expectedState) == false) { + if (null == state || null == expectedState) { + logger.debug("Failed to validate the response, at least one of the stored [{}] or received [{}] values were empty. ", state, + expectedState); + throw new ElasticsearchSecurityException("Failed to validate the response, state parameter is missing."); + } else if (state.equals(expectedState) == false) { logger.debug("Invalid state parameter [{}], while [{}] was expected", state, expectedState); - throw new ElasticsearchSecurityException("Received a response with an invalid state parameter"); + throw new ElasticsearchSecurityException("Received a response with an invalid state parameter."); } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index 664a7b78725c4..451f40ea9d4df 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -35,7 +35,6 @@ import org.elasticsearch.xpack.core.ssl.SSLService; import org.elasticsearch.xpack.security.authc.support.DelegatedAuthorizationSupport; import org.elasticsearch.xpack.security.authc.support.UserRoleMapper; -import org.elasticsearch.xpack.security.authc.support.mapper.NativeRoleMappingStore; import java.net.MalformedURLException; import java.net.URI; @@ -88,7 +87,7 @@ public class OpenIdConnectRealm extends Realm { private DelegatedAuthorizationSupport delegatedRealms; - public OpenIdConnectRealm(RealmConfig config, SSLService sslService, NativeRoleMappingStore roleMapper) { + public OpenIdConnectRealm(RealmConfig config, SSLService sslService, UserRoleMapper roleMapper) { super(config); this.roleMapper = roleMapper; this.rpConfiguration = buildRelyingPartyConfiguration(config); @@ -102,6 +101,20 @@ public OpenIdConnectRealm(RealmConfig config, SSLService sslService, NativeRoleM this.populateUserMetadata = config.getSetting(POPULATE_USER_METADATA); } + OpenIdConnectRealm(RealmConfig config, OpenIdConnectAuthenticator authenticator, UserRoleMapper roleMapper) { + super(config); + this.roleMapper = roleMapper; + this.rpConfiguration = null; + this.opConfiguration = null; + this.openIdConnectAuthenticator = authenticator; + this.principalAttribute = ClaimParser.forSetting(logger, PRINCIPAL_CLAIM, config, true); + this.groupsAttribute = ClaimParser.forSetting(logger, GROUPS_CLAIM, config, false); + this.dnAttribute = ClaimParser.forSetting(logger, DN_CLAIM, config, false); + this.nameAttribute = ClaimParser.forSetting(logger, NAME_CLAIM, config, false); + this.mailAttribute = ClaimParser.forSetting(logger, MAIL_CLAIM, config, false); + this.populateUserMetadata = config.getSetting(POPULATE_USER_METADATA); + } + OpenIdConnectRealm(RealmConfig config) { super(config); this.roleMapper = null; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java new file mode 100644 index 0000000000000..742ff3db3ec35 --- /dev/null +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java @@ -0,0 +1,117 @@ +package org.elasticsearch.xpack.security.authc.oidc; + +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.oauth2.sdk.ResponseType; +import com.nimbusds.oauth2.sdk.Scope; +import com.nimbusds.oauth2.sdk.id.ClientID; +import com.nimbusds.oauth2.sdk.id.Issuer; +import org.elasticsearch.ElasticsearchException; +import org.elasticsearch.common.settings.SecureString; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.util.concurrent.ThreadContext; +import org.elasticsearch.env.Environment; +import org.elasticsearch.env.TestEnvironment; +import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.core.security.authc.RealmConfig; +import org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings; +import org.junit.Before; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; + +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows; +import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey; +import static org.hamcrest.Matchers.containsString; + +public class OpenIdConnectAuthenticatorTests extends ESTestCase { + + private OpenIdConnectAuthenticator authenticator; + private static String REALM_NAME = "oidc-realm"; + private Settings globalSettings; + private Environment env; + private ThreadContext threadContext; + + @Before + public void setup() throws Exception { + globalSettings = Settings.builder().put("path.home", createTempDir()).build(); + env = TestEnvironment.newEnvironment(globalSettings); + threadContext = new ThreadContext(globalSettings); + authenticator = buildAuthenticator(); + } + + + private OpenIdConnectAuthenticator buildAuthenticator() throws MalformedURLException, URISyntaxException { + final RealmConfig config = buildConfig(getBasicRealmSettings().build()); + return new OpenIdConnectAuthenticator(config, getOpConfig(), getRpConfig(), null); + } + + public void testEmptyRedirectUrlIsRejected() { + OpenIdConnectToken token = new OpenIdConnectToken(null, randomAlphaOfLength(8), randomAlphaOfLength(8)); + ElasticsearchException e = expectThrows(ElasticsearchException.class, () -> { + authenticator.authenticate(token); + }); + assertThat(e.getMessage(), containsString("Failed to consume the OpenID connect response")); + } + + public void testInvalidStateIsRejected() { + final String code = randomAlphaOfLengthBetween(8, 12); + final String state = randomAlphaOfLengthBetween(8, 12); + final String invalidState = state.concat(randomAlphaOfLength(2)); + final String redirectUrl = "https://rp.elastic.co/cb?code=" + code + "&state=" + state; + OpenIdConnectToken token = new OpenIdConnectToken(redirectUrl, invalidState, randomAlphaOfLength(10)); + ElasticsearchException e = expectThrows(ElasticsearchException.class, () -> { + authenticator.authenticate(token); + }); + assertThat(e.getMessage(), containsString("Received a response with an invalid state parameter")); + } + + public void testInvalidNonceIsRejected() { + //TODO + } + + private Settings.Builder getBasicRealmSettings() { + return Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.org/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.org/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.org/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.elastic.co/cb") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), randomFrom("code", "id_token")) + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.GROUPS_CLAIM.getClaim()), "groups") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.MAIL_CLAIM.getClaim()), "mail") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getClaim()), "name"); + } + + private OpenIdConnectProviderConfiguration getOpConfig() throws MalformedURLException, URISyntaxException { + return new OpenIdConnectProviderConfiguration("op_name", + new Issuer("https://op.example.com"), + new URL("https://op.example.org/jwks.json"), + new URI("https://op.example.org/login"), + new URI("https://op.example.org/token"), + new URI("https://op.example.org/userinfo")); + } + + private RelyingPartyConfiguration getRpConfig() throws URISyntaxException { + return new RelyingPartyConfiguration( + new ClientID("rp-my"), + new SecureString("mysecret".toCharArray()), + new URI("https://rp.elastic.co/cb"), + new ResponseType("code"), + new Scope("openid"), + JWSAlgorithm.RS384); + } + + private RealmConfig buildConfig(Settings realmSettings) { + final Settings settings = Settings.builder() + .put("path.home", createTempDir()) + .put(realmSettings).build(); + final Environment env = TestEnvironment.newEnvironment(settings); + return new RealmConfig(new RealmConfig.RealmIdentifier("oidc", REALM_NAME), settings, env, threadContext); + } +} diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java new file mode 100644 index 0000000000000..23846db4de3d7 --- /dev/null +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java @@ -0,0 +1,279 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.security.authc.oidc; + + +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.settings.SettingsException; +import org.elasticsearch.common.util.concurrent.ThreadContext; +import org.elasticsearch.env.Environment; +import org.elasticsearch.env.TestEnvironment; +import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.core.security.action.oidc.OpenIdConnectPrepareAuthenticationResponse; +import org.elasticsearch.xpack.core.security.authc.RealmConfig; +import org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings; +import org.hamcrest.Matchers; +import org.junit.Before; + +import java.util.Arrays; + +import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey; +import static org.hamcrest.Matchers.equalTo; + +public class OpenIdConnectRealmSettingsTests extends ESTestCase { + + private static final String REALM_NAME = "oidc1-realm"; + private Settings globalSettings; + private Environment env; + private ThreadContext threadContext; + + @Before + public void setupEnv() { + globalSettings = Settings.builder().put("path.home", createTempDir()).build(); + env = TestEnvironment.newEnvironment(globalSettings); + threadContext = new ThreadContext(globalSettings); + } + + public void testIncorrectResponseTypeThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "hybrid"); + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), Matchers.containsString("[xpack.security.authc.realms.oidc.oidc1-realm.rp.response_type]." + + " Allowed values are [code, id_token]")); + } + + public void testMissingAuthorizationEndpointThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT))); + } + + public void testInvalidAuthorizationEndpointThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "this is not a URI") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT))); + } + + public void testMissingTokenEndpointThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT))); + } + + public void testInvalidTokenEndpointThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "This is not a uri") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT))); + } + + public void testMissingJwksUrlThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL))); + } + + public void testInvalidJwksUrlThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "this is not a url") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "This is not a uri") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL))); + } + + public void testMissingIssuerThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER))); + } + + public void testMissingNameTypeThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME))); + } + + public void testMissingRedirectUriThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI))); + } + + public void testMissingClientIdThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID))); + } + + public void testMissingPrincipalClaimThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") + .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), + Arrays.asList("openid", "scope1", "scope2")); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()))); + } + + public void testPatternWithoutSettingThrowsError() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getPattern()), "^(.*)$") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") + .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), + Arrays.asList("openid", "scope1", "scope2")); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + }); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getClaim()))); + assertThat(exception.getMessage(), + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getPattern()))); + } + + private RealmConfig buildConfig(Settings realmSettings) { + final Settings settings = Settings.builder() + .put("path.home", createTempDir()) + .put(realmSettings).build(); + final Environment env = TestEnvironment.newEnvironment(settings); + return new RealmConfig(new RealmConfig.RealmIdentifier("oidc", REALM_NAME), settings, env, threadContext); + } +} diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java index 17e499a1eeac4..20e7b8f9e3f3e 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java @@ -5,31 +5,54 @@ */ package org.elasticsearch.xpack.security.authc.oidc; - +import com.nimbusds.jwt.JWTClaimsSet; +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.settings.SettingsException; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; import org.elasticsearch.env.TestEnvironment; +import org.elasticsearch.license.XPackLicenseState; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.core.security.action.oidc.OpenIdConnectPrepareAuthenticationResponse; +import org.elasticsearch.xpack.core.security.authc.AuthenticationResult; +import org.elasticsearch.xpack.core.security.authc.Realm; import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings; +import org.elasticsearch.xpack.core.security.authc.saml.SamlRealmSettings; +import org.elasticsearch.xpack.core.security.authc.support.DelegatedAuthorizationSettings; +import org.elasticsearch.xpack.core.security.user.User; +import org.elasticsearch.xpack.security.authc.support.MockLookupRealm; +import org.elasticsearch.xpack.security.authc.support.UserRoleMapper; import org.hamcrest.Matchers; import org.junit.Before; +import org.mockito.Mockito; import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import static java.time.Instant.now; import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey; +import static org.hamcrest.Matchers.arrayContainingInAnyOrder; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class OpenIdConnectRealmTests extends ESTestCase { - private static final String REALM_NAME = "oidc1-realm"; private Settings globalSettings; private Environment env; private ThreadContext threadContext; + private static final String REALM_NAME = "oidc-realm"; @Before public void setupEnv() { globalSettings = Settings.builder().put("path.home", createTempDir()).build(); @@ -37,236 +60,85 @@ public void setupEnv() { threadContext = new ThreadContext(globalSettings); } - public void testIncorrectResponseTypeThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "hybrid"); - IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), Matchers.containsString("[xpack.security.authc.realms.oidc.oidc1-realm.rp.response_type]." + - " Allowed values are [code, id_token]")); - } + public void testAuthentication() throws Exception { + final UserRoleMapper roleMapper = mock(UserRoleMapper.class); + AtomicReference userData = new AtomicReference<>(); + Mockito.doAnswer(invocation -> { + assert invocation.getArguments().length == 2; + userData.set((UserRoleMapper.UserData) invocation.getArguments()[0]); + ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; + listener.onResponse(new HashSet<>(Arrays.asList("kibana_user", "role1"))); + return null; + }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), any(ActionListener.class)); - public void testMissingAuthorizationEndpointThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT))); - } + final boolean notPopulateMetadata = randomBoolean(); - public void testInvalidAuthorizationEndpointThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "this is not a URI") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT))); + AuthenticationResult result = authenticateWithOidc(roleMapper, notPopulateMetadata, false); + assertThat(result.getUser().roles(), arrayContainingInAnyOrder("kibana_user", "role1")); + if (notPopulateMetadata == false) { + assertThat(result.getUser().metadata().get("oidc_iss"), equalTo("https://op.company.org")); + assertThat(result.getUser().metadata().get("oidc_name"), equalTo("Clinton Barton")); + } } - public void testMissingTokenEndpointThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT))); - } + public void testWithAuthorizingRealm() throws Exception { + final UserRoleMapper roleMapper = mock(UserRoleMapper.class); + Mockito.doAnswer(invocation -> { + assert invocation.getArguments().length == 2; + ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; + listener.onFailure(new RuntimeException("Role mapping should not be called")); + return null; + }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), any(ActionListener.class)); - public void testInvalidTokenEndpointThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "This is not a uri") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT))); + AuthenticationResult result = authenticateWithOidc(roleMapper, randomBoolean(), true); + assertThat(result.getUser().roles(), arrayContainingInAnyOrder("lookup_user_role")); + assertThat(result.getUser().fullName(), equalTo("Clinton Barton")); + assertThat(result.getUser().metadata().entrySet(), Matchers.iterableWithSize(1)); + assertThat(result.getUser().metadata().get("is_lookup"), Matchers.equalTo(true)); } - public void testMissingJwksUrlThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL))); + public void testClaimPatternParsing() throws Exception { + final Settings.Builder builder = getBasicRealmSettings(); + builder.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getPattern()), "^OIDC-(.+)"); + final RealmConfig config = buildConfig(builder.build()); + final OpenIdConnectRealmSettings.ClaimSetting principalSetting = new OpenIdConnectRealmSettings.ClaimSetting("principal"); + final OpenIdConnectRealm.ClaimParser parser = OpenIdConnectRealm.ClaimParser.forSetting(logger, principalSetting, config, true); + final JWTClaimsSet claims = new JWTClaimsSet.Builder() + .subject("OIDC-cbarton") + .audience("https://rp.elastic.co/cb") + .expirationTime(Date.from(now().plusSeconds(3600))) + .issueTime(Date.from(now().minusSeconds(5))) + .jwtID(randomAlphaOfLength(8)) + .issuer("https://op.company.org") + .build(); + assertThat(parser.getClaimValue(claims), equalTo("cbarton")); } - public void testInvalidJwksUrlThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "this is not a url") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "This is not a uri") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL))); - } + public void testInvalidPrincipalClaimPatternParsing() throws Exception { + final OpenIdConnectAuthenticator authenticator = mock(OpenIdConnectAuthenticator.class); - public void testMissingIssuerThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER))); - } - - public void testMissingNameTypeThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME))); - } - - public void testMissingRedirectUriThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI))); - } - - public void testMissingClientIdThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID))); - } - - public void testMissingPrincipalClaimThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") - .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), - Arrays.asList("openid", "scope1", "scope2")); - SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()))); - } - - public void testPatternWithoutSettingThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getPattern()), "^(.*)$") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") - .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), - Arrays.asList("openid", "scope1", "scope2")); - SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getClaim()))); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getPattern()))); + final OpenIdConnectToken token = new OpenIdConnectToken("", "", ""); + final Settings.Builder builder = getBasicRealmSettings(); + builder.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getPattern()), "^OIDC-(.+)"); + final RealmConfig config = buildConfig(builder.build()); + final OpenIdConnectRealm realm = new OpenIdConnectRealm(config, authenticator, null); + final OpenIdConnectRealmSettings.ClaimSetting principalSetting = new OpenIdConnectRealmSettings.ClaimSetting("principal"); + final JWTClaimsSet claims = new JWTClaimsSet.Builder() + .subject("cbarton@avengers.com") + .audience("https://rp.elastic.co/cb") + .expirationTime(Date.from(now().plusSeconds(3600))) + .issueTime(Date.from(now().minusSeconds(5))) + .jwtID(randomAlphaOfLength(8)) + .issuer("https://op.company.org") + .build(); + when(authenticator.authenticate(token)).thenReturn(claims); + final PlainActionFuture future = new PlainActionFuture<>(); + realm.authenticate(token, future); + final AuthenticationResult result = future.actionGet(); + assertThat(result.getStatus(), equalTo(AuthenticationResult.Status.CONTINUE)); + assertThat(result.getMessage(), containsString("claims.principal")); + assertThat(result.getMessage(), containsString("sub")); + assertThat(result.getMessage(), containsString("^OIDC-(.+)")); } public void testBuilidingAuthenticationRequest() { @@ -311,6 +183,56 @@ public void testBuilidingAuthenticationRequestWithDefaultScope() { "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state=" + state + "&nonce=" + nonce + "&client_id=rp-my")); } + + private AuthenticationResult authenticateWithOidc(UserRoleMapper roleMapper, boolean notPopulateMetadata, boolean useAuthorizingRealm) + throws Exception { + + final String principal = "324235435454"; + + final MockLookupRealm lookupRealm = new MockLookupRealm( + new RealmConfig(new RealmConfig.RealmIdentifier("mock", "mock_lookup"), globalSettings, env, threadContext)); + final OpenIdConnectAuthenticator authenticator = mock(OpenIdConnectAuthenticator.class); + + final Settings.Builder builder = getBasicRealmSettings(); + if (notPopulateMetadata) { + builder.put(getFullSettingKey(REALM_NAME, SamlRealmSettings.POPULATE_USER_METADATA), + false); + } + if (useAuthorizingRealm) { + builder.putList(getFullSettingKey(new RealmConfig.RealmIdentifier("oidc", REALM_NAME), + DelegatedAuthorizationSettings.AUTHZ_REALMS), lookupRealm.name()); + lookupRealm.registerUser(new User(principal, new String[]{"lookup_user_role"}, "Clinton Barton", "cbarton@shield.gov", + Collections.singletonMap("is_lookup", true), true)); + } + final RealmConfig config = buildConfig(builder.build()); + final OpenIdConnectRealm realm = new OpenIdConnectRealm(config, authenticator, roleMapper); + initializeRealms(realm, lookupRealm); + final OpenIdConnectToken token = new OpenIdConnectToken("", "", ""); + final JWTClaimsSet claims = new JWTClaimsSet.Builder() + .subject(principal) + .audience("https://rp.elastic.co/cb") + .expirationTime(Date.from(now().plusSeconds(3600))) + .issueTime(Date.from(now().minusSeconds(5))) + .jwtID(randomAlphaOfLength(8)) + .issuer("https://op.company.org") + .claim("groups", Arrays.asList("group1", "group2", "groups3")) + .claim("mail", "cbarton@shield.gov") + .claim("name", "Clinton Barton") + .build(); + + when(authenticator.authenticate(token)).thenReturn(claims); + final PlainActionFuture future = new PlainActionFuture<>(); + realm.authenticate(token, future); + final AuthenticationResult result = future.get(); + assertThat(result, notNullValue()); + assertThat(result.getStatus(), equalTo(AuthenticationResult.Status.SUCCESS)); + assertThat(result.getUser().principal(), equalTo(principal)); + assertThat(result.getUser().email(), equalTo("cbarton@shield.gov")); + assertThat(result.getUser().fullName(), equalTo("Clinton Barton")); + + return result; + } + private RealmConfig buildConfig(Settings realmSettings) { final Settings settings = Settings.builder() .put("path.home", createTempDir()) @@ -318,4 +240,31 @@ private RealmConfig buildConfig(Settings realmSettings) { final Environment env = TestEnvironment.newEnvironment(settings); return new RealmConfig(new RealmConfig.RealmIdentifier("oidc", REALM_NAME), settings, env, threadContext); } + + private void initializeRealms(Realm... realms) { + XPackLicenseState licenseState = mock(XPackLicenseState.class); + when(licenseState.isAuthorizationRealmAllowed()).thenReturn(true); + + final List realmList = Arrays.asList(realms); + for (Realm realm : realms) { + realm.initialize(realmList, licenseState); + } + } + + private Settings.Builder getBasicRealmSettings() { + return Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.org/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.org/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.org/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.elastic.co/cb") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), randomFrom("code", "id_token")) + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.GROUPS_CLAIM.getClaim()), "groups") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.MAIL_CLAIM.getClaim()), "mail") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getClaim()), "name"); + } } From b70526aedd712d8974a4cb3fd882fb364e3baef8 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Fri, 25 Jan 2019 18:02:30 +0200 Subject: [PATCH 05/20] Fix bugs and add unit tests --- .../oidc/OpenIdConnectRealmSettings.java | 29 +- .../oidc/OpenIdConnectAuthenticator.java | 102 +++-- .../OpenIdConnectProviderConfiguration.java | 11 +- .../authc/oidc/OpenIdConnectRealm.java | 40 +- .../oidc/OpenIdConnectAuthenticatorTests.java | 365 +++++++++++++++++- .../oidc/OpenIdConnectRealmSettingsTests.java | 74 ++-- .../authc/oidc/OpenIdConnectRealmTests.java | 17 +- 7 files changed, 496 insertions(+), 142 deletions(-) diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java index 98baeeb796bf1..d319e9e9d5e0f 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java @@ -7,16 +7,15 @@ import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; +import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.RealmSettings; import org.elasticsearch.xpack.core.security.authc.support.DelegatedAuthorizationSettings; import org.elasticsearch.xpack.core.ssl.SSLConfigurationSettings; -import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -48,7 +47,7 @@ private OpenIdConnectRealmSettings() { public static final Setting.AffixSetting RP_RESPONSE_TYPE = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "rp.response_type", key -> Setting.simpleString(key, v -> { - List responseTypes = Arrays.asList("code", "id_token"); + List responseTypes = Arrays.asList("code", "id_token", "id_token, token"); if (responseTypes.contains(v) == false) { throw new IllegalArgumentException("Invalid value [" + v + "] for [" + key + "]. Allowed values are " + responseTypes + ""); } @@ -98,19 +97,22 @@ private OpenIdConnectRealmSettings() { }, Setting.Property.NodeScope)); public static final Setting.AffixSetting OP_ISSUER = RealmSettings.simpleString(TYPE, "op.issuer", Setting.Property.NodeScope); - public static final Setting.AffixSetting OP_JWKSET_URL - = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "op.jwkset_url", - key -> Setting.simpleString(key, v -> { - try { - new URL(v); - } catch (MalformedURLException e) { - throw new IllegalArgumentException("Invalid value [" + v + "] for [" + key + "]. Not a valid URL.", e); - } - }, Setting.Property.NodeScope)); + public static final Setting.AffixSetting OP_JWKSET_PATH + = RealmSettings.simpleString(TYPE, "rp.jwkset_path", Setting.Property.NodeScope); public static final Setting.AffixSetting POPULATE_USER_METADATA = Setting.affixKeySetting( RealmSettings.realmSettingPrefix(TYPE), "populate_user_metadata", key -> Setting.boolSetting(key, true, Setting.Property.NodeScope)); + private static final TimeValue DEFAULT_TIMEOUT = TimeValue.timeValueSeconds(5); + public static final Setting.AffixSetting HTTP_CONNECT_TIMEOUT + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "http.connect_timeout", + key -> Setting.timeSetting(key, DEFAULT_TIMEOUT, Setting.Property.NodeScope)); + public static final Setting.AffixSetting HTTP_CONNECTION_READ_TIMEOUT + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "http.connection_read_timeout", + key -> Setting.timeSetting(key, DEFAULT_TIMEOUT, Setting.Property.NodeScope)); + public static final Setting.AffixSetting HTTP_SOCKET_TIMEOUT + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "http.socket_timeout", + key -> Setting.timeSetting(key, DEFAULT_TIMEOUT, Setting.Property.NodeScope)); public static final ClaimSetting PRINCIPAL_CLAIM = new ClaimSetting("principal"); public static final ClaimSetting GROUPS_CLAIM = new ClaimSetting("groups"); @@ -121,7 +123,8 @@ private OpenIdConnectRealmSettings() { public static Set> getSettings() { final Set> set = Sets.newHashSet( RP_CLIENT_ID, RP_REDIRECT_URI, RP_RESPONSE_TYPE, RP_REQUESTED_SCOPES, RP_CLIENT_SECRET, RP_SIGNATURE_VERIFICATION_ALGORITHM, - OP_NAME, OP_AUTHORIZATION_ENDPOINT, OP_TOKEN_ENDPOINT, OP_USERINFO_ENDPOINT, OP_ISSUER, OP_JWKSET_URL); + OP_NAME, OP_AUTHORIZATION_ENDPOINT, OP_TOKEN_ENDPOINT, OP_USERINFO_ENDPOINT, OP_ISSUER, OP_JWKSET_PATH, + HTTP_CONNECT_TIMEOUT, HTTP_CONNECTION_READ_TIMEOUT, HTTP_SOCKET_TIMEOUT); set.addAll(DelegatedAuthorizationSettings.getSettings(TYPE)); set.addAll(RealmSettings.getStandardSettings(TYPE)); set.addAll(SSLConfigurationSettings.getRealmSettings(TYPE)); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java index fb66bc7a9e0e9..88d81ec2da6a8 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java @@ -6,11 +6,13 @@ package org.elasticsearch.xpack.security.authc.oidc; import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.util.DefaultResourceRetriever; import com.nimbusds.jose.util.IOUtils; import com.nimbusds.jose.util.Resource; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.oauth2.sdk.AbstractRequest; import com.nimbusds.oauth2.sdk.AuthorizationCode; import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; import com.nimbusds.oauth2.sdk.AuthorizationGrant; @@ -43,6 +45,7 @@ import com.nimbusds.openid.connect.sdk.validators.IDTokenValidator; import net.minidev.json.JSONObject; import org.apache.http.HttpResponse; +import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.ssl.NoopHostnameVerifier; @@ -53,6 +56,7 @@ import org.apache.logging.log4j.Logger; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.SpecialPermission; +import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.RealmSettings; @@ -65,10 +69,15 @@ import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.HTTP_CONNECT_TIMEOUT; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.HTTP_CONNECTION_READ_TIMEOUT; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.HTTP_SOCKET_TIMEOUT; + /** * Handles an OpenID Connect Authentication response as received by the facilitator. In the case of an implicit flow, validates * the ID Token and extracts the elasticsearch user properties from it. In the case of an authorization code flow, it first @@ -80,15 +89,32 @@ public class OpenIdConnectAuthenticator { private final OpenIdConnectProviderConfiguration opConfig; private final RelyingPartyConfiguration rpConfig; private final SSLService sslService; + private final PrivilegedResourceRetriever privilegedResourceResolver; protected final Logger logger = LogManager.getLogger(getClass()); + public OpenIdConnectAuthenticator(RealmConfig realmConfig, OpenIdConnectProviderConfiguration opConfig, + RelyingPartyConfiguration rpConfig, + SSLService sslService) { + this.realmConfig = realmConfig; + this.opConfig = opConfig; + this.rpConfig = rpConfig; + this.sslService = sslService; + this.privilegedResourceResolver = getPrivilegedResourceRetriever(); + } + + // For testing OpenIdConnectAuthenticator(RealmConfig realmConfig, OpenIdConnectProviderConfiguration opConfig, RelyingPartyConfiguration rpConfig, - SSLService sslService) { + SSLService sslService, PrivilegedResourceRetriever resourceRetriever) { this.realmConfig = realmConfig; this.opConfig = opConfig; this.rpConfig = rpConfig; this.sslService = sslService; + this.privilegedResourceResolver = resourceRetriever; + } + + OpenIdConnectAuthenticator() { + this(null, null, null, null, null); } /** @@ -125,14 +151,13 @@ public JWTClaimsSet authenticate(OpenIdConnectToken token) { Tuple tokens = exchangeCodeForToken(code); accessToken = tokens.v1(); idToken = tokens.v2(); - validateAccessToken(accessToken, idToken, true); } else { idToken = response.getIDToken(); accessToken = response.getAccessToken(); - validateAccessToken(accessToken, idToken, false); } final JWTClaimsSet idTokenClaims = validateAndParseIdToken(idToken, expectedNonce); - if (opConfig.getAuthorizationEndpoint() != null) { + if (opConfig.getUserinfoEndpoint() != null) { + validateAccessToken(accessToken, idToken, rpConfig.getResponseType().impliesCodeFlow()); final JWTClaimsSet userInfoClaims = getUserInfo(accessToken); final JSONObject combinedClaims = idTokenClaims.toJSONObject(); combinedClaims.merge(userInfoClaims.toJSONObject()); @@ -164,15 +189,16 @@ public JWTClaimsSet authenticate(OpenIdConnectToken token) { private void validateAccessToken(AccessToken accessToken, JWT idToken, boolean optional) { try { // only "bearer" is defined in the specification but check just in case - if (accessToken.getType().equals("bearer") == false) { - logger.debug("Invalid access token type [{}], while [bearer] was expected", accessToken.getType()); - throw new ElasticsearchSecurityException("Received a response with an invalid state parameter"); + if (accessToken.getType().toString().equals("Bearer") == false) { + logger.debug("Invalid access token type [{}], while [Bearer] was expected", accessToken.getType()); + throw new ElasticsearchSecurityException("Received a response with an invalid access token type"); } - AccessTokenHash atHash = new AccessTokenHash(idToken.getJWTClaimsSet().getStringClaim("at_hash")); - if (null == atHash && optional == false) { + String atHashValue = idToken.getJWTClaimsSet().getStringClaim("at_hash"); + if (null == atHashValue && optional == false) { logger.debug("Failed to verify access token. at_hash claim is missing from the ID Token"); throw new ElasticsearchSecurityException("Failed to verify access token"); } + AccessTokenHash atHash = new AccessTokenHash(atHashValue); JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(idToken.getHeader().getAlgorithm().getName()); AccessTokenValidator.validate(accessToken, jwsAlgorithm, atHash); } catch (Exception e) { @@ -189,6 +215,7 @@ private void validateAccessToken(AccessToken accessToken, JWT idToken, boolean o * session with the facilitator * @return a {@link JWTClaimsSet} with the OP claims that were contained in the Id Token */ + @SuppressForbidden(reason = "uses toFile") private JWTClaimsSet validateAndParseIdToken(JWT idToken, Nonce expectedNonce) { Secret clientSecret = null; try { @@ -198,8 +225,16 @@ private JWTClaimsSet validateAndParseIdToken(JWT idToken, Nonce expectedNonce) { clientSecret = new Secret(rpConfig.getClientSecret().toString()); validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, clientSecret); } else { - validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, - opConfig.getJwkSetUrl(), getPrivilegedResourceRetriever()); + String jwkSetPath = opConfig.getJwkSetPath(); + if (jwkSetPath.startsWith("https://")) { + validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, + new URL(jwkSetPath), privilegedResourceResolver); + } else { + final Path path = realmConfig.env().configFile().resolve(jwkSetPath); + final JWKSet jwkSet = JWKSet.load(path.toFile()); + validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, jwkSet); + } + } JWTClaimsSet verifiedIdTokenClaims = validator.validate(idToken, expectedNonce).toJWTClaimsSet(); if (logger.isTraceEnabled()) { @@ -209,7 +244,7 @@ private JWTClaimsSet validateAndParseIdToken(JWT idToken, Nonce expectedNonce) { } catch (Exception e) { logger.debug("Failed to parse or validate the ID Token. ", e); - throw new ElasticsearchSecurityException("Failed to parse or validate the ID Token"); + throw new ElasticsearchSecurityException("Failed to parse or validate the ID Token", e); } finally { if (null != clientSecret) { clientSecret.erase(); @@ -250,18 +285,27 @@ private void validateState(State expectedState, State state) { } /** - * Makes a {@link HTTPRequest} using the appropriate TLS configuration and returns the associated {@link HTTPResponse} + * Wraps sending an {@link HTTPRequest} with the appropriate permissions and returns the associated {@link HTTPResponse} */ private HTTPResponse getResponse(HTTPRequest httpRequest) throws PrivilegedActionException { + SpecialPermission.check(); + return AccessController.doPrivileged((PrivilegedExceptionAction) httpRequest::send); + } + + /** + * Converts an {@link AbstractRequest} to a {@link HTTPRequest} setting the necessary TLS configuration and timeout parameters + */ + private HTTPRequest buildRequest(AbstractRequest request) { final String sslKey = RealmSettings.realmSslPrefix(realmConfig.identifier()); final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration(sslKey); boolean isHostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); final HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; + final HTTPRequest httpRequest = request.toHTTPRequest(); httpRequest.setSSLSocketFactory(sslService.sslSocketFactory(sslConfiguration)); httpRequest.setHostnameVerifier(verifier); - - SpecialPermission.check(); - return AccessController.doPrivileged((PrivilegedExceptionAction) httpRequest::send); + httpRequest.setConnectTimeout(Math.toIntExact(realmConfig.getSetting(HTTP_CONNECT_TIMEOUT).getMillis())); + httpRequest.setReadTimeout(Math.toIntExact(realmConfig.getSetting(HTTP_CONNECTION_READ_TIMEOUT).getSeconds())); + return httpRequest; } /** @@ -277,8 +321,8 @@ private Tuple exchangeCodeForToken(AuthorizationCode code) { clientSecret = new Secret(rpConfig.getClientSecret().toString()); final ClientAuthentication clientAuth = new ClientSecretBasic(rpConfig.getClientId(), clientSecret); final AuthorizationGrant codeGrant = new AuthorizationCodeGrant(code, rpConfig.getRedirectUri()); - final TokenRequest request = new TokenRequest(opConfig.getTokenEndpoint(), clientAuth, codeGrant); - final HTTPResponse httpResponse = getResponse(request.toHTTPRequest()); + final TokenRequest tokenRequest = new TokenRequest(opConfig.getTokenEndpoint(), clientAuth, codeGrant); + final HTTPResponse httpResponse = getResponse(buildRequest(tokenRequest)); final TokenResponse tokenResponse = OIDCTokenResponseParser.parse(httpResponse); if (tokenResponse.indicatesSuccess() == false) { TokenErrorResponse errorResponse = (TokenErrorResponse) tokenResponse; @@ -317,9 +361,8 @@ private Tuple exchangeCodeForToken(AuthorizationCode code) { private JWTClaimsSet getUserInfo(AccessToken accessToken) { try { final BearerAccessToken bearerToken = new BearerAccessToken(accessToken.getValue()); - final HTTPRequest httpRequest = new UserInfoRequest(opConfig.getUserinfoEndpoint(), bearerToken).toHTTPRequest(); - final HTTPResponse httpResponse = getResponse(httpRequest); - final UserInfoResponse response = UserInfoResponse.parse(httpResponse); + final UserInfoRequest userInfoRequest = new UserInfoRequest(opConfig.getUserinfoEndpoint(), bearerToken); + final UserInfoResponse response = UserInfoResponse.parse(getResponse(buildRequest(userInfoRequest))); if (response.indicatesSuccess() == false) { UserInfoErrorResponse errorResponse = response.toErrorResponse(); logger.debug("Failed to get user information from the UserInfo endpoint. Code=[{}], " + @@ -341,22 +384,24 @@ private JWTClaimsSet getUserInfo(AccessToken accessToken) { * Creates a new {@link PrivilegedResourceRetriever} to be used with the {@link IDTokenValidator} by passing the * necessary client SSLContext and hostname verification configuration */ - private PrivilegedResourceRetriever getPrivilegedResourceRetriever() { + PrivilegedResourceRetriever getPrivilegedResourceRetriever() { final String sslKey = RealmSettings.realmSslPrefix(realmConfig.identifier()); final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration(sslKey); boolean isHostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); final HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; - return new PrivilegedResourceRetriever(sslService.sslContext(sslConfiguration), verifier); + return new PrivilegedResourceRetriever(sslService.sslContext(sslConfiguration), verifier, realmConfig); } - private static final class PrivilegedResourceRetriever extends DefaultResourceRetriever { + static class PrivilegedResourceRetriever extends DefaultResourceRetriever { private SSLContext clientContext; private HostnameVerifier verifier; + private RealmConfig config; - PrivilegedResourceRetriever(final SSLContext clientContext, final HostnameVerifier verifier) { + PrivilegedResourceRetriever(final SSLContext clientContext, final HostnameVerifier verifier, final RealmConfig config) { super(); this.clientContext = clientContext; this.verifier = verifier; + this.config = config; } @Override @@ -366,9 +411,14 @@ public Resource retrieveResource(final URL url) throws IOException { return AccessController.doPrivileged( (PrivilegedExceptionAction) () -> { final BasicHttpContext context = new BasicHttpContext(); + final RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(Math.toIntExact(config.getSetting(HTTP_CONNECT_TIMEOUT).getMillis())) + .setConnectionRequestTimeout(Math.toIntExact(config.getSetting(HTTP_CONNECTION_READ_TIMEOUT).getSeconds())) + .setSocketTimeout(Math.toIntExact(config.getSetting(HTTP_SOCKET_TIMEOUT).getMillis())).build(); try (CloseableHttpClient client = HttpClients.custom() .setSSLContext(clientContext) .setSSLHostnameVerifier(verifier) + .setDefaultRequestConfig(requestConfig) .build()) { HttpGet get = new HttpGet(url.toURI()); HttpResponse response = client.execute(get, context); @@ -379,8 +429,6 @@ public Resource retrieveResource(final URL url) throws IOException { } catch (final PrivilegedActionException e) { throw (IOException) e.getCause(); } - } - } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectProviderConfiguration.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectProviderConfiguration.java index 635d962a92c37..d6384515d6ebe 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectProviderConfiguration.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectProviderConfiguration.java @@ -9,7 +9,6 @@ import org.elasticsearch.common.Nullable; import java.net.URI; -import java.net.URL; import java.util.Objects; /** @@ -21,16 +20,16 @@ public class OpenIdConnectProviderConfiguration { private final URI tokenEndpoint; private final URI userinfoEndpoint; private final Issuer issuer; - private final URL jwkSetUrl; + private final String jwkSetPath; - public OpenIdConnectProviderConfiguration(String providerName, Issuer issuer, URL jwkSetUrl, URI authorizationEndpoint, + public OpenIdConnectProviderConfiguration(String providerName, Issuer issuer, String jwkSetPath, URI authorizationEndpoint, URI tokenEndpoint, @Nullable URI userinfoEndpoint) { this.providerName = Objects.requireNonNull(providerName, "OP Name must be provided"); this.authorizationEndpoint = Objects.requireNonNull(authorizationEndpoint, "Authorization Endpoint must be provided"); this.tokenEndpoint = Objects.requireNonNull(tokenEndpoint, "Token Endpoint must be provided"); this.userinfoEndpoint = userinfoEndpoint; this.issuer = Objects.requireNonNull(issuer, "OP Issuer must be provided"); - this.jwkSetUrl = Objects.requireNonNull(jwkSetUrl, "jwkSetUrl must be provided"); + this.jwkSetPath = Objects.requireNonNull(jwkSetPath, "jwkSetUrl must be provided"); } public String getProviderName() { @@ -53,7 +52,7 @@ public Issuer getIssuer() { return issuer; } - public URL getJwkSetUrl() { - return jwkSetUrl; + public String getJwkSetPath() { + return jwkSetPath; } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index 451f40ea9d4df..5a59fa31c5d5a 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -24,6 +24,7 @@ import org.elasticsearch.common.settings.SettingsException; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.license.XPackLicenseState; +import org.elasticsearch.xpack.core.XPackSettings; import org.elasticsearch.xpack.core.security.action.oidc.OpenIdConnectPrepareAuthenticationResponse; import org.elasticsearch.xpack.core.security.authc.AuthenticationResult; import org.elasticsearch.xpack.core.security.authc.AuthenticationToken; @@ -33,13 +34,13 @@ import org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings; import org.elasticsearch.xpack.core.security.user.User; import org.elasticsearch.xpack.core.ssl.SSLService; +import org.elasticsearch.xpack.security.authc.TokenService; import org.elasticsearch.xpack.security.authc.support.DelegatedAuthorizationSupport; import org.elasticsearch.xpack.security.authc.support.UserRoleMapper; -import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; + import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -58,7 +59,7 @@ import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.NAME_CLAIM; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_ISSUER; -import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_JWKSET_URL; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_JWKSET_PATH; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_NAME; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.OP_USERINFO_ENDPOINT; @@ -84,6 +85,7 @@ public class OpenIdConnectRealm extends Realm { private final ClaimParser mailAttribute; private final Boolean populateUserMetadata; private final UserRoleMapper roleMapper; + private DelegatedAuthorizationSupport delegatedRealms; @@ -99,28 +101,19 @@ public OpenIdConnectRealm(RealmConfig config, SSLService sslService, UserRoleMap this.nameAttribute = ClaimParser.forSetting(logger, NAME_CLAIM, config, false); this.mailAttribute = ClaimParser.forSetting(logger, MAIL_CLAIM, config, false); this.populateUserMetadata = config.getSetting(POPULATE_USER_METADATA); + if (TokenService.isTokenServiceEnabled(config.settings()) == false) { + throw new IllegalStateException("OpenID Connect Realm requires that the token service be enabled (" + + XPackSettings.TOKEN_SERVICE_ENABLED_SETTING.getKey() + ")"); + } } + // For testing OpenIdConnectRealm(RealmConfig config, OpenIdConnectAuthenticator authenticator, UserRoleMapper roleMapper) { super(config); this.roleMapper = roleMapper; - this.rpConfiguration = null; - this.opConfiguration = null; - this.openIdConnectAuthenticator = authenticator; - this.principalAttribute = ClaimParser.forSetting(logger, PRINCIPAL_CLAIM, config, true); - this.groupsAttribute = ClaimParser.forSetting(logger, GROUPS_CLAIM, config, false); - this.dnAttribute = ClaimParser.forSetting(logger, DN_CLAIM, config, false); - this.nameAttribute = ClaimParser.forSetting(logger, NAME_CLAIM, config, false); - this.mailAttribute = ClaimParser.forSetting(logger, MAIL_CLAIM, config, false); - this.populateUserMetadata = config.getSetting(POPULATE_USER_METADATA); - } - - OpenIdConnectRealm(RealmConfig config) { - super(config); - this.roleMapper = null; this.rpConfiguration = buildRelyingPartyConfiguration(config); this.opConfiguration = buildOpenIdConnectProviderConfiguration(config); - this.openIdConnectAuthenticator = new OpenIdConnectAuthenticator(config, opConfiguration, rpConfiguration, null); + this.openIdConnectAuthenticator = authenticator; this.principalAttribute = ClaimParser.forSetting(logger, PRINCIPAL_CLAIM, config, true); this.groupsAttribute = ClaimParser.forSetting(logger, GROUPS_CLAIM, config, false); this.dnAttribute = ClaimParser.forSetting(logger, DN_CLAIM, config, false); @@ -231,13 +224,9 @@ private RelyingPartyConfiguration buildRelyingPartyConfiguration(RealmConfig con private OpenIdConnectProviderConfiguration buildOpenIdConnectProviderConfiguration(RealmConfig config) { String providerName = require(config, OP_NAME); Issuer issuer = new Issuer(require(config, OP_ISSUER)); - URL jwkSetUrl; - try { - jwkSetUrl = new URL(require(config, OP_JWKSET_URL)); - } catch (MalformedURLException e) { - // This should never happen as it's already validated in the settings - throw new SettingsException("Invalid URL: " + OP_JWKSET_URL.getKey(), e); - } + + String jwkSetUrl = require(config, OP_JWKSET_PATH); + URI authorizationEndpoint; try { authorizationEndpoint = new URI(require(config, OP_AUTHORIZATION_ENDPOINT)); @@ -395,6 +384,5 @@ static ClaimParser forSetting(Logger logger, OpenIdConnectRealmSettings.ClaimSet } } } - } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java index 742ff3db3ec35..466069cce3e0e 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java @@ -1,11 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ package org.elasticsearch.xpack.security.authc.oidc; import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.ECDSASigner; +import com.nimbusds.jose.crypto.MACSigner; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jose.jwk.ECKey; +import com.nimbusds.jose.jwk.JWK; +import com.nimbusds.jose.jwk.JWKSet; +import com.nimbusds.jose.jwk.KeyUse; +import com.nimbusds.jose.jwk.OctetSequenceKey; +import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jose.proc.BadJWSException; +import com.nimbusds.jose.util.Resource; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import com.nimbusds.jwt.proc.BadJWTException; import com.nimbusds.oauth2.sdk.ResponseType; import com.nimbusds.oauth2.sdk.Scope; import com.nimbusds.oauth2.sdk.id.ClientID; import com.nimbusds.oauth2.sdk.id.Issuer; +import com.nimbusds.oauth2.sdk.id.State; +import com.nimbusds.oauth2.sdk.token.AccessToken; +import com.nimbusds.oauth2.sdk.token.BearerAccessToken; +import com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse; +import com.nimbusds.openid.connect.sdk.Nonce; +import com.nimbusds.openid.connect.sdk.claims.AccessTokenHash; import org.elasticsearch.ElasticsearchException; +import org.elasticsearch.ElasticsearchSecurityException; +import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; @@ -14,16 +42,34 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings; +import org.elasticsearch.xpack.core.ssl.SSLService; import org.junit.Before; -import java.net.MalformedURLException; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.security.Key; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.util.Base64; +import java.util.Date; +import java.util.UUID; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows; +import static java.time.Instant.now; import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class OpenIdConnectAuthenticatorTests extends ESTestCase { @@ -35,16 +81,24 @@ public class OpenIdConnectAuthenticatorTests extends ESTestCase { @Before public void setup() throws Exception { - globalSettings = Settings.builder().put("path.home", createTempDir()).build(); + globalSettings = Settings.builder().put("path.home", createTempDir()) + .put("xpack.security.authc.realms.oidc.oidc-realm.ssl.verification_mode", "certificate").build(); env = TestEnvironment.newEnvironment(globalSettings); threadContext = new ThreadContext(globalSettings); authenticator = buildAuthenticator(); } - private OpenIdConnectAuthenticator buildAuthenticator() throws MalformedURLException, URISyntaxException { + private OpenIdConnectAuthenticator buildAuthenticator() throws URISyntaxException { final RealmConfig config = buildConfig(getBasicRealmSettings().build()); - return new OpenIdConnectAuthenticator(config, getOpConfig(), getRpConfig(), null); + return new OpenIdConnectAuthenticator(config, getOpConfig(), getDefaultRpConfig(), new SSLService(globalSettings, env)); + } + + private OpenIdConnectAuthenticator buildAuthenticator(OpenIdConnectProviderConfiguration opConfig, + RelyingPartyConfiguration rpConfig, + OpenIdConnectAuthenticator.PrivilegedResourceRetriever retriever) { + final RealmConfig config = buildConfig(getBasicRealmSettings().build()); + return new OpenIdConnectAuthenticator(config, opConfig, rpConfig, new SSLService(globalSettings, env), retriever); } public void testEmptyRedirectUrlIsRejected() { @@ -67,8 +121,162 @@ public void testInvalidStateIsRejected() { assertThat(e.getMessage(), containsString("Received a response with an invalid state parameter")); } - public void testInvalidNonceIsRejected() { - //TODO + public void testInvalidNonceIsRejected() throws Exception { + final Tuple keyMaterial = getRandomJwkForType(randomFrom("ES", "RS", "HS")); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + + final State state = new State(); + final Nonce nonce = new Nonce(); + final Nonce invalidNonce = new Nonce(); + final String subject = "janedoe"; + final String keyId = (jwk.getAlgorithm().getName().startsWith("HS")) ? null : jwk.getKeyID(); + final String responseUrl = buildResponseUrl(state, invalidNonce, key, jwk.getAlgorithm().getName(), keyId, subject, true, false); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> authenticator.authenticate(token)); + assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); + assertThat(e.getCause(), instanceOf(BadJWTException.class)); + assertThat(e.getCause().getMessage(), containsString("Unexpected JWT nonce")); + } + + public void testAuthenticateImplicitFlowWithRsa() throws Exception { + final Tuple keyMaterial = getRandomJwkForType("RS"); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, false); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); + JWTClaimsSet claimsSet = authenticator.authenticate(token); + assertThat(claimsSet.getSubject(), equalTo(subject)); + } + + public void testAuthenticateImplicitFlowWithEcdsa() throws Exception { + final Tuple keyMaterial = getRandomJwkForType("RS"); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, false); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); + JWTClaimsSet claimsSet = authenticator.authenticate(token); + assertThat(claimsSet.getSubject(), equalTo(subject)); + } + + public void testAuthenticateImplicitFlowWithHmac() throws Exception { + final Tuple keyMaterial = getRandomJwkForType("HS"); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), null, subject, true, false); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); + JWTClaimsSet claimsSet = authenticator.authenticate(token); + assertThat(claimsSet.getSubject(), equalTo(subject)); + } + + public void testAuthenticateImplicitFlowFailsWithForgedRsaIdToken() throws Exception { + final Tuple keyMaterial = getRandomJwkForType("RS"); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, true); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> authenticator.authenticate(token)); + assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); + assertThat(e.getCause(), instanceOf(BadJWSException.class)); + assertThat(e.getCause().getMessage(), containsString("Signed JWT rejected: Invalid signature")); + } + + public void testAuthenticateImplicitFlowFailsWithForgedEcsdsaIdToken() throws Exception { + final Tuple keyMaterial = getRandomJwkForType("ES"); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, true); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> authenticator.authenticate(token)); + assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); + assertThat(e.getCause(), instanceOf(BadJWSException.class)); + assertThat(e.getCause().getMessage(), containsString("Signed JWT rejected: Invalid signature")); + } + + public void testAuthenticateImplicitFlowFailsWithForgedHmacIdToken() throws Exception { + final Tuple keyMaterial = getRandomJwkForType("HS"); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), null, subject, true, true); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> authenticator.authenticate(token)); + assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); + assertThat(e.getCause(), instanceOf(BadJWSException.class)); + assertThat(e.getCause().getMessage(), containsString("Signed JWT rejected: Invalid signature")); } private Settings.Builder getBasicRealmSettings() { @@ -77,7 +285,7 @@ private Settings.Builder getBasicRealmSettings() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.org/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.org/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.org/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.elastic.co/cb") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") @@ -88,25 +296,35 @@ private Settings.Builder getBasicRealmSettings() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getClaim()), "name"); } - private OpenIdConnectProviderConfiguration getOpConfig() throws MalformedURLException, URISyntaxException { + private OpenIdConnectProviderConfiguration getOpConfig() throws URISyntaxException { return new OpenIdConnectProviderConfiguration("op_name", new Issuer("https://op.example.com"), - new URL("https://op.example.org/jwks.json"), + "https://op.example.org/jwks.json", new URI("https://op.example.org/login"), new URI("https://op.example.org/token"), - new URI("https://op.example.org/userinfo")); + null); } - private RelyingPartyConfiguration getRpConfig() throws URISyntaxException { + private RelyingPartyConfiguration getDefaultRpConfig() throws URISyntaxException { return new RelyingPartyConfiguration( new ClientID("rp-my"), - new SecureString("mysecret".toCharArray()), + new SecureString("thisismysupersupersupersupersupersuperlongsecret".toCharArray()), new URI("https://rp.elastic.co/cb"), - new ResponseType("code"), + new ResponseType("id_token", "token"), new Scope("openid"), JWSAlgorithm.RS384); } + private RelyingPartyConfiguration getRpConfig(String alg) throws URISyntaxException { + return new RelyingPartyConfiguration( + new ClientID("rp-my"), + new SecureString("thisismysupersupersupersupersupersuperlongsecret".toCharArray()), + new URI("https://rp.elastic.co/cb"), + new ResponseType("id_token", "token"), + new Scope("openid"), + JWSAlgorithm.parse(alg)); + } + private RealmConfig buildConfig(Settings realmSettings) { final Settings settings = Settings.builder() .put("path.home", createTempDir()) @@ -114,4 +332,121 @@ private RealmConfig buildConfig(Settings realmSettings) { final Environment env = TestEnvironment.newEnvironment(settings); return new RealmConfig(new RealmConfig.RealmIdentifier("oidc", REALM_NAME), settings, env, threadContext); } + + private String buildResponseUrl(State state, Nonce nonce, Key key, String alg, String keyId, String subject, boolean withAccessToken, + boolean forged) + throws Exception { + AccessToken accessToken = null; + RelyingPartyConfiguration rpConfig = getRpConfig(alg); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + JWTClaimsSet.Builder idTokenBuilder = new JWTClaimsSet.Builder() + .jwtID(randomAlphaOfLength(8)) + .audience(rpConfig.getClientId().getValue()) + .expirationTime(Date.from(now().plusSeconds(3600))) + .issuer(opConfig.getIssuer().getValue()) + .issueTime(Date.from(now().minusSeconds(4))) + .notBeforeTime(Date.from(now().minusSeconds(4))) + .claim("nonce", nonce) + .subject(subject); + + if (withAccessToken) { + accessToken = new BearerAccessToken(Base64.getUrlEncoder().encodeToString(randomByteArrayOfLength(32))); + AccessTokenHash expectedHash = AccessTokenHash.compute(accessToken, JWSAlgorithm.parse(alg)); + idTokenBuilder.claim("at_hash", expectedHash.getValue()); + } + + SignedJWT jwt = new SignedJWT( + new JWSHeader.Builder(JWSAlgorithm.parse(alg)).keyID(keyId).build(), + idTokenBuilder.build()); + + if (key instanceof RSAPrivateKey) { + jwt.sign(new RSASSASigner((PrivateKey) key)); + } else if (key instanceof ECPrivateKey) { + jwt.sign(new ECDSASigner((ECPrivateKey) key)); + } else if (key instanceof SecretKey) { + jwt.sign(new MACSigner((SecretKey) key)); + } + if (forged) { + // Change the sub claim to "attacker" + String[] serializedParts = jwt.serialize().split("\\."); + String legitimatePayload = new String(Base64.getUrlDecoder().decode(serializedParts[1]), StandardCharsets.UTF_8); + String forgedPayload = legitimatePayload.replace(subject, "attacker"); + String encodedForgedPayload = + Base64.getUrlEncoder().withoutPadding().encodeToString(forgedPayload.getBytes(StandardCharsets.UTF_8)); + String fordedTokenString = serializedParts[0] + "." + encodedForgedPayload + "." + serializedParts[2]; + jwt = SignedJWT.parse(fordedTokenString); + } + AuthenticationSuccessResponse response = new AuthenticationSuccessResponse( + rpConfig.getRedirectUri(), + null, + jwt, + accessToken, + state, + null, + null); + if (forged) { + + } + return response.toURI().toString(); + + } + + private Tuple getRandomJwkForType(String type) throws Exception { + JWK jwk; + Key key; + int hashSize; + if (type.equals("RS")) { + hashSize = randomFrom(256, 384, 512); + int keySize = randomFrom(2048, 4096); + KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); + gen.initialize(keySize); + KeyPair keyPair = gen.generateKeyPair(); + key = keyPair.getPrivate(); + jwk = new RSAKey.Builder((RSAPublicKey) keyPair.getPublic()) + .privateKey((RSAPrivateKey) keyPair.getPrivate()) + .keyUse(KeyUse.SIGNATURE) + .keyID(UUID.randomUUID().toString()) + .algorithm(JWSAlgorithm.parse(type + hashSize)) + .build(); + + } else if (type.equals("HS")) { + hashSize = randomFrom(256, 384); + SecretKeySpec hmacKey = new SecretKeySpec("thisismysupersupersupersupersupersuperlongsecret".getBytes(StandardCharsets.UTF_8), + "HmacSha" + hashSize); + //SecretKey hmacKey = KeyGenerator.getInstance("HmacSha" + hashSize).generateKey(); + key = hmacKey; + jwk = new OctetSequenceKey.Builder(hmacKey) + .keyID(UUID.randomUUID().toString()) + .algorithm(JWSAlgorithm.parse(type + hashSize)) + .build(); + + } else if (type.equals("ES")) { + hashSize = randomFrom(256, 384, 512); + ECKey.Curve curve = curveFromHashSize(hashSize); + KeyPairGenerator gen = KeyPairGenerator.getInstance("EC"); + gen.initialize(curve.toECParameterSpec()); + KeyPair keyPair = gen.generateKeyPair(); + key = keyPair.getPrivate(); + jwk = new ECKey.Builder(curve, (ECPublicKey) keyPair.getPublic()) + .privateKey((ECPrivateKey) keyPair.getPrivate()) + .algorithm(JWSAlgorithm.parse(type + hashSize)) + .build(); + } else { + throw new IllegalArgumentException("Invalid key type :" + type); + } + return new Tuple(key, new JWKSet(jwk)); + } + + private ECKey.Curve curveFromHashSize(int size) { + if (size == 256) { + return ECKey.Curve.P_256; + } else if (size == 384) { + return ECKey.Curve.P_384; + } else if (size == 512) { + return ECKey.Curve.P_521; + } else { + throw new IllegalArgumentException("Invalid hash size:" + size); + } + } + } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java index 23846db4de3d7..cc5728da71918 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java @@ -12,7 +12,6 @@ import org.elasticsearch.env.Environment; import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.core.security.action.oidc.OpenIdConnectPrepareAuthenticationResponse; import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings; import org.hamcrest.Matchers; @@ -21,7 +20,6 @@ import java.util.Arrays; import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey; -import static org.hamcrest.Matchers.equalTo; public class OpenIdConnectRealmSettingsTests extends ESTestCase { @@ -43,30 +41,30 @@ public void testIncorrectResponseTypeThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "hybrid"); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); - assertThat(exception.getMessage(), Matchers.containsString("[xpack.security.authc.realms.oidc.oidc1-realm.rp.response_type]." + - " Allowed values are [code, id_token]")); + assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, + OpenIdConnectRealmSettings.RP_RESPONSE_TYPE))); } public void testMissingAuthorizationEndpointThrowsError() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT))); @@ -76,7 +74,7 @@ public void testInvalidAuthorizationEndpointThrowsError() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "this is not a URI") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") @@ -84,7 +82,7 @@ public void testInvalidAuthorizationEndpointThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT))); @@ -94,14 +92,14 @@ public void testMissingTokenEndpointThrowsError() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT))); @@ -111,7 +109,7 @@ public void testInvalidTokenEndpointThrowsError() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "This is not a uri") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") @@ -119,7 +117,7 @@ public void testInvalidTokenEndpointThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT))); @@ -134,29 +132,11 @@ public void testMissingJwksUrlThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); - }); - assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL))); - } - - public void testInvalidJwksUrlThrowsError() { - final Settings.Builder settingsBuilder = Settings.builder() - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "this is not a url") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "This is not a uri") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + SettingsException exception = expectThrows(SettingsException.class, () -> { + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); assertThat(exception.getMessage(), - Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL))); + Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH))); } public void testMissingIssuerThrowsError() { @@ -164,13 +144,13 @@ public void testMissingIssuerThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER))); @@ -181,13 +161,13 @@ public void testMissingNameTypeThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME))); @@ -198,13 +178,13 @@ public void testMissingRedirectUriThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI))); @@ -216,12 +196,12 @@ public void testMissingClientIdThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID))); @@ -233,14 +213,14 @@ public void testMissingPrincipalClaimThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), Arrays.asList("openid", "scope1", "scope2")); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()))); @@ -252,7 +232,7 @@ public void testPatternWithoutSettingThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getPattern()), "^(.*)$") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") @@ -261,7 +241,7 @@ public void testPatternWithoutSettingThrowsError() { .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), Arrays.asList("openid", "scope1", "scope2")); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getClaim()))); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java index 20e7b8f9e3f3e..0d960a80105df 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java @@ -76,8 +76,8 @@ public void testAuthentication() throws Exception { AuthenticationResult result = authenticateWithOidc(roleMapper, notPopulateMetadata, false); assertThat(result.getUser().roles(), arrayContainingInAnyOrder("kibana_user", "role1")); if (notPopulateMetadata == false) { - assertThat(result.getUser().metadata().get("oidc_iss"), equalTo("https://op.company.org")); - assertThat(result.getUser().metadata().get("oidc_name"), equalTo("Clinton Barton")); + assertThat(result.getUser().metadata().get("oidc(iss)"), equalTo("https://op.company.org")); + assertThat(result.getUser().metadata().get("oidc(name)"), equalTo("Clinton Barton")); } } @@ -147,14 +147,15 @@ public void testBuilidingAuthenticationRequest() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), Arrays.asList("openid", "scope1", "scope2")); - final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), + null); final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(); final String state = response.getState(); final String nonce = response.getNonce(); @@ -170,12 +171,13 @@ public void testBuilidingAuthenticationRequestWithDefaultScope() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build())); + final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), + null); final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(); final String state = response.getState(); final String nonce = response.getNonce(); @@ -188,7 +190,6 @@ private AuthenticationResult authenticateWithOidc(UserRoleMapper roleMapper, boo throws Exception { final String principal = "324235435454"; - final MockLookupRealm lookupRealm = new MockLookupRealm( new RealmConfig(new RealmConfig.RealmIdentifier("mock", "mock_lookup"), globalSettings, env, threadContext)); final OpenIdConnectAuthenticator authenticator = mock(OpenIdConnectAuthenticator.class); @@ -257,7 +258,7 @@ private Settings.Builder getBasicRealmSettings() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.org/token") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") - .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_URL), "https://op.example.org/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.org/jwks.json") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.elastic.co/cb") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") From 05910d98154bb3bfb8d2e7bcfc1b4c84f38a1a7e Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Tue, 29 Jan 2019 13:25:45 +0200 Subject: [PATCH 06/20] Address Feedback - Make the calls to TokenEndpoint and UserInfoEndpoint asynchrously - Move IdTokenValidator to an instance variable --- .../oidc/OpenIdConnectRealmSettings.java | 28 +- ...nsportOpenIdConnectAuthenticateAction.java | 5 +- .../xpack/security/authc/InternalRealms.java | 15 +- .../oidc/OpenIdConnectAuthenticator.java | 570 ++++++++++++------ .../authc/oidc/OpenIdConnectRealm.java | 51 +- .../authc/oidc/OpenIdConnectToken.java | 12 +- .../authc/oidc/RelyingPartyConfiguration.java | 8 +- .../oidc/OpenIdConnectAuthenticatorTests.java | 279 ++++++--- .../oidc/OpenIdConnectRealmSettingsTests.java | 25 +- .../authc/oidc/OpenIdConnectRealmTests.java | 58 +- 10 files changed, 727 insertions(+), 324 deletions(-) diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java index d319e9e9d5e0f..4955530e65e12 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java @@ -29,6 +29,8 @@ public class OpenIdConnectRealmSettings { private OpenIdConnectRealmSettings() { } + private static final List signingAlgorithms = Collections.unmodifiableList( + Arrays.asList("HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "PS256", "PS384", "PS512")); public static final String TYPE = "oidc"; public static final Setting.AffixSetting RP_CLIENT_ID @@ -47,7 +49,7 @@ private OpenIdConnectRealmSettings() { public static final Setting.AffixSetting RP_RESPONSE_TYPE = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "rp.response_type", key -> Setting.simpleString(key, v -> { - List responseTypes = Arrays.asList("code", "id_token", "id_token, token"); + List responseTypes = Arrays.asList("code", "id_token", "id_token token"); if (responseTypes.contains(v) == false) { throw new IllegalArgumentException("Invalid value [" + v + "] for [" + key + "]. Allowed values are " + responseTypes + ""); } @@ -55,11 +57,9 @@ private OpenIdConnectRealmSettings() { public static final Setting.AffixSetting RP_SIGNATURE_VERIFICATION_ALGORITHM = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "rp.signature_verification_algorithm", key -> new Setting<>(key, "RS256", Function.identity(), v -> { - List sigAlgo = Arrays.asList("HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "ES256", "ES384", - "ES512", "PS256", "PS384", "PS512"); - if (sigAlgo.contains(v) == false) { + if (signingAlgorithms.contains(v) == false) { throw new IllegalArgumentException( - "Invalid value [" + v + "] for [" + key + "]. Allowed values are " + sigAlgo + "}]"); + "Invalid value [" + v + "] for [" + key + "]. Allowed values are " + signingAlgorithms + "}]"); } }, Setting.Property.NodeScope)); public static final Setting.AffixSetting> RP_REQUESTED_SCOPES = Setting.affixKeySetting( @@ -87,7 +87,7 @@ private OpenIdConnectRealmSettings() { } }, Setting.Property.NodeScope)); public static final Setting.AffixSetting OP_USERINFO_ENDPOINT - = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "op.token_endpoint", + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "op.userinfo_endpoint", key -> Setting.simpleString(key, v -> { try { new URI(v); @@ -98,8 +98,11 @@ private OpenIdConnectRealmSettings() { public static final Setting.AffixSetting OP_ISSUER = RealmSettings.simpleString(TYPE, "op.issuer", Setting.Property.NodeScope); public static final Setting.AffixSetting OP_JWKSET_PATH - = RealmSettings.simpleString(TYPE, "rp.jwkset_path", Setting.Property.NodeScope); + = RealmSettings.simpleString(TYPE, "op.jwkset_path", Setting.Property.NodeScope); + public static final Setting.AffixSetting ALLOWED_CLOCK_SKEW + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "allowed_clock_skew", + key -> Setting.timeSetting(key, TimeValue.timeValueSeconds(60), Setting.Property.NodeScope)); public static final Setting.AffixSetting POPULATE_USER_METADATA = Setting.affixKeySetting( RealmSettings.realmSettingPrefix(TYPE), "populate_user_metadata", key -> Setting.boolSetting(key, true, Setting.Property.NodeScope)); @@ -113,6 +116,12 @@ private OpenIdConnectRealmSettings() { public static final Setting.AffixSetting HTTP_SOCKET_TIMEOUT = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "http.socket_timeout", key -> Setting.timeSetting(key, DEFAULT_TIMEOUT, Setting.Property.NodeScope)); + public static final Setting.AffixSetting HTTP_MAX_CONNECTIONS + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "http.max_connections", + key -> Setting.intSetting(key, 200, Setting.Property.NodeScope)); + public static final Setting.AffixSetting HTTP_MAX_ENDPOINT_CONNECTIONS + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "http.max_endpoint_connections", + key -> Setting.intSetting(key, 200, Setting.Property.NodeScope)); public static final ClaimSetting PRINCIPAL_CLAIM = new ClaimSetting("principal"); public static final ClaimSetting GROUPS_CLAIM = new ClaimSetting("groups"); @@ -124,7 +133,8 @@ public static Set> getSettings() { final Set> set = Sets.newHashSet( RP_CLIENT_ID, RP_REDIRECT_URI, RP_RESPONSE_TYPE, RP_REQUESTED_SCOPES, RP_CLIENT_SECRET, RP_SIGNATURE_VERIFICATION_ALGORITHM, OP_NAME, OP_AUTHORIZATION_ENDPOINT, OP_TOKEN_ENDPOINT, OP_USERINFO_ENDPOINT, OP_ISSUER, OP_JWKSET_PATH, - HTTP_CONNECT_TIMEOUT, HTTP_CONNECTION_READ_TIMEOUT, HTTP_SOCKET_TIMEOUT); + HTTP_CONNECT_TIMEOUT, HTTP_CONNECTION_READ_TIMEOUT, HTTP_SOCKET_TIMEOUT, HTTP_MAX_CONNECTIONS, HTTP_MAX_ENDPOINT_CONNECTIONS, + ALLOWED_CLOCK_SKEW); set.addAll(DelegatedAuthorizationSettings.getSettings(TYPE)); set.addAll(RealmSettings.getStandardSettings(TYPE)); set.addAll(SSLConfigurationSettings.getRealmSettings(TYPE)); @@ -146,7 +156,7 @@ public static Set> getSettings() { *
  • An optional java pattern (regex) to apply to that claim value in order to extract the substring that should be used.
  • * * For example, the Elasticsearch User Principal could be configured to come from the OpenID Connect standard claim "email", - * and extract only the local-port of the user's email address (i.e. the name before the '@'). + * and extract only the local-part of the user's email address (i.e. the name before the '@'). * This class encapsulates those 2 settings. */ public static final class ClaimSetting { diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectAuthenticateAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectAuthenticateAction.java index 4f58fa7c6f72c..e5a76972b1288 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectAuthenticateAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectAuthenticateAction.java @@ -5,6 +5,8 @@ */ package org.elasticsearch.xpack.security.action.oidc; +import com.nimbusds.oauth2.sdk.id.State; +import com.nimbusds.openid.connect.sdk.Nonce; import org.apache.logging.log4j.message.ParameterizedMessage; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; @@ -49,7 +51,8 @@ public TransportOpenIdConnectAuthenticateAction(ThreadPool threadPool, Transport @Override protected void doExecute(Task task, OpenIdConnectAuthenticateRequest request, ActionListener listener) { - final OpenIdConnectToken token = new OpenIdConnectToken(request.getRedirectUri(), request.getState(), request.getNonce()); + final OpenIdConnectToken token = new OpenIdConnectToken(request.getRedirectUri(), new State(request.getState()), + new Nonce(request.getNonce())); final ThreadContext threadContext = threadPool.getThreadContext(); Authentication originatingAuthentication = Authentication.getAuthentication(threadContext); try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java index d8ce9316c117d..8c2c023d558d2 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java @@ -47,6 +47,7 @@ /** * Provides a single entry point into dealing with all standard XPack security {@link Realm realms}. * This class does not handle extensions. + * * @see Realms for the component that manages configured realms (including custom extension realms) */ public final class InternalRealms { @@ -55,15 +56,15 @@ public final class InternalRealms { * The list of all internal realm types, excluding {@link ReservedRealm#TYPE}. */ private static final Set XPACK_TYPES = Collections - .unmodifiableSet(Sets.newHashSet(NativeRealmSettings.TYPE, FileRealmSettings.TYPE, LdapRealmSettings.AD_TYPE, - LdapRealmSettings.LDAP_TYPE, PkiRealmSettings.TYPE, SamlRealmSettings.TYPE, KerberosRealmSettings.TYPE)); + .unmodifiableSet(Sets.newHashSet(NativeRealmSettings.TYPE, FileRealmSettings.TYPE, LdapRealmSettings.AD_TYPE, + LdapRealmSettings.LDAP_TYPE, PkiRealmSettings.TYPE, SamlRealmSettings.TYPE, KerberosRealmSettings.TYPE)); /** * The list of all standard realm types, which are those provided by x-pack and do not have extensive * interaction with third party sources */ private static final Set STANDARD_TYPES = Collections.unmodifiableSet(Sets.newHashSet(NativeRealmSettings.TYPE, - FileRealmSettings.TYPE, LdapRealmSettings.AD_TYPE, LdapRealmSettings.LDAP_TYPE, PkiRealmSettings.TYPE)); + FileRealmSettings.TYPE, LdapRealmSettings.AD_TYPE, LdapRealmSettings.LDAP_TYPE, PkiRealmSettings.TYPE)); /** * Determines whether type is an internal realm-type that is provided by x-pack, @@ -92,6 +93,7 @@ static boolean isStandardRealm(String type) { /** * Creates {@link Realm.Factory factories} for each internal realm type. * This excludes the {@link ReservedRealm}, as it cannot be created dynamically. + * * @return A map from realm-type to Factory */ public static Map getFactories(ThreadPool threadPool, ResourceWatcherService resourceWatcherService, @@ -107,13 +109,14 @@ public static Map getFactories(ThreadPool threadPool, Res return nativeRealm; }); map.put(LdapRealmSettings.AD_TYPE, config -> new LdapRealm(config, sslService, - resourceWatcherService, nativeRoleMappingStore, threadPool)); + resourceWatcherService, nativeRoleMappingStore, threadPool)); map.put(LdapRealmSettings.LDAP_TYPE, config -> new LdapRealm(config, - sslService, resourceWatcherService, nativeRoleMappingStore, threadPool)); + sslService, resourceWatcherService, nativeRoleMappingStore, threadPool)); map.put(PkiRealmSettings.TYPE, config -> new PkiRealm(config, resourceWatcherService, nativeRoleMappingStore)); map.put(SamlRealmSettings.TYPE, config -> SamlRealm.create(config, sslService, resourceWatcherService, nativeRoleMappingStore)); map.put(KerberosRealmSettings.TYPE, config -> new KerberosRealm(config, nativeRoleMappingStore, threadPool)); - map.put(OpenIdConnectRealmSettings.TYPE, config -> new OpenIdConnectRealm(config, sslService, nativeRoleMappingStore)); + map.put(OpenIdConnectRealmSettings.TYPE, config -> new OpenIdConnectRealm(config, sslService, nativeRoleMappingStore, + resourceWatcherService)); return Collections.unmodifiableMap(map); } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java index 88d81ec2da6a8..1ad30d4c9a757 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java @@ -5,59 +5,74 @@ */ package org.elasticsearch.xpack.security.authc.oidc; +import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.jwk.JWKSet; +import com.nimbusds.jose.proc.BadJOSEException; import com.nimbusds.jose.util.DefaultResourceRetriever; import com.nimbusds.jose.util.IOUtils; import com.nimbusds.jose.util.Resource; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.oauth2.sdk.AbstractRequest; import com.nimbusds.oauth2.sdk.AuthorizationCode; import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; -import com.nimbusds.oauth2.sdk.AuthorizationGrant; import com.nimbusds.oauth2.sdk.ErrorObject; import com.nimbusds.oauth2.sdk.TokenErrorResponse; -import com.nimbusds.oauth2.sdk.TokenRequest; -import com.nimbusds.oauth2.sdk.TokenResponse; -import com.nimbusds.oauth2.sdk.auth.ClientAuthentication; -import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic; import com.nimbusds.oauth2.sdk.auth.Secret; -import com.nimbusds.oauth2.sdk.http.HTTPRequest; -import com.nimbusds.oauth2.sdk.http.HTTPResponse; import com.nimbusds.oauth2.sdk.id.State; import com.nimbusds.oauth2.sdk.token.AccessToken; -import com.nimbusds.oauth2.sdk.token.BearerAccessToken; +import com.nimbusds.oauth2.sdk.token.BearerTokenError; +import com.nimbusds.oauth2.sdk.util.JSONObjectUtils; import com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse; import com.nimbusds.openid.connect.sdk.AuthenticationResponse; import com.nimbusds.openid.connect.sdk.AuthenticationResponseParser; import com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse; import com.nimbusds.openid.connect.sdk.Nonce; import com.nimbusds.openid.connect.sdk.OIDCTokenResponse; -import com.nimbusds.openid.connect.sdk.OIDCTokenResponseParser; -import com.nimbusds.openid.connect.sdk.UserInfoErrorResponse; -import com.nimbusds.openid.connect.sdk.UserInfoRequest; -import com.nimbusds.openid.connect.sdk.UserInfoResponse; -import com.nimbusds.openid.connect.sdk.UserInfoSuccessResponse; import com.nimbusds.openid.connect.sdk.claims.AccessTokenHash; import com.nimbusds.openid.connect.sdk.token.OIDCTokens; import com.nimbusds.openid.connect.sdk.validators.AccessTokenValidator; import com.nimbusds.openid.connect.sdk.validators.IDTokenValidator; import net.minidev.json.JSONObject; +import org.apache.commons.codec.Charsets; +import org.apache.http.Header; +import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.auth.AuthenticationException; +import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.concurrent.FutureCallback; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.entity.ContentType; +import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClients; +import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; +import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.util.EntityUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.message.ParameterizedMessage; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.SpecialPermission; +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.common.CheckedRunnable; +import org.elasticsearch.common.Strings; import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.collect.Tuple; +import org.elasticsearch.watcher.FileChangesListener; +import org.elasticsearch.watcher.FileWatcher; +import org.elasticsearch.watcher.ResourceWatcherService; import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.RealmSettings; import org.elasticsearch.xpack.core.ssl.SSLConfiguration; @@ -66,16 +81,26 @@ import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URL; +import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.security.AccessController; +import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.ALLOWED_CLOCK_SKEW; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.HTTP_CONNECT_TIMEOUT; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.HTTP_CONNECTION_READ_TIMEOUT; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.HTTP_MAX_CONNECTIONS; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.HTTP_MAX_ENDPOINT_CONNECTIONS; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.HTTP_SOCKET_TIMEOUT; /** @@ -89,92 +114,113 @@ public class OpenIdConnectAuthenticator { private final OpenIdConnectProviderConfiguration opConfig; private final RelyingPartyConfiguration rpConfig; private final SSLService sslService; - private final PrivilegedResourceRetriever privilegedResourceResolver; + private IDTokenValidator idTokenValidator; + private final CloseableHttpAsyncClient httpClient; + private final ResourceWatcherService watcherService; protected final Logger logger = LogManager.getLogger(getClass()); public OpenIdConnectAuthenticator(RealmConfig realmConfig, OpenIdConnectProviderConfiguration opConfig, - RelyingPartyConfiguration rpConfig, - SSLService sslService) { + RelyingPartyConfiguration rpConfig, SSLService sslService, ResourceWatcherService watcherService) { this.realmConfig = realmConfig; this.opConfig = opConfig; this.rpConfig = rpConfig; this.sslService = sslService; - this.privilegedResourceResolver = getPrivilegedResourceRetriever(); + this.httpClient = createHttpClient(); + this.idTokenValidator = createIdTokenValidator(getPrivilegedResourceRetriever()); + this.watcherService = watcherService; } // For testing OpenIdConnectAuthenticator(RealmConfig realmConfig, OpenIdConnectProviderConfiguration opConfig, RelyingPartyConfiguration rpConfig, - SSLService sslService, PrivilegedResourceRetriever resourceRetriever) { + SSLService sslService, IDTokenValidator idTokenValidator, ResourceWatcherService watcherService) { this.realmConfig = realmConfig; this.opConfig = opConfig; this.rpConfig = rpConfig; this.sslService = sslService; - this.privilegedResourceResolver = resourceRetriever; - } - - OpenIdConnectAuthenticator() { - this(null, null, null, null, null); + this.httpClient = createHttpClient(); + this.idTokenValidator = idTokenValidator; + this.watcherService = watcherService; } /** - * Processes an OpenID Connect Response to an Authentication Request that comes in the form of a URL with the necessary parameters, that - * is contained in the provided Token. If the response is valid, it returns a set of OpenID Connect claims that identify the - * authenticated user. If the UserInfo endpoint is specified in the configuration, we attempt to make a UserInfo request and add - * the returned claims. + * Processes an OpenID Connect Response to an Authentication Request that comes in the form of a URL with the necessary parameters, + * that is contained in the provided Token. If the response is valid, it calls the provided listener with a set of OpenID Connect + * claims that identify the authenticated user. If the UserInfo endpoint is specified in the configuration, we attempt to make a + * UserInfo request and add the returned claims to the Id Token claims. * - * @param token The OpenIdConnectToken to consume - * @return a {@link JWTClaimsSet} with the OP claims for the user - * @throws ElasticsearchSecurityException if the response is invalid in any way + * @param token The OpenIdConnectToken to consume + * @param listener The listener to notify with the resolved {@link JWTClaimsSet} */ - public JWTClaimsSet authenticate(OpenIdConnectToken token) { + public void authenticate(OpenIdConnectToken token, final ActionListener listener) { try { AuthenticationResponse authenticationResponse = AuthenticationResponseParser.parse(new URI(token.getRedirectUrl())); - Nonce expectedNonce = new Nonce(token.getNonce()); - State expectedState = new State(token.getState()); + final Nonce expectedNonce = token.getNonce(); + State expectedState = token.getState(); if (logger.isTraceEnabled()) { logger.trace("OpenID Connect Provider redirected user to [{}]. Expected Nonce is [{}] and expected State is [{}]", token.getRedirectUrl(), expectedNonce, expectedState); } if (authenticationResponse instanceof AuthenticationErrorResponse) { ErrorObject error = ((AuthenticationErrorResponse) authenticationResponse).getErrorObject(); - throw new ElasticsearchSecurityException("OpenID Connect Provider response indicates authentication failure." + - "Code=[{}], Description=[{}]", error.getCode(), error.getDescription()); + listener.onFailure(new ElasticsearchSecurityException("OpenID Connect Provider response indicates authentication failure" + + "Code=[{}], Description=[{}]", error.getCode(), error.getDescription())); } final AuthenticationSuccessResponse response = authenticationResponse.toSuccessResponse(); validateState(expectedState, response.getState()); validateResponseType(response); - JWT idToken; - AccessToken accessToken; if (rpConfig.getResponseType().impliesCodeFlow()) { final AuthorizationCode code = response.getAuthorizationCode(); - Tuple tokens = exchangeCodeForToken(code); - accessToken = tokens.v1(); - idToken = tokens.v2(); + exchangeCodeForToken(code, ActionListener.wrap(tokens -> { + final AccessToken accessToken = tokens.v1(); + final JWT idToken = tokens.v2(); + validateAccessToken(accessToken, idToken, true); + getUserClaims(accessToken, idToken, expectedNonce, listener); + }, listener::onFailure)); } else { - idToken = response.getIDToken(); - accessToken = response.getAccessToken(); + final JWT idToken = response.getIDToken(); + final AccessToken accessToken = response.getAccessToken(); + validateAccessToken(accessToken, idToken, false); + getUserClaims(accessToken, idToken, expectedNonce, listener); } - final JWTClaimsSet idTokenClaims = validateAndParseIdToken(idToken, expectedNonce); - if (opConfig.getUserinfoEndpoint() != null) { - validateAccessToken(accessToken, idToken, rpConfig.getResponseType().impliesCodeFlow()); - final JWTClaimsSet userInfoClaims = getUserInfo(accessToken); - final JSONObject combinedClaims = idTokenClaims.toJSONObject(); - combinedClaims.merge(userInfoClaims.toJSONObject()); - return (JWTClaimsSet.parse(combinedClaims)); - } else { - return idTokenClaims; - } - } catch (ElasticsearchSecurityException e) { // Don't wrap in a new ElasticsearchSecurityException - throw e; + listener.onFailure(e); } catch (Exception e) { - logger.debug("Failed to consume the OpenID connect response", e); - throw new ElasticsearchSecurityException("Failed to consume the OpenID connect response"); + listener.onFailure(new ElasticsearchSecurityException("Failed to consume the OpenID connect response. ", e)); } } + /** + * Collects all the user claims we can get for the authenticated user. This happens in two steps: + *
      + *
    • First we attempt to validate the Id Token we have received and get any claims it contains
    • + *
    • If the UserInfo endpoint is configured, we also attempt to get the user info response from there and parse the returned + * claims
    • + *
    + * + * @param accessToken The {@link AccessToken} that the OP has issued for this user + * @param idToken The {@link JWT} Id Token that the OP has issued for this user + * @param expectedNonce The nonce value we sent in the authentication request and should be contained in the Id Token + * @param claimsListener The listener to notify with the resolved {@link JWTClaimsSet} + */ + private void getUserClaims(AccessToken accessToken, JWT idToken, Nonce expectedNonce, ActionListener claimsListener) { + try { + JWTClaimsSet verifiedIdTokenClaims = idTokenValidator.validate(idToken, expectedNonce).toJWTClaimsSet(); + if (logger.isTraceEnabled()) { + logger.trace("Received and validated the Id Token for the user: [{}]", verifiedIdTokenClaims); + } + if (opConfig.getUserinfoEndpoint() != null) { + getAndCombineUserInfoClaims(accessToken, verifiedIdTokenClaims, claimsListener); + } else { + claimsListener.onResponse(verifiedIdTokenClaims); + } + } catch (com.nimbusds.oauth2.sdk.ParseException | JOSEException | BadJOSEException e) { + claimsListener.onFailure(new ElasticsearchSecurityException("Failed to parse or validate the ID Token", e)); + } + } + + /** * Validates an access token according to the * specification @@ -188,68 +234,35 @@ public JWTClaimsSet authenticate(OpenIdConnectToken token) { */ private void validateAccessToken(AccessToken accessToken, JWT idToken, boolean optional) { try { - // only "bearer" is defined in the specification but check just in case + // only "Bearer" is defined in the specification but check just in case if (accessToken.getType().toString().equals("Bearer") == false) { - logger.debug("Invalid access token type [{}], while [Bearer] was expected", accessToken.getType()); - throw new ElasticsearchSecurityException("Received a response with an invalid access token type"); + throw new ElasticsearchSecurityException("Invalid access token type [{}], while [Bearer] was expected", + accessToken.getType()); } String atHashValue = idToken.getJWTClaimsSet().getStringClaim("at_hash"); if (null == atHashValue && optional == false) { - logger.debug("Failed to verify access token. at_hash claim is missing from the ID Token"); - throw new ElasticsearchSecurityException("Failed to verify access token"); + throw new ElasticsearchSecurityException("Failed to verify access token. at_hash claim is missing from the ID Token"); } AccessTokenHash atHash = new AccessTokenHash(atHashValue); JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(idToken.getHeader().getAlgorithm().getName()); AccessTokenValidator.validate(accessToken, jwsAlgorithm, atHash); } catch (Exception e) { - logger.debug("Failed to verify access token.", e); - throw new ElasticsearchSecurityException("Failed to verify access token."); + throw new ElasticsearchSecurityException("Failed to verify access token.", e); } } /** - * Parses and validates an OpenID Connect Id Token to a set of claims + * Reads and parses a JWKSet from a file * - * @param idToken The Id Token to parse and validate - * @param expectedNonce The nonce that was generated in the beginning of this authentication attempt and was stored at the user's - * session with the facilitator - * @return a {@link JWTClaimsSet} with the OP claims that were contained in the Id Token + * @param jwkSetPath The path to the file that contains the JWKs as a string. + * @return the parsed {@link JWKSet} + * @throws ParseException if the file cannot be parsed + * @throws IOException if the file cannot be read */ @SuppressForbidden(reason = "uses toFile") - private JWTClaimsSet validateAndParseIdToken(JWT idToken, Nonce expectedNonce) { - Secret clientSecret = null; - try { - final IDTokenValidator validator; - final JWSAlgorithm requestedAlgorithm = rpConfig.getSignatureVerificationAlgorithm(); - if (JWSAlgorithm.Family.HMAC_SHA.contains(requestedAlgorithm)) { - clientSecret = new Secret(rpConfig.getClientSecret().toString()); - validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, clientSecret); - } else { - String jwkSetPath = opConfig.getJwkSetPath(); - if (jwkSetPath.startsWith("https://")) { - validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, - new URL(jwkSetPath), privilegedResourceResolver); - } else { - final Path path = realmConfig.env().configFile().resolve(jwkSetPath); - final JWKSet jwkSet = JWKSet.load(path.toFile()); - validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, jwkSet); - } - - } - JWTClaimsSet verifiedIdTokenClaims = validator.validate(idToken, expectedNonce).toJWTClaimsSet(); - if (logger.isTraceEnabled()) { - logger.trace("Received the Id Token for the user: [{}]", verifiedIdTokenClaims); - } - return verifiedIdTokenClaims; - - } catch (Exception e) { - logger.debug("Failed to parse or validate the ID Token. ", e); - throw new ElasticsearchSecurityException("Failed to parse or validate the ID Token", e); - } finally { - if (null != clientSecret) { - clientSecret.erase(); - } - } + private JWKSet readJwkSetFromFile(String jwkSetPath) throws IOException, ParseException { + final Path path = realmConfig.env().configFile().resolve(jwkSetPath); + return JWKSet.load(path.toFile()); } /** @@ -260,9 +273,9 @@ private JWTClaimsSet validateAndParseIdToken(JWT idToken, Nonce expectedNonce) { */ private void validateResponseType(AuthenticationSuccessResponse response) { if (rpConfig.getResponseType().equals(response.impliedResponseType()) == false) { - logger.debug("Unexpected response type [{}], while [{}] is configured", response.impliedResponseType(), - rpConfig.getResponseType()); - throw new ElasticsearchSecurityException("Received a response with an unexpected response type"); + throw new ElasticsearchSecurityException("Unexpected response type [{}], while [{}] is configured", + response.impliedResponseType(), rpConfig.getResponseType()); + } } @@ -274,109 +287,298 @@ private void validateResponseType(AuthenticationSuccessResponse response) { * @param state The state that was contained in the response */ private void validateState(State expectedState, State state) { - if (null == state || null == expectedState) { - logger.debug("Failed to validate the response, at least one of the stored [{}] or received [{}] values were empty. ", state, - expectedState); - throw new ElasticsearchSecurityException("Failed to validate the response, state parameter is missing."); + if (null == state) { + throw new ElasticsearchSecurityException("Failed to validate the response, the response did not contain a state parameter"); + } else if (null == expectedState) { + throw new ElasticsearchSecurityException("Failed to validate the response, the user's session did not contain a state " + + "parameter"); } else if (state.equals(expectedState) == false) { - logger.debug("Invalid state parameter [{}], while [{}] was expected", state, expectedState); - throw new ElasticsearchSecurityException("Received a response with an invalid state parameter."); + throw new ElasticsearchSecurityException("Invalid state parameter [{}], while [{}] was expected", state, expectedState); } } /** - * Wraps sending an {@link HTTPRequest} with the appropriate permissions and returns the associated {@link HTTPResponse} + * Attempts to make a request to the UserInfo Endpoint of the OpenID Connect provider */ - private HTTPResponse getResponse(HTTPRequest httpRequest) throws PrivilegedActionException { - SpecialPermission.check(); - return AccessController.doPrivileged((PrivilegedExceptionAction) httpRequest::send); + private void getAndCombineUserInfoClaims(AccessToken accessToken, JWTClaimsSet verifiedIdTokenClaims, + ActionListener claimsListener) { + try { + final HttpGet httpGet = new HttpGet(opConfig.getUserinfoEndpoint()); + httpGet.setHeader("Authorization", "Bearer " + accessToken.getValue()); + AccessController.doPrivileged((PrivilegedAction) () -> { + httpClient.execute(httpGet, new FutureCallback() { + @Override + public void completed(HttpResponse result) { + handleUserinfoResponse(result, verifiedIdTokenClaims, claimsListener); + } + + @Override + public void failed(Exception ex) { + claimsListener.onFailure(new ElasticsearchSecurityException("Failed to get claims from the Userinfo Endpoint.", + ex)); + } + + @Override + public void cancelled() { + claimsListener.onFailure( + new ElasticsearchSecurityException("Failed to get claims from the Userinfo Endpoint. Request was cancelled")); + } + }); + return null; + }); + } catch (Exception e) { + claimsListener.onFailure(new ElasticsearchSecurityException("Failed to get user information from the UserInfo endpoint.", e)); + } } /** - * Converts an {@link AbstractRequest} to a {@link HTTPRequest} setting the necessary TLS configuration and timeout parameters + * Handle the UserInfo Response from the OpenID Connect Provider. If successful, merge the returned claims with the claims + * of the Id Token and call the provided listener. */ - private HTTPRequest buildRequest(AbstractRequest request) { - final String sslKey = RealmSettings.realmSslPrefix(realmConfig.identifier()); - final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration(sslKey); - boolean isHostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); - final HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; - final HTTPRequest httpRequest = request.toHTTPRequest(); - httpRequest.setSSLSocketFactory(sslService.sslSocketFactory(sslConfiguration)); - httpRequest.setHostnameVerifier(verifier); - httpRequest.setConnectTimeout(Math.toIntExact(realmConfig.getSetting(HTTP_CONNECT_TIMEOUT).getMillis())); - httpRequest.setReadTimeout(Math.toIntExact(realmConfig.getSetting(HTTP_CONNECTION_READ_TIMEOUT).getSeconds())); - return httpRequest; + private void handleUserinfoResponse(HttpResponse httpResponse, JWTClaimsSet verifiedIdTokenClaims, + ActionListener claimsListener) { + try { + final HttpEntity entity = httpResponse.getEntity(); + final Header encodingHeader = entity.getContentEncoding(); + final Charset encoding = encodingHeader == null ? StandardCharsets.UTF_8 : Charsets.toCharset(encodingHeader.getValue()); + final Header contentHeader = entity.getContentType(); + if (httpResponse.getStatusLine().getStatusCode() == 200) { + final String contentAsString = EntityUtils.toString(entity, encoding); + if (ContentType.parse(contentHeader.getValue()).getMimeType().equals("application/json")) { + final JWTClaimsSet userInfoClaims = JWTClaimsSet.parse(contentAsString); + if (logger.isTraceEnabled()) { + logger.trace("Successfully retrieved user information: [{}]", userInfoClaims.toJSONObject().toJSONString()); + } + final JSONObject combinedClaims = verifiedIdTokenClaims.toJSONObject(); + combinedClaims.merge(userInfoClaims.toJSONObject()); + claimsListener.onResponse(JWTClaimsSet.parse(combinedClaims)); + } else if (ContentType.parse(contentHeader.getValue()).getMimeType().equals("application/jwt")) { + //TODO Handle validating possibly signed responses + claimsListener.onFailure(new IllegalStateException("Unable to parse Userinfo Response. Signed/encryopted JWTs are" + + "not currently supported")); + } else { + claimsListener.onFailure(new IllegalStateException("Unable to parse Userinfo Response. Content type was expected to " + + "be [application/json] or [appliation/jwt] but was [" + contentHeader.getValue() + "]")); + } + } else { + final Header wwwAuthenticateHeader = httpResponse.getFirstHeader("WWW-Authenticate"); + if (Strings.hasText(wwwAuthenticateHeader.getValue())) { + BearerTokenError error = BearerTokenError.parse(wwwAuthenticateHeader.getValue()); + claimsListener.onFailure( + new ElasticsearchSecurityException("Failed to get user information from the UserInfo endpoint. Code=[{}], " + + "Description=[{}]", error.getCode(), error.getDescription())); + } else { + claimsListener.onFailure( + new ElasticsearchSecurityException("Failed to get user information from the UserInfo endpoint. Code=[{}], " + + "Description=[{}]", httpResponse.getStatusLine().getStatusCode(), + httpResponse.getStatusLine().getReasonPhrase())); + } + } + } catch (IOException | com.nimbusds.oauth2.sdk.ParseException | ParseException e) { + claimsListener.onFailure(new ElasticsearchSecurityException("Failed to get user information from the UserInfo endpoint.", + e)); + } } /** - * Completes the Authorization Code Grant authentication flow of OpenId Connect by exchanging the received - * authorization code for an Id Token and an access token. - * - * @param code the authorization code that was received as a response to the authentication request - * @return a {@link Tuple} containing the received (yet not validated) {@link AccessToken} and {@link JWT} + * Attempts to make a request to the Token Endpoint of the OpenID Connect provider in order to exchange an + * authorization code for an Id Token (and potentially an Access Token) */ - private Tuple exchangeCodeForToken(AuthorizationCode code) { - Secret clientSecret = null; + private void exchangeCodeForToken(AuthorizationCode code, ActionListener> tokensListener) { try { - clientSecret = new Secret(rpConfig.getClientSecret().toString()); - final ClientAuthentication clientAuth = new ClientSecretBasic(rpConfig.getClientId(), clientSecret); - final AuthorizationGrant codeGrant = new AuthorizationCodeGrant(code, rpConfig.getRedirectUri()); - final TokenRequest tokenRequest = new TokenRequest(opConfig.getTokenEndpoint(), clientAuth, codeGrant); - final HTTPResponse httpResponse = getResponse(buildRequest(tokenRequest)); - final TokenResponse tokenResponse = OIDCTokenResponseParser.parse(httpResponse); - if (tokenResponse.indicatesSuccess() == false) { - TokenErrorResponse errorResponse = (TokenErrorResponse) tokenResponse; - logger.debug("Failed to exchange code for Id Token. Code=[{}], Description=[{}]", - errorResponse.getErrorObject().getCode(), errorResponse.getErrorObject().getDescription()); - throw new ElasticsearchSecurityException("Failed to exchange code for Id Token."); + final AuthorizationCodeGrant codeGrant = new AuthorizationCodeGrant(code, rpConfig.getRedirectUri()); + final HttpPost httpPost = new HttpPost(opConfig.getTokenEndpoint()); + final List params = new ArrayList<>(); + for (Map.Entry> entry : codeGrant.toParameters().entrySet()) { + // All parameters of AuthorizationCodeGrant are singleton lists + params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().get(0))); } - OIDCTokenResponse successResponse = (OIDCTokenResponse) tokenResponse.toSuccessResponse(); - if (logger.isTraceEnabled()) { - logger.trace("Successfully exchanged code for ID Token: [{}]", successResponse.toJSONObject().toJSONString()); - } - final OIDCTokens oidcTokens = successResponse.getOIDCTokens(); - final AccessToken accessToken = oidcTokens.getAccessToken(); - final JWT idToken = oidcTokens.getIDToken(); - if (idToken == null) { - logger.debug("Failed to parse the received Id Token to a JWT"); - throw new ElasticsearchSecurityException("Failed to exchange code for Id Token."); + httpPost.setEntity(new UrlEncodedFormEntity(params)); + httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); + UsernamePasswordCredentials creds = new UsernamePasswordCredentials(rpConfig.getClientId().getValue(), + rpConfig.getClientSecret().toString()); + httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null)); + SpecialPermission.check(); + AccessController.doPrivileged((PrivilegedAction) () -> { + httpClient.execute(httpPost, new FutureCallback() { + @Override + public void completed(HttpResponse result) { + handleTokenResponse(result, tokensListener); + } + + @Override + public void failed(Exception ex) { + tokensListener.onFailure( + new ElasticsearchSecurityException("Failed to exchange code for Id Token using the Token Endpoint.", ex)); + } + + @Override + public void cancelled() { + final String message = "Failed to exchange code for Id Token using the Token Endpoint. Request was cancelled"; + tokensListener.onFailure(new ElasticsearchSecurityException(message)); + } + }); + return null; + }); + } catch (AuthenticationException | UnsupportedEncodingException e) { + tokensListener.onFailure( + new ElasticsearchSecurityException("Failed to exchange code for Id Token using the Token Endpoint.", e)); + } + } + + /** + * Handle the Token Response from the OpenID Connect Provider. If successful, extract the (yet not validated) Id Token + * and access token and call the provided listener. + */ + private void handleTokenResponse(HttpResponse httpResponse, ActionListener> tokensListener) { + try { + final HttpEntity entity = httpResponse.getEntity(); + final Header encodingHeader = entity.getContentEncoding(); + final Header contentHeader = entity.getContentType(); + if (ContentType.parse(contentHeader.getValue()).getMimeType().equals("application/json") == false) { + tokensListener.onFailure(new IllegalStateException("Unable to parse Token Response. Content type was expected to be " + + "[application/json] but was [" + contentHeader.getValue() + "]")); + return; } - return new Tuple<>(accessToken, idToken); - } catch (Exception e) { - logger.debug("Failed to exchange code for Id Token using the Token Endpoint. ", e); - throw new ElasticsearchSecurityException("Failed to exchange code for Id Token."); - } finally { - if (null != clientSecret) { - clientSecret.erase(); + final Charset encoding = encodingHeader == null ? StandardCharsets.UTF_8 : Charsets.toCharset(encodingHeader.getValue()); + final String json = EntityUtils.toString(entity, encoding); + final OIDCTokenResponse oidcTokenResponse = OIDCTokenResponse.parse(JSONObjectUtils.parse(json)); + if (oidcTokenResponse.indicatesSuccess() == false) { + TokenErrorResponse errorResponse = oidcTokenResponse.toErrorResponse(); + tokensListener.onFailure( + new ElasticsearchSecurityException("Failed to exchange code for Id Token. Code=[{}], Description=[{}]", + errorResponse.getErrorObject().getCode(), errorResponse.getErrorObject().getDescription())); + } else { + OIDCTokenResponse successResponse = oidcTokenResponse.toSuccessResponse(); + if (logger.isTraceEnabled()) { + logger.trace("Successfully exchanged code for ID Token: [{}]", successResponse.toJSONObject().toJSONString()); + } + final OIDCTokens oidcTokens = successResponse.getOIDCTokens(); + final AccessToken accessToken = oidcTokens.getAccessToken(); + final JWT idToken = oidcTokens.getIDToken(); + if (idToken == null) { + tokensListener.onFailure(new ElasticsearchSecurityException("Token Response did not contain an ID Token or parsing of" + + " the JWT failed.")); + return; + } + tokensListener.onResponse(new Tuple<>(accessToken, idToken)); } + } catch (IOException | com.nimbusds.oauth2.sdk.ParseException e) { + tokensListener.onFailure( + new ElasticsearchSecurityException("Failed to exchange code for Id Token using the Token Endpoint. " + + "Unable to parse Token Response", e)); } } /** - * Makes a request to the UserInfo Endpoint of the OP - * - * @param accessToken the access token to authenticate - * @return a {@link JWTClaimsSet} with the claims returned + * Creates a {@link CloseableHttpAsyncClient} that uses a {@link PoolingNHttpClientConnectionManager} */ - private JWTClaimsSet getUserInfo(AccessToken accessToken) { + private CloseableHttpAsyncClient createHttpClient() { try { - final BearerAccessToken bearerToken = new BearerAccessToken(accessToken.getValue()); - final UserInfoRequest userInfoRequest = new UserInfoRequest(opConfig.getUserinfoEndpoint(), bearerToken); - final UserInfoResponse response = UserInfoResponse.parse(getResponse(buildRequest(userInfoRequest))); - if (response.indicatesSuccess() == false) { - UserInfoErrorResponse errorResponse = response.toErrorResponse(); - logger.debug("Failed to get user information from the UserInfo endpoint. Code=[{}], " + - "Description=[{}]", errorResponse.getErrorObject().getCode(), errorResponse.getErrorObject().getDescription()); - throw new ElasticsearchSecurityException("Failed to get user information from the UserInfo endpoint"); + SpecialPermission.check(); + return AccessController.doPrivileged( + (PrivilegedExceptionAction) () -> { + ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); + PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor); + connectionManager.setDefaultMaxPerRoute(realmConfig.getSetting(HTTP_MAX_ENDPOINT_CONNECTIONS)); + connectionManager.setMaxTotal(realmConfig.getSetting(HTTP_MAX_CONNECTIONS)); + final String sslKey = RealmSettings.realmSslPrefix(realmConfig.identifier()); + final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration(sslKey); + final SSLContext clientContext = sslService.sslContext(sslConfiguration); + boolean isHostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); + final HostnameVerifier verifier = isHostnameVerificationEnabled ? + new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; + final RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(Math.toIntExact(realmConfig.getSetting(HTTP_CONNECT_TIMEOUT).getMillis())) + .setConnectionRequestTimeout(Math.toIntExact(realmConfig.getSetting(HTTP_CONNECTION_READ_TIMEOUT).getSeconds())) + .setSocketTimeout(Math.toIntExact(realmConfig.getSetting(HTTP_SOCKET_TIMEOUT).getMillis())).build(); + CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.custom() + .setConnectionManager(connectionManager) + .setSSLContext(clientContext) + .setSSLHostnameVerifier(verifier) + .setDefaultRequestConfig(requestConfig) + .build(); + httpAsyncClient.start(); + return httpAsyncClient; + }); + } catch (PrivilegedActionException e) { + throw new IllegalStateException("Unable to create a HttpAsyncClient instance", e); + } + } + + /* + * Creates an {@link IDTokenValidator} based on the current Relying Party configuration + */ + IDTokenValidator createIdTokenValidator(final PrivilegedResourceRetriever retriever) { + try { + final JWSAlgorithm requestedAlgorithm = rpConfig.getSignatureAlgorithm(); + final int allowedClockSkew = Math.toIntExact(realmConfig.getSetting(ALLOWED_CLOCK_SKEW).getMillis()); + final IDTokenValidator idTokenValidator; + if (JWSAlgorithm.Family.HMAC_SHA.contains(requestedAlgorithm)) { + final Secret clientSecret = new Secret(rpConfig.getClientSecret().toString()); + idTokenValidator = + new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, clientSecret); + } else { + String jwkSetPath = opConfig.getJwkSetPath(); + if (jwkSetPath.startsWith("https://")) { + idTokenValidator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), + requestedAlgorithm, new URL(jwkSetPath), retriever); + + } else { + setMetadataFileWatcher(jwkSetPath, retriever); + final JWKSet jwkSet = readJwkSetFromFile(jwkSetPath); + idTokenValidator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), requestedAlgorithm, jwkSet); + } } - UserInfoSuccessResponse successResponse = response.toSuccessResponse(); - if (logger.isTraceEnabled()) { - logger.trace("Successfully retrieved user information: [{}]", successResponse.getUserInfo().toJSONObject().toJSONString()); + idTokenValidator.setMaxClockSkew(allowedClockSkew); + return idTokenValidator; + } catch (IOException | ParseException e) { + throw new IllegalStateException("Unable to create a IDTokenValidator instance", e); + } + } + + private void setMetadataFileWatcher(String jwkSetPath, PrivilegedResourceRetriever resourceRetriever) throws IOException { + final Path path = realmConfig.env().configFile().resolve(jwkSetPath); + FileWatcher watcher = new FileWatcher(path); + watcher.addListener(new FileListener(logger, () -> this.idTokenValidator = createIdTokenValidator(resourceRetriever))); + watcherService.add(watcher, ResourceWatcherService.Frequency.MEDIUM); + } + + protected void close() { + try { + this.httpClient.close(); + } catch (IOException e) { + logger.debug("Unable to close the HttpAsyncClient", e); + } + } + + private static class FileListener implements FileChangesListener { + + private final Logger logger; + private final CheckedRunnable onChange; + + private FileListener(Logger logger, CheckedRunnable onChange) { + this.logger = logger; + this.onChange = onChange; + } + + @Override + public void onFileCreated(Path file) { + onFileChanged(file); + } + + @Override + public void onFileDeleted(Path file) { + onFileChanged(file); + } + + @Override + public void onFileChanged(Path file) { + try { + onChange.run(); + } catch (Exception e) { + logger.warn(new ParameterizedMessage("An error occurred while reloading file {}", file), e); } - return successResponse.getUserInfoJWT().getJWTClaimsSet(); - } catch (Exception e) { - logger.debug("FFailed to get user information from the UserInfo endpoint. ", e); - throw new ElasticsearchSecurityException("Failed to get user information from the UserInfo endpoint."); } } @@ -384,7 +586,7 @@ private JWTClaimsSet getUserInfo(AccessToken accessToken) { * Creates a new {@link PrivilegedResourceRetriever} to be used with the {@link IDTokenValidator} by passing the * necessary client SSLContext and hostname verification configuration */ - PrivilegedResourceRetriever getPrivilegedResourceRetriever() { + private PrivilegedResourceRetriever getPrivilegedResourceRetriever() { final String sslKey = RealmSettings.realmSslPrefix(realmConfig.identifier()); final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration(sslKey); boolean isHostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index 5a59fa31c5d5a..afeecfcea1bb9 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -8,6 +8,7 @@ import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.oauth2.sdk.ParseException; import com.nimbusds.oauth2.sdk.ResponseType; import com.nimbusds.oauth2.sdk.Scope; import com.nimbusds.oauth2.sdk.id.ClientID; @@ -17,13 +18,16 @@ import com.nimbusds.openid.connect.sdk.Nonce; import org.apache.logging.log4j.Logger; import org.elasticsearch.ElasticsearchException; +import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.Strings; +import org.elasticsearch.common.lease.Releasable; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.SettingsException; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.license.XPackLicenseState; +import org.elasticsearch.watcher.ResourceWatcherService; import org.elasticsearch.xpack.core.XPackSettings; import org.elasticsearch.xpack.core.security.action.oidc.OpenIdConnectPrepareAuthenticationResponse; import org.elasticsearch.xpack.core.security.authc.AuthenticationResult; @@ -72,7 +76,7 @@ import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_SIGNATURE_VERIFICATION_ALGORITHM; -public class OpenIdConnectRealm extends Realm { +public class OpenIdConnectRealm extends Realm implements Releasable { public static final String CONTEXT_TOKEN_DATA = "_oidc_tokendata"; private final OpenIdConnectProviderConfiguration opConfiguration; @@ -88,13 +92,14 @@ public class OpenIdConnectRealm extends Realm { private DelegatedAuthorizationSupport delegatedRealms; - - public OpenIdConnectRealm(RealmConfig config, SSLService sslService, UserRoleMapper roleMapper) { + public OpenIdConnectRealm(RealmConfig config, SSLService sslService, UserRoleMapper roleMapper, + ResourceWatcherService watcherService) { super(config); this.roleMapper = roleMapper; this.rpConfiguration = buildRelyingPartyConfiguration(config); this.opConfiguration = buildOpenIdConnectProviderConfiguration(config); - this.openIdConnectAuthenticator = new OpenIdConnectAuthenticator(config, opConfiguration, rpConfiguration, sslService); + this.openIdConnectAuthenticator = + new OpenIdConnectAuthenticator(config, opConfiguration, rpConfiguration, sslService, watcherService); this.principalAttribute = ClaimParser.forSetting(logger, PRINCIPAL_CLAIM, config, true); this.groupsAttribute = ClaimParser.forSetting(logger, GROUPS_CLAIM, config, false); this.dnAttribute = ClaimParser.forSetting(logger, DN_CLAIM, config, false); @@ -144,12 +149,16 @@ public AuthenticationToken token(ThreadContext context) { public void authenticate(AuthenticationToken token, ActionListener listener) { if (token instanceof OpenIdConnectToken) { OpenIdConnectToken oidcToken = (OpenIdConnectToken) token; - try { - JWTClaimsSet claims = openIdConnectAuthenticator.authenticate(oidcToken); - buildUserFromClaims(claims, listener); - } catch (ElasticsearchException e) { - listener.onResponse(AuthenticationResult.unsuccessful("Failed to authenticate user", e)); - } + openIdConnectAuthenticator.authenticate(oidcToken, ActionListener.wrap( + jwtClaimsSet -> buildUserFromClaims(jwtClaimsSet, listener), + e -> { + logger.debug("Failed to consume the OpenIdConnectToken ", e); + if (e instanceof ElasticsearchSecurityException) { + listener.onResponse(AuthenticationResult.unsuccessful("Failed to authenticate user with OpenID Connect", e)); + } else { + listener.onFailure(e); + } + })); } else { listener.onResponse(AuthenticationResult.notHandled()); } @@ -195,7 +204,7 @@ private void buildUserFromClaims(JWTClaimsSet claims, ActionListener { - final User user = new User(principal, roles.toArray(new String[0]), name, mail, userMetadata, true); + final User user = new User(principal, roles.toArray(Strings.EMPTY_ARRAY), name, mail, userMetadata, true); authResultListener.onResponse(AuthenticationResult.success(user)); }, authResultListener::onFailure)); @@ -213,8 +222,18 @@ private RelyingPartyConfiguration buildRelyingPartyConfiguration(RealmConfig con } final ClientID clientId = new ClientID(require(config, RP_CLIENT_ID)); final SecureString clientSecret = config.getSetting(RP_CLIENT_SECRET); - final ResponseType responseType = new ResponseType(require(config, RP_RESPONSE_TYPE)); - final Scope requestedScope = new Scope(config.getSetting(RP_REQUESTED_SCOPES).toArray(new String[0])); + final ResponseType responseType; + try { + // This should never happen as it's already validated in the settings + responseType = ResponseType.parse(require(config, RP_RESPONSE_TYPE)); + } catch (ParseException e) { + throw new SettingsException("Invalid value for " + RP_RESPONSE_TYPE.getKey(), e); + } + + final Scope requestedScope = new Scope(config.getSetting(RP_REQUESTED_SCOPES).toArray(Strings.EMPTY_ARRAY)); + if (requestedScope.contains("openid") == false) { + requestedScope.add("openid"); + } final JWSAlgorithm signatureVerificationAlgorithm = JWSAlgorithm.parse(require(config, RP_SIGNATURE_VERIFICATION_ALGORITHM)); return new RelyingPartyConfiguration(clientId, clientSecret, redirectUri, responseType, requestedScope, @@ -250,7 +269,6 @@ private OpenIdConnectProviderConfiguration buildOpenIdConnectProviderConfigurati throw new SettingsException("Invalid URI: " + OP_USERINFO_ENDPOINT.getKey(), e); } - return new OpenIdConnectProviderConfiguration(providerName, issuer, jwkSetUrl, authorizationEndpoint, tokenEndpoint, userinfoEndpoint); } @@ -287,6 +305,11 @@ public OpenIdConnectPrepareAuthenticationResponse buildAuthenticationRequestUri( state.getValue(), nonce.getValue()); } + @Override + public void close() { + openIdConnectAuthenticator.close(); + } + static final class ClaimParser { private final String name; private final Function> parser; diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java index ac5a686a88249..f29fd87a67666 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java @@ -5,6 +5,8 @@ */ package org.elasticsearch.xpack.security.authc.oidc; +import com.nimbusds.oauth2.sdk.id.State; +import com.nimbusds.openid.connect.sdk.Nonce; import org.elasticsearch.xpack.core.security.authc.AuthenticationToken; /** @@ -15,8 +17,8 @@ public class OpenIdConnectToken implements AuthenticationToken { private String redirectUrl; - private String state; - private String nonce; + private State state; + private Nonce nonce; /** * @param redirectUrl The URI where the OP redirected the browser after the authentication event at the OP. This is passed as is from @@ -27,7 +29,7 @@ public class OpenIdConnectToken implements AuthenticationToken { * @param nonce The nonce value that we generated for this specific flow and should be stored at the user's session with the * facilitator. */ - public OpenIdConnectToken(String redirectUrl, String state, String nonce) { + public OpenIdConnectToken(String redirectUrl, State state, Nonce nonce) { this.redirectUrl = redirectUrl; this.state = state; this.nonce = nonce; @@ -48,11 +50,11 @@ public void clearCredentials() { this.redirectUrl = null; } - public String getState() { + public State getState() { return state; } - public String getNonce() { + public Nonce getNonce() { return nonce; } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java index 18fa984d05dec..370a3e6866af8 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/RelyingPartyConfiguration.java @@ -23,7 +23,7 @@ public class RelyingPartyConfiguration { private final URI redirectUri; private final ResponseType responseType; private final Scope requestedScope; - private final JWSAlgorithm signatureVerificationAlgorithm; + private final JWSAlgorithm signatureAlgorithm; public RelyingPartyConfiguration(ClientID clientId, SecureString clientSecret, URI redirectUri, ResponseType responseType, Scope requestedScope, @@ -33,7 +33,7 @@ public RelyingPartyConfiguration(ClientID clientId, SecureString clientSecret, U this.redirectUri = Objects.requireNonNull(redirectUri, "redirectUri must be provided"); this.responseType = Objects.requireNonNull(responseType, "responseType must be provided"); this.requestedScope = Objects.requireNonNull(requestedScope, "responseType must be provided"); - this.signatureVerificationAlgorithm = Objects.requireNonNull(algorithm, "algorithm must be provided"); + this.signatureAlgorithm = Objects.requireNonNull(algorithm, "algorithm must be provided"); } public ClientID getClientId() { @@ -56,7 +56,7 @@ public Scope getRequestedScope() { return requestedScope; } - public JWSAlgorithm getSignatureVerificationAlgorithm() { - return signatureVerificationAlgorithm; + public JWSAlgorithm getSignatureAlgorithm() { + return signatureAlgorithm; } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java index 466069cce3e0e..2034756562ab8 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java @@ -23,6 +23,7 @@ import com.nimbusds.jwt.proc.BadJWTException; import com.nimbusds.oauth2.sdk.ResponseType; import com.nimbusds.oauth2.sdk.Scope; +import com.nimbusds.oauth2.sdk.auth.Secret; import com.nimbusds.oauth2.sdk.id.ClientID; import com.nimbusds.oauth2.sdk.id.Issuer; import com.nimbusds.oauth2.sdk.id.State; @@ -31,8 +32,9 @@ import com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse; import com.nimbusds.openid.connect.sdk.Nonce; import com.nimbusds.openid.connect.sdk.claims.AccessTokenHash; -import org.elasticsearch.ElasticsearchException; +import com.nimbusds.openid.connect.sdk.validators.IDTokenValidator; import org.elasticsearch.ElasticsearchSecurityException; +import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; @@ -43,12 +45,15 @@ import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings; import org.elasticsearch.xpack.core.ssl.SSLService; +import org.junit.After; import org.junit.Before; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; +import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; +import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.Key; import java.security.KeyPair; @@ -80,67 +85,94 @@ public class OpenIdConnectAuthenticatorTests extends ESTestCase { private ThreadContext threadContext; @Before - public void setup() throws Exception { + public void setup() { globalSettings = Settings.builder().put("path.home", createTempDir()) .put("xpack.security.authc.realms.oidc.oidc-realm.ssl.verification_mode", "certificate").build(); env = TestEnvironment.newEnvironment(globalSettings); threadContext = new ThreadContext(globalSettings); - authenticator = buildAuthenticator(); } + @After + public void cleanup() { + authenticator.close(); + } private OpenIdConnectAuthenticator buildAuthenticator() throws URISyntaxException { final RealmConfig config = buildConfig(getBasicRealmSettings().build()); - return new OpenIdConnectAuthenticator(config, getOpConfig(), getDefaultRpConfig(), new SSLService(globalSettings, env)); + return new OpenIdConnectAuthenticator(config, getOpConfig(), getDefaultRpConfig(), new SSLService(globalSettings, env), null); + } + + private OpenIdConnectAuthenticator buildAuthenticator(OpenIdConnectProviderConfiguration opConfig, RelyingPartyConfiguration rpConfig, + OpenIdConnectAuthenticator.PrivilegedResourceRetriever retriever) + throws MalformedURLException { + final RealmConfig config = buildConfig(getBasicRealmSettings().build()); + final IDTokenValidator validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), + rpConfig.getSignatureAlgorithm(), new URL(opConfig.getJwkSetPath()), retriever); + return new OpenIdConnectAuthenticator(config, opConfig, rpConfig, new SSLService(globalSettings, env), validator, + null); } private OpenIdConnectAuthenticator buildAuthenticator(OpenIdConnectProviderConfiguration opConfig, - RelyingPartyConfiguration rpConfig, - OpenIdConnectAuthenticator.PrivilegedResourceRetriever retriever) { + RelyingPartyConfiguration rpConfig) { final RealmConfig config = buildConfig(getBasicRealmSettings().build()); - return new OpenIdConnectAuthenticator(config, opConfig, rpConfig, new SSLService(globalSettings, env), retriever); + final IDTokenValidator validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), + rpConfig.getSignatureAlgorithm(), new Secret(rpConfig.getClientSecret().toString())); + return new OpenIdConnectAuthenticator(config, opConfig, rpConfig, new SSLService(globalSettings, env), validator, + null); } - public void testEmptyRedirectUrlIsRejected() { - OpenIdConnectToken token = new OpenIdConnectToken(null, randomAlphaOfLength(8), randomAlphaOfLength(8)); - ElasticsearchException e = expectThrows(ElasticsearchException.class, () -> { - authenticator.authenticate(token); - }); + public void testEmptyRedirectUrlIsRejected() throws Exception { + authenticator = buildAuthenticator(); + OpenIdConnectToken token = new OpenIdConnectToken(null, new State(), new Nonce()); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); assertThat(e.getMessage(), containsString("Failed to consume the OpenID connect response")); } - public void testInvalidStateIsRejected() { + public void testInvalidStateIsRejected() throws URISyntaxException { + authenticator = buildAuthenticator(); final String code = randomAlphaOfLengthBetween(8, 12); final String state = randomAlphaOfLengthBetween(8, 12); final String invalidState = state.concat(randomAlphaOfLength(2)); final String redirectUrl = "https://rp.elastic.co/cb?code=" + code + "&state=" + state; - OpenIdConnectToken token = new OpenIdConnectToken(redirectUrl, invalidState, randomAlphaOfLength(10)); - ElasticsearchException e = expectThrows(ElasticsearchException.class, () -> { - authenticator.authenticate(token); - }); - assertThat(e.getMessage(), containsString("Received a response with an invalid state parameter")); + OpenIdConnectToken token = new OpenIdConnectToken(redirectUrl, new State(invalidState), new Nonce()); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); + assertThat(e.getMessage(), containsString("Invalid state parameter")); } public void testInvalidNonceIsRejected() throws Exception { - final Tuple keyMaterial = getRandomJwkForType(randomFrom("ES", "RS", "HS")); + final Tuple keyMaterial = getRandomJwkForType(randomFrom("HS", "ES", "RS")); final JWK jwk = keyMaterial.v2().getKeys().get(0); final Key key = keyMaterial.v1(); RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); OpenIdConnectProviderConfiguration opConfig = getOpConfig(); - OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = - mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); - when(privilegedResourceRetriever.retrieveResource(any())) - .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); - authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + if (jwk.getAlgorithm().getName().startsWith("HS")) { + authenticator = buildAuthenticator(opConfig, rpConfig); + } else { + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + } final State state = new State(); final Nonce nonce = new Nonce(); final Nonce invalidNonce = new Nonce(); final String subject = "janedoe"; final String keyId = (jwk.getAlgorithm().getName().startsWith("HS")) ? null : jwk.getKeyID(); - final String responseUrl = buildResponseUrl(state, invalidNonce, key, jwk.getAlgorithm().getName(), keyId, subject, true, false); - final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); - ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> authenticator.authenticate(token)); + final String responseUrl = + buildAndSignResponseUrl(state, invalidNonce, key, jwk.getAlgorithm().getName(), keyId, subject, true, false); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); assertThat(e.getCause(), instanceOf(BadJWTException.class)); assertThat(e.getCause().getMessage(), containsString("Unexpected JWT nonce")); @@ -161,9 +193,12 @@ public void testAuthenticateImplicitFlowWithRsa() throws Exception { final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, false); - final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); - JWTClaimsSet claimsSet = authenticator.authenticate(token); + final String responseUrl = + buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, false); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + JWTClaimsSet claimsSet = future.actionGet(); assertThat(claimsSet.getSubject(), equalTo(subject)); } @@ -182,9 +217,12 @@ public void testAuthenticateImplicitFlowWithEcdsa() throws Exception { final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, false); - final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); - JWTClaimsSet claimsSet = authenticator.authenticate(token); + final String responseUrl = + buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, false); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + JWTClaimsSet claimsSet = future.actionGet(); assertThat(claimsSet.getSubject(), equalTo(subject)); } @@ -195,21 +233,99 @@ public void testAuthenticateImplicitFlowWithHmac() throws Exception { RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); OpenIdConnectProviderConfiguration opConfig = getOpConfig(); - OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = - mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); - when(privilegedResourceRetriever.retrieveResource(any())) - .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); - authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + authenticator = buildAuthenticator(opConfig, rpConfig); + + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String responseUrl = + buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), null, subject, true, false); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + JWTClaimsSet claimsSet = future.actionGet(); + assertThat(claimsSet.getSubject(), equalTo(subject)); + } + public void testClockSkewIsHonored() throws Exception { + final Tuple keyMaterial = getRandomJwkForType(randomFrom("HS", "ES", "RS")); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + if (jwk.getAlgorithm().getName().startsWith("HS")) { + authenticator = buildAuthenticator(opConfig, rpConfig); + } else { + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + } final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), null, subject, true, false); - final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); - JWTClaimsSet claimsSet = authenticator.authenticate(token); + final String keyId = (jwk.getAlgorithm().getName().startsWith("HS")) ? null : jwk.getKeyID(); + JWTClaimsSet.Builder idTokenBuilder = new JWTClaimsSet.Builder() + .jwtID(randomAlphaOfLength(8)) + .audience(rpConfig.getClientId().getValue()) + // Expired 55 seconds ago with an allowed clock skew of 60 seconds + .expirationTime(Date.from(now().minusSeconds(55))) + .issuer(opConfig.getIssuer().getValue()) + .issueTime(Date.from(now().minusSeconds(200))) + .notBeforeTime(Date.from(now().minusSeconds(60))) + .claim("nonce", nonce) + .subject(subject); + final String responseUrl = buildAndSignResponseUrl(idTokenBuilder.build(), state, key, jwk.getAlgorithm().getName(), keyId, + subject, true, false); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + JWTClaimsSet claimsSet = future.actionGet(); assertThat(claimsSet.getSubject(), equalTo(subject)); } + public void testImplicitFlowFailsWithExpiredToken() throws Exception { + final Tuple keyMaterial = getRandomJwkForType(randomFrom("HS", "ES", "RS")); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + if (jwk.getAlgorithm().getName().startsWith("HS")) { + authenticator = buildAuthenticator(opConfig, rpConfig); + } else { + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + } + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String keyId = (jwk.getAlgorithm().getName().startsWith("HS")) ? null : jwk.getKeyID(); + JWTClaimsSet.Builder idTokenBuilder = new JWTClaimsSet.Builder() + .jwtID(randomAlphaOfLength(8)) + .audience(rpConfig.getClientId().getValue()) + // Expired 61 seconds ago with an allowed clock skew of 60 seconds + .expirationTime(Date.from(now().minusSeconds(61))) + .issuer(opConfig.getIssuer().getValue()) + .issueTime(Date.from(now().minusSeconds(200))) + .notBeforeTime(Date.from(now().minusSeconds(80))) + .claim("nonce", nonce) + .subject(subject); + final String responseUrl = buildAndSignResponseUrl(idTokenBuilder.build(), state, key, jwk.getAlgorithm().getName(), keyId, + subject, true, false); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); + assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); + assertThat(e.getCause(), instanceOf(BadJWTException.class)); + assertThat(e.getCause().getMessage(), containsString("Expired JWT")); + } + public void testAuthenticateImplicitFlowFailsWithForgedRsaIdToken() throws Exception { final Tuple keyMaterial = getRandomJwkForType("RS"); final JWK jwk = keyMaterial.v2().getKeys().get(0); @@ -225,9 +341,13 @@ public void testAuthenticateImplicitFlowFailsWithForgedRsaIdToken() throws Excep final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, true); - final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); - ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> authenticator.authenticate(token)); + final String responseUrl = + buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, true); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); assertThat(e.getCause(), instanceOf(BadJWSException.class)); assertThat(e.getCause().getMessage(), containsString("Signed JWT rejected: Invalid signature")); @@ -248,9 +368,13 @@ public void testAuthenticateImplicitFlowFailsWithForgedEcsdsaIdToken() throws Ex final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, true); - final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); - ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> authenticator.authenticate(token)); + final String responseUrl = + buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, true); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); assertThat(e.getCause(), instanceOf(BadJWSException.class)); assertThat(e.getCause().getMessage(), containsString("Signed JWT rejected: Invalid signature")); @@ -262,18 +386,18 @@ public void testAuthenticateImplicitFlowFailsWithForgedHmacIdToken() throws Exce final Key key = keyMaterial.v1(); RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); OpenIdConnectProviderConfiguration opConfig = getOpConfig(); - OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = - mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); - when(privilegedResourceRetriever.retrieveResource(any())) - .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); - authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + authenticator = buildAuthenticator(opConfig, rpConfig); final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = buildResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), null, subject, true, true); - final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state.getValue(), nonce.getValue()); - ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> authenticator.authenticate(token)); + final String responseUrl = + buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), null, subject, true, true); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); assertThat(e.getCause(), instanceOf(BadJWSException.class)); assertThat(e.getCause().getMessage(), containsString("Signed JWT rejected: Invalid signature")); @@ -333,31 +457,17 @@ private RealmConfig buildConfig(Settings realmSettings) { return new RealmConfig(new RealmConfig.RealmIdentifier("oidc", REALM_NAME), settings, env, threadContext); } - private String buildResponseUrl(State state, Nonce nonce, Key key, String alg, String keyId, String subject, boolean withAccessToken, - boolean forged) - throws Exception { + private String buildAndSignResponseUrl(JWTClaimsSet idToken, State state, Key key, String alg, String keyId, + String subject, boolean withAccessToken, boolean forged) throws Exception { AccessToken accessToken = null; - RelyingPartyConfiguration rpConfig = getRpConfig(alg); - OpenIdConnectProviderConfiguration opConfig = getOpConfig(); - JWTClaimsSet.Builder idTokenBuilder = new JWTClaimsSet.Builder() - .jwtID(randomAlphaOfLength(8)) - .audience(rpConfig.getClientId().getValue()) - .expirationTime(Date.from(now().plusSeconds(3600))) - .issuer(opConfig.getIssuer().getValue()) - .issueTime(Date.from(now().minusSeconds(4))) - .notBeforeTime(Date.from(now().minusSeconds(4))) - .claim("nonce", nonce) - .subject(subject); - if (withAccessToken) { accessToken = new BearerAccessToken(Base64.getUrlEncoder().encodeToString(randomByteArrayOfLength(32))); AccessTokenHash expectedHash = AccessTokenHash.compute(accessToken, JWSAlgorithm.parse(alg)); - idTokenBuilder.claim("at_hash", expectedHash.getValue()); + idToken = JWTClaimsSet.parse(idToken.toJSONObject().appendField("at_hash", expectedHash.getValue())); } - SignedJWT jwt = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.parse(alg)).keyID(keyId).build(), - idTokenBuilder.build()); + idToken); if (key instanceof RSAPrivateKey) { jwt.sign(new RSASSASigner((PrivateKey) key)); @@ -376,6 +486,7 @@ private String buildResponseUrl(State state, Nonce nonce, Key key, String alg, S String fordedTokenString = serializedParts[0] + "." + encodedForgedPayload + "." + serializedParts[2]; jwt = SignedJWT.parse(fordedTokenString); } + RelyingPartyConfiguration rpConfig = getRpConfig(alg); AuthenticationSuccessResponse response = new AuthenticationSuccessResponse( rpConfig.getRedirectUri(), null, @@ -384,13 +495,29 @@ private String buildResponseUrl(State state, Nonce nonce, Key key, String alg, S state, null, null); - if (forged) { - - } return response.toURI().toString(); } + private String buildAndSignResponseUrl(State state, Nonce nonce, Key key, String alg, String keyId, String subject, + boolean withAccessToken, boolean forged) + throws Exception { + AccessToken accessToken = null; + RelyingPartyConfiguration rpConfig = getRpConfig(alg); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + JWTClaimsSet.Builder idTokenBuilder = new JWTClaimsSet.Builder() + .jwtID(randomAlphaOfLength(8)) + .audience(rpConfig.getClientId().getValue()) + .expirationTime(Date.from(now().plusSeconds(3600))) + .issuer(opConfig.getIssuer().getValue()) + .issueTime(Date.from(now().minusSeconds(4))) + .notBeforeTime(Date.from(now().minusSeconds(4))) + .claim("nonce", nonce) + .subject(subject); + + return buildAndSignResponseUrl(idTokenBuilder.build(), state, key, alg, keyId, subject, withAccessToken, forged); + } + private Tuple getRandomJwkForType(String type) throws Exception { JWK jwk; Key key; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java index cc5728da71918..917df50c89e61 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java @@ -31,7 +31,6 @@ public class OpenIdConnectRealmSettingsTests extends ESTestCase { @Before public void setupEnv() { globalSettings = Settings.builder().put("path.home", createTempDir()).build(); - env = TestEnvironment.newEnvironment(globalSettings); threadContext = new ThreadContext(globalSettings); } @@ -47,7 +46,7 @@ public void testIncorrectResponseTypeThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "hybrid"); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE))); @@ -64,7 +63,7 @@ public void testMissingAuthorizationEndpointThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT))); @@ -82,7 +81,7 @@ public void testInvalidAuthorizationEndpointThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT))); @@ -99,7 +98,7 @@ public void testMissingTokenEndpointThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT))); @@ -117,7 +116,7 @@ public void testInvalidTokenEndpointThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT))); @@ -133,7 +132,7 @@ public void testMissingJwksUrlThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH))); @@ -150,7 +149,7 @@ public void testMissingIssuerThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER))); @@ -167,7 +166,7 @@ public void testMissingNameTypeThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME))); @@ -184,7 +183,7 @@ public void testMissingRedirectUriThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI))); @@ -201,7 +200,7 @@ public void testMissingClientIdThrowsError() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID))); @@ -220,7 +219,7 @@ public void testMissingPrincipalClaimThrowsError() { .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), Arrays.asList("openid", "scope1", "scope2")); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()))); @@ -241,7 +240,7 @@ public void testPatternWithoutSettingThrowsError() { .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), Arrays.asList("openid", "scope1", "scope2")); SettingsException exception = expectThrows(SettingsException.class, () -> { - new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), null); + new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); }); assertThat(exception.getMessage(), Matchers.containsString(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.NAME_CLAIM.getClaim()))); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java index 0d960a80105df..15247b19e040b 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java @@ -6,6 +6,8 @@ package org.elasticsearch.xpack.security.authc.oidc; import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.oauth2.sdk.id.State; +import com.nimbusds.openid.connect.sdk.Nonce; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.common.settings.Settings; @@ -26,7 +28,6 @@ import org.elasticsearch.xpack.security.authc.support.UserRoleMapper; import org.hamcrest.Matchers; import org.junit.Before; -import org.mockito.Mockito; import java.util.Arrays; import java.util.Collections; @@ -43,6 +44,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -53,6 +55,7 @@ public class OpenIdConnectRealmTests extends ESTestCase { private ThreadContext threadContext; private static final String REALM_NAME = "oidc-realm"; + @Before public void setupEnv() { globalSettings = Settings.builder().put("path.home", createTempDir()).build(); @@ -63,7 +66,7 @@ public void setupEnv() { public void testAuthentication() throws Exception { final UserRoleMapper roleMapper = mock(UserRoleMapper.class); AtomicReference userData = new AtomicReference<>(); - Mockito.doAnswer(invocation -> { + doAnswer(invocation -> { assert invocation.getArguments().length == 2; userData.set((UserRoleMapper.UserData) invocation.getArguments()[0]); ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; @@ -83,7 +86,7 @@ public void testAuthentication() throws Exception { public void testWithAuthorizingRealm() throws Exception { final UserRoleMapper roleMapper = mock(UserRoleMapper.class); - Mockito.doAnswer(invocation -> { + doAnswer(invocation -> { assert invocation.getArguments().length == 2; ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; listener.onFailure(new RuntimeException("Role mapping should not be called")); @@ -114,15 +117,13 @@ public void testClaimPatternParsing() throws Exception { assertThat(parser.getClaimValue(claims), equalTo("cbarton")); } - public void testInvalidPrincipalClaimPatternParsing() throws Exception { + public void testInvalidPrincipalClaimPatternParsing() { final OpenIdConnectAuthenticator authenticator = mock(OpenIdConnectAuthenticator.class); - - final OpenIdConnectToken token = new OpenIdConnectToken("", "", ""); + final OpenIdConnectToken token = new OpenIdConnectToken("", new State(), new Nonce()); final Settings.Builder builder = getBasicRealmSettings(); builder.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getPattern()), "^OIDC-(.+)"); final RealmConfig config = buildConfig(builder.build()); final OpenIdConnectRealm realm = new OpenIdConnectRealm(config, authenticator, null); - final OpenIdConnectRealmSettings.ClaimSetting principalSetting = new OpenIdConnectRealmSettings.ClaimSetting("principal"); final JWTClaimsSet claims = new JWTClaimsSet.Builder() .subject("cbarton@avengers.com") .audience("https://rp.elastic.co/cb") @@ -131,7 +132,12 @@ public void testInvalidPrincipalClaimPatternParsing() throws Exception { .jwtID(randomAlphaOfLength(8)) .issuer("https://op.company.org") .build(); - when(authenticator.authenticate(token)).thenReturn(claims); + doAnswer((i) -> { + ActionListener listener = (ActionListener) i.getArguments()[1]; + listener.onResponse(claims); + return null; + }).when(authenticator).authenticate(any(OpenIdConnectToken.class), any(ActionListener.class)); + final PlainActionFuture future = new PlainActionFuture<>(); realm.authenticate(token, future); final AuthenticationResult result = future.actionGet(); @@ -141,6 +147,29 @@ public void testInvalidPrincipalClaimPatternParsing() throws Exception { assertThat(result.getMessage(), containsString("^OIDC-(.+)")); } + public void testBuildRelyingPartyConfigWithoutOpenIdScope() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") + .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), + Arrays.asList("scope1", "scope2")); + final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, + null); + final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(); + final String state = response.getState(); + final String nonce = response.getNonce(); + assertThat(response.getAuthenticationRequestUrl(), + equalTo("https://op.example.com/login?scope=scope1+scope2+openid&response_type=code" + + "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state=" + state + "&nonce=" + nonce + "&client_id=rp-my")); + } + public void testBuilidingAuthenticationRequest() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") @@ -154,7 +183,7 @@ public void testBuilidingAuthenticationRequest() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code") .putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), Arrays.asList("openid", "scope1", "scope2")); - final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), + final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(); final String state = response.getState(); @@ -176,7 +205,7 @@ public void testBuilidingAuthenticationRequestWithDefaultScope() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); - final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), new OpenIdConnectAuthenticator(), + final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(); final String state = response.getState(); @@ -208,7 +237,7 @@ private AuthenticationResult authenticateWithOidc(UserRoleMapper roleMapper, boo final RealmConfig config = buildConfig(builder.build()); final OpenIdConnectRealm realm = new OpenIdConnectRealm(config, authenticator, roleMapper); initializeRealms(realm, lookupRealm); - final OpenIdConnectToken token = new OpenIdConnectToken("", "", ""); + final OpenIdConnectToken token = new OpenIdConnectToken("", new State(), new Nonce()); final JWTClaimsSet claims = new JWTClaimsSet.Builder() .subject(principal) .audience("https://rp.elastic.co/cb") @@ -221,7 +250,12 @@ private AuthenticationResult authenticateWithOidc(UserRoleMapper roleMapper, boo .claim("name", "Clinton Barton") .build(); - when(authenticator.authenticate(token)).thenReturn(claims); + doAnswer((i) -> { + ActionListener listener = (ActionListener) i.getArguments()[1]; + listener.onResponse(claims); + return null; + }).when(authenticator).authenticate(any(OpenIdConnectToken.class), any(ActionListener.class)); + final PlainActionFuture future = new PlainActionFuture<>(); realm.authenticate(token, future); final AuthenticationResult result = future.get(); From b8aa5be2398c72e8ed86e2765c3cf0944b34d541 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Wed, 30 Jan 2019 10:26:52 +0200 Subject: [PATCH 07/20] Fix Access Token validation Access Token will not be returned in the implicit flow if the response type is set to "id_token" (as opposed to "id_token token") In such cases, there is no access token to validate and we cannot make requests to the UserInfo endpoint, even if the user has configured the Userinfo endpoint in the configuration --- .../oidc/OpenIdConnectRealmSettings.java | 2 +- .../oidc/OpenIdConnectAuthenticator.java | 60 +++++++++++-------- 2 files changed, 37 insertions(+), 25 deletions(-) diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java index 4955530e65e12..06ef9bde82af4 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java @@ -31,6 +31,7 @@ private OpenIdConnectRealmSettings() { private static final List signingAlgorithms = Collections.unmodifiableList( Arrays.asList("HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "PS256", "PS384", "PS512")); + private static final List responseTypes = Arrays.asList("code", "id_token", "id_token token"); public static final String TYPE = "oidc"; public static final Setting.AffixSetting RP_CLIENT_ID @@ -49,7 +50,6 @@ private OpenIdConnectRealmSettings() { public static final Setting.AffixSetting RP_RESPONSE_TYPE = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "rp.response_type", key -> Setting.simpleString(key, v -> { - List responseTypes = Arrays.asList("code", "id_token", "id_token token"); if (responseTypes.contains(v) == false) { throw new IllegalArgumentException("Invalid value [" + v + "] for [" + key + "]. Allowed values are " + responseTypes + ""); } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java index 1ad30d4c9a757..d7af96ba08b6e 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java @@ -17,6 +17,7 @@ import com.nimbusds.oauth2.sdk.AuthorizationCode; import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; import com.nimbusds.oauth2.sdk.ErrorObject; +import com.nimbusds.oauth2.sdk.ResponseType; import com.nimbusds.oauth2.sdk.TokenErrorResponse; import com.nimbusds.oauth2.sdk.auth.Secret; import com.nimbusds.oauth2.sdk.id.State; @@ -67,6 +68,7 @@ import org.elasticsearch.SpecialPermission; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.CheckedRunnable; +import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.collect.Tuple; @@ -174,13 +176,13 @@ public void authenticate(OpenIdConnectToken token, final ActionListener { final AccessToken accessToken = tokens.v1(); final JWT idToken = tokens.v2(); - validateAccessToken(accessToken, idToken, true); + validateAccessToken(accessToken, idToken); getUserClaims(accessToken, idToken, expectedNonce, listener); }, listener::onFailure)); } else { final JWT idToken = response.getIDToken(); final AccessToken accessToken = response.getAccessToken(); - validateAccessToken(accessToken, idToken, false); + validateAccessToken(accessToken, idToken); getUserClaims(accessToken, idToken, expectedNonce, listener); } } catch (ElasticsearchSecurityException e) { @@ -195,8 +197,8 @@ public void authenticate(OpenIdConnectToken token, final ActionListener *
  • First we attempt to validate the Id Token we have received and get any claims it contains
  • - *
  • If the UserInfo endpoint is configured, we also attempt to get the user info response from there and parse the returned - * claims
  • + *
  • If we have received an Access Token and the UserInfo endpoint is configured, we also attempt to get the user info response + * from there and parse the returned claims
  • * * * @param accessToken The {@link AccessToken} that the OP has issued for this user @@ -204,13 +206,13 @@ public void authenticate(OpenIdConnectToken token, final ActionListener claimsListener) { + private void getUserClaims(@Nullable AccessToken accessToken, JWT idToken, Nonce expectedNonce, ActionListener claimsListener) { try { JWTClaimsSet verifiedIdTokenClaims = idTokenValidator.validate(idToken, expectedNonce).toJWTClaimsSet(); if (logger.isTraceEnabled()) { logger.trace("Received and validated the Id Token for the user: [{}]", verifiedIdTokenClaims); } - if (opConfig.getUserinfoEndpoint() != null) { + if (accessToken != null && opConfig.getUserinfoEndpoint() != null) { getAndCombineUserInfoClaims(accessToken, verifiedIdTokenClaims, claimsListener); } else { claimsListener.onResponse(verifiedIdTokenClaims); @@ -223,29 +225,39 @@ private void getUserClaims(AccessToken accessToken, JWT idToken, Nonce expectedN /** * Validates an access token according to the - * specification + * specification. + *

    + * When using the authorization code flow the OP might not provide the at_hash parameter in the + * Id Token as allowed in the specification. In such a case we can't validate the access token + * but this is considered safe as it was received in a back channel communication that was protected + * by TLS. Also when using the implicit flow with the response type set to "id_token", no Access + * Token will be returned from the OP * - * @param accessToken The Access Token to validate + * @param accessToken The Access Token to validate. Can be null when the configured response type is "id_token" * @param idToken The Id Token that was received in the same response - * @param optional When using the authorization code flow the OP might not provide the at_hash parameter in the - * Id Token as allowed in the specification. In such a case we can't validate the access token - * but this is considered safe as it was received in a back channel communication that was protected - * by TLS. */ - private void validateAccessToken(AccessToken accessToken, JWT idToken, boolean optional) { + private void validateAccessToken(AccessToken accessToken, JWT idToken) { try { - // only "Bearer" is defined in the specification but check just in case - if (accessToken.getType().toString().equals("Bearer") == false) { - throw new ElasticsearchSecurityException("Invalid access token type [{}], while [Bearer] was expected", - accessToken.getType()); - } - String atHashValue = idToken.getJWTClaimsSet().getStringClaim("at_hash"); - if (null == atHashValue && optional == false) { - throw new ElasticsearchSecurityException("Failed to verify access token. at_hash claim is missing from the ID Token"); + if (rpConfig.getResponseType().equals(ResponseType.parse("id_token token")) || + rpConfig.getResponseType().equals(ResponseType.parse("code"))) { + assert (accessToken != null) : "Access Token cannot be null for Response Type " + rpConfig.getResponseType().toString(); + final boolean optional = rpConfig.getResponseType().equals(ResponseType.parse("code")); + // only "Bearer" is defined in the specification but check just in case + if (accessToken.getType().toString().equals("Bearer") == false) { + throw new ElasticsearchSecurityException("Invalid access token type [{}], while [Bearer] was expected", + accessToken.getType()); + } + String atHashValue = idToken.getJWTClaimsSet().getStringClaim("at_hash"); + if (null == atHashValue && optional == false) { + throw new ElasticsearchSecurityException("Failed to verify access token. at_hash claim is missing from the ID Token"); + } + AccessTokenHash atHash = new AccessTokenHash(atHashValue); + JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(idToken.getHeader().getAlgorithm().getName()); + AccessTokenValidator.validate(accessToken, jwsAlgorithm, atHash); + } else if (rpConfig.getResponseType().equals(ResponseType.parse("id_token")) && accessToken != null) { + // This should NOT happen and indicates a misconfigured OP. Warn the user but do not fail + logger.warn("Access Token incorrectly returned from the OpenId Connect Provider while using \"id_token\" response type."); } - AccessTokenHash atHash = new AccessTokenHash(atHashValue); - JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(idToken.getHeader().getAlgorithm().getName()); - AccessTokenValidator.validate(accessToken, jwsAlgorithm, atHash); } catch (Exception e) { throw new ElasticsearchSecurityException("Failed to verify access token.", e); } From e3204f5258d754dc9cc8fc38331d5a7109d6f1b7 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Wed, 30 Jan 2019 10:29:03 +0200 Subject: [PATCH 08/20] Completes security tests Our tests now handle all applicable known attacks. References: - https://www.nds.ruhr-uni-bochum.de/media/ei/veroeffentlichungen/2017/01/30/oidc-security.pdf - https://www.nds.ruhr-uni-bochum.de/media/ei/veroeffentlichungen/2017/01/13/OIDCSecurity_1.pdf - https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ --- .../oidc/OpenIdConnectAuthenticatorTests.java | 360 ++++++++++++++++-- 1 file changed, 323 insertions(+), 37 deletions(-) diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java index 2034756562ab8..cde58988dab08 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java @@ -16,9 +16,12 @@ import com.nimbusds.jose.jwk.KeyUse; import com.nimbusds.jose.jwk.OctetSequenceKey; import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jose.proc.BadJOSEException; import com.nimbusds.jose.proc.BadJWSException; import com.nimbusds.jose.util.Resource; +import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.PlainJWT; import com.nimbusds.jwt.SignedJWT; import com.nimbusds.jwt.proc.BadJWTException; import com.nimbusds.oauth2.sdk.ResponseType; @@ -33,8 +36,10 @@ import com.nimbusds.openid.connect.sdk.Nonce; import com.nimbusds.openid.connect.sdk.claims.AccessTokenHash; import com.nimbusds.openid.connect.sdk.validators.IDTokenValidator; +import com.nimbusds.openid.connect.sdk.validators.InvalidHashException; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.support.PlainActionFuture; +import org.elasticsearch.common.Nullable; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; @@ -166,8 +171,8 @@ public void testInvalidNonceIsRejected() throws Exception { final Nonce invalidNonce = new Nonce(); final String subject = "janedoe"; final String keyId = (jwk.getAlgorithm().getName().startsWith("HS")) ? null : jwk.getKeyID(); - final String responseUrl = - buildAndSignResponseUrl(state, invalidNonce, key, jwk.getAlgorithm().getName(), keyId, subject, true, false); + final Tuple tokens = buildTokens(invalidNonce, key, jwk.getAlgorithm().getName(), keyId, subject, true, false); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); final PlainActionFuture future = new PlainActionFuture<>(); authenticator.authenticate(token, future); @@ -193,8 +198,8 @@ public void testAuthenticateImplicitFlowWithRsa() throws Exception { final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = - buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, false); + final Tuple tokens = buildTokens(nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, false); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); final PlainActionFuture future = new PlainActionFuture<>(); authenticator.authenticate(token, future); @@ -217,8 +222,8 @@ public void testAuthenticateImplicitFlowWithEcdsa() throws Exception { final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = - buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, false); + final Tuple tokens = buildTokens(nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, false); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); final PlainActionFuture future = new PlainActionFuture<>(); authenticator.authenticate(token, future); @@ -238,8 +243,8 @@ public void testAuthenticateImplicitFlowWithHmac() throws Exception { final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = - buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), null, subject, true, false); + final Tuple tokens = buildTokens(nonce, key, jwk.getAlgorithm().getName(), null, subject, true, false); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); final PlainActionFuture future = new PlainActionFuture<>(); authenticator.authenticate(token, future); @@ -273,11 +278,12 @@ public void testClockSkewIsHonored() throws Exception { .expirationTime(Date.from(now().minusSeconds(55))) .issuer(opConfig.getIssuer().getValue()) .issueTime(Date.from(now().minusSeconds(200))) - .notBeforeTime(Date.from(now().minusSeconds(60))) + .notBeforeTime(Date.from(now().minusSeconds(200))) .claim("nonce", nonce) .subject(subject); - final String responseUrl = buildAndSignResponseUrl(idTokenBuilder.build(), state, key, jwk.getAlgorithm().getName(), keyId, - subject, true, false); + final Tuple tokens = buildTokens(idTokenBuilder.build(), key, jwk.getAlgorithm().getName(), keyId, subject, + true, false); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); final PlainActionFuture future = new PlainActionFuture<>(); authenticator.authenticate(token, future); @@ -311,11 +317,12 @@ public void testImplicitFlowFailsWithExpiredToken() throws Exception { .expirationTime(Date.from(now().minusSeconds(61))) .issuer(opConfig.getIssuer().getValue()) .issueTime(Date.from(now().minusSeconds(200))) - .notBeforeTime(Date.from(now().minusSeconds(80))) + .notBeforeTime(Date.from(now().minusSeconds(200))) .claim("nonce", nonce) .subject(subject); - final String responseUrl = buildAndSignResponseUrl(idTokenBuilder.build(), state, key, jwk.getAlgorithm().getName(), keyId, + final Tuple tokens = buildTokens(idTokenBuilder.build(), key, jwk.getAlgorithm().getName(), keyId, subject, true, false); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); final PlainActionFuture future = new PlainActionFuture<>(); authenticator.authenticate(token, future); @@ -326,6 +333,130 @@ public void testImplicitFlowFailsWithExpiredToken() throws Exception { assertThat(e.getCause().getMessage(), containsString("Expired JWT")); } + public void testImplicitFlowFailsNotYetIssuedToken() throws Exception { + final Tuple keyMaterial = getRandomJwkForType(randomFrom("HS", "ES", "RS")); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + if (jwk.getAlgorithm().getName().startsWith("HS")) { + authenticator = buildAuthenticator(opConfig, rpConfig); + } else { + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + } + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String keyId = (jwk.getAlgorithm().getName().startsWith("HS")) ? null : jwk.getKeyID(); + JWTClaimsSet.Builder idTokenBuilder = new JWTClaimsSet.Builder() + .jwtID(randomAlphaOfLength(8)) + .audience(rpConfig.getClientId().getValue()) + // Expired 61 seconds ago with an allowed clock skew of 60 seconds + .expirationTime(Date.from(now().plusSeconds(3600))) + .issuer(opConfig.getIssuer().getValue()) + .issueTime(Date.from(now().plusSeconds(61))) + .notBeforeTime(Date.from(now().minusSeconds(61))) + .claim("nonce", nonce) + .subject(subject); + final Tuple tokens = buildTokens(idTokenBuilder.build(), key, jwk.getAlgorithm().getName(), keyId, + subject, true, false); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); + assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); + assertThat(e.getCause(), instanceOf(BadJWTException.class)); + assertThat(e.getCause().getMessage(), containsString("JWT issue time ahead of current time")); + } + + public void testImplicitFlowFailsInvalidIssuer() throws Exception { + final Tuple keyMaterial = getRandomJwkForType(randomFrom("HS", "ES", "RS")); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + if (jwk.getAlgorithm().getName().startsWith("HS")) { + authenticator = buildAuthenticator(opConfig, rpConfig); + } else { + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + } + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String keyId = (jwk.getAlgorithm().getName().startsWith("HS")) ? null : jwk.getKeyID(); + JWTClaimsSet.Builder idTokenBuilder = new JWTClaimsSet.Builder() + .jwtID(randomAlphaOfLength(8)) + .audience(rpConfig.getClientId().getValue()) + .expirationTime(Date.from(now().plusSeconds(3600))) + .issuer("https://another.op.org") + .issueTime(Date.from(now().minusSeconds(200))) + .notBeforeTime(Date.from(now().minusSeconds(200))) + .claim("nonce", nonce) + .subject(subject); + final Tuple tokens = buildTokens(idTokenBuilder.build(), key, jwk.getAlgorithm().getName(), keyId, + subject, true, false); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); + assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); + assertThat(e.getCause(), instanceOf(BadJWTException.class)); + assertThat(e.getCause().getMessage(), containsString("Unexpected JWT issuer")); + } + + public void testImplicitFlowFailsInvalidAudience() throws Exception { + final Tuple keyMaterial = getRandomJwkForType(randomFrom("HS", "ES", "RS")); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + if (jwk.getAlgorithm().getName().startsWith("HS")) { + authenticator = buildAuthenticator(opConfig, rpConfig); + } else { + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + } + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String keyId = (jwk.getAlgorithm().getName().startsWith("HS")) ? null : jwk.getKeyID(); + JWTClaimsSet.Builder idTokenBuilder = new JWTClaimsSet.Builder() + .jwtID(randomAlphaOfLength(8)) + .audience("some-other-RP") + .expirationTime(Date.from(now().plusSeconds(3600))) + .issuer(opConfig.getIssuer().getValue()) + .issueTime(Date.from(now().minusSeconds(200))) + .notBeforeTime(Date.from(now().minusSeconds(80))) + .claim("nonce", nonce) + .subject(subject); + final Tuple tokens = buildTokens(idTokenBuilder.build(), key, jwk.getAlgorithm().getName(), keyId, + subject, true, false); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); + assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); + assertThat(e.getCause(), instanceOf(BadJWTException.class)); + assertThat(e.getCause().getMessage(), containsString("Unexpected JWT audience")); + } + public void testAuthenticateImplicitFlowFailsWithForgedRsaIdToken() throws Exception { final Tuple keyMaterial = getRandomJwkForType("RS"); final JWK jwk = keyMaterial.v2().getKeys().get(0); @@ -341,8 +472,8 @@ public void testAuthenticateImplicitFlowFailsWithForgedRsaIdToken() throws Excep final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = - buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, true); + final Tuple tokens = buildTokens(nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, true); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); final PlainActionFuture future = new PlainActionFuture<>(); authenticator.authenticate(token, future); @@ -368,8 +499,8 @@ public void testAuthenticateImplicitFlowFailsWithForgedEcsdsaIdToken() throws Ex final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = - buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, true); + final Tuple tokens = buildTokens(nonce, key, jwk.getAlgorithm().getName(), jwk.getKeyID(), subject, true, true); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); final PlainActionFuture future = new PlainActionFuture<>(); authenticator.authenticate(token, future); @@ -391,8 +522,8 @@ public void testAuthenticateImplicitFlowFailsWithForgedHmacIdToken() throws Exce final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; - final String responseUrl = - buildAndSignResponseUrl(state, nonce, key, jwk.getAlgorithm().getName(), null, subject, true, true); + final Tuple tokens = buildTokens(nonce, key, jwk.getAlgorithm().getName(), null, subject, true, true); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); final PlainActionFuture future = new PlainActionFuture<>(); authenticator.authenticate(token, future); @@ -403,6 +534,151 @@ public void testAuthenticateImplicitFlowFailsWithForgedHmacIdToken() throws Exce assertThat(e.getCause().getMessage(), containsString("Signed JWT rejected: Invalid signature")); } + public void testAuthenticateImplicitFlowFailsWithForgedAccessToken() throws Exception { + final Tuple keyMaterial = getRandomJwkForType(randomFrom("HS", "ES", "RS")); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + if (jwk.getAlgorithm().getName().startsWith("HS")) { + authenticator = buildAuthenticator(opConfig, rpConfig); + } else { + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + } + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String keyId = (jwk.getAlgorithm().getName().startsWith("HS")) ? null : jwk.getKeyID(); + final Tuple tokens = buildTokens(nonce, key, jwk.getAlgorithm().getName(), keyId, subject, true, false); + final String responseUrl = buildAuthResponse(tokens.v2(), new BearerAccessToken("someforgedAccessToken"), state, + rpConfig.getRedirectUri()); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); + assertThat(e.getMessage(), containsString("Failed to verify access token")); + assertThat(e.getCause(), instanceOf(InvalidHashException.class)); + assertThat(e.getCause().getMessage(), containsString("Access token hash (at_hash) mismatch")); + } + + public void testImplicitFlowFailsWithNoneAlgorithm() throws Exception { + final Tuple keyMaterial = getRandomJwkForType(randomFrom("HS", "ES", "RS")); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfigNoAccessToken(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + if (jwk.getAlgorithm().getName().startsWith("HS")) { + authenticator = buildAuthenticator(opConfig, rpConfig); + } else { + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + } + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + final String keyId = (jwk.getAlgorithm().getName().startsWith("HS")) ? null : jwk.getKeyID(); + final Tuple tokens = buildTokens(nonce, key, jwk.getAlgorithm().getName(), keyId, subject, false, false); + JWT idToken = tokens.v2(); + // Change the algorithm of the signed JWT to NONE + String[] serializedParts = idToken.serialize().split("\\."); + String legitimateHeader = new String(Base64.getUrlDecoder().decode(serializedParts[0]), StandardCharsets.UTF_8); + String forgedHeader = legitimateHeader.replace(jwk.getAlgorithm().getName(), "NONE"); + String encodedForgedHeader = + Base64.getUrlEncoder().withoutPadding().encodeToString(forgedHeader.getBytes(StandardCharsets.UTF_8)); + String fordedTokenString = encodedForgedHeader + "." + serializedParts[1] + "." + serializedParts[2]; + idToken = SignedJWT.parse(fordedTokenString); + final String responseUrl = buildAuthResponse(idToken, tokens.v1(), state, rpConfig.getRedirectUri()); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); + assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); + assertThat(e.getCause(), instanceOf(BadJOSEException.class)); + assertThat(e.getCause().getMessage(), containsString("Another algorithm expected, or no matching key(s) found")); + } + + /** + * The premise of this attack is that an RP that expects a JWT signed with an asymmetric algorithm (RSA, ECDSA) + * receives a JWT signed with an HMAC. Trusting the received JWT's alg claim more than it's own configuration, + * it attempts to validate the HMAC with the provider's {RSA,EC} public key as a secret key + */ + public void testImplicitFlowFailsWithAlgorithmMixupAttack() throws Exception { + final Tuple keyMaterial = getRandomJwkForType(randomFrom("ES", "RS")); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + final Key key = keyMaterial.v1(); + RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + SecretKeySpec hmacKey = new SecretKeySpec("thisismysupersupersupersupersupersuperlongsecret".getBytes(StandardCharsets.UTF_8), + "HmacSha384"); + final Tuple tokens = buildTokens(nonce, hmacKey, "HS384", null, subject, + true, false); + final String responseUrl = buildAuthResponse(tokens.v2(), tokens.v1(), state, rpConfig.getRedirectUri()); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); + assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); + assertThat(e.getCause(), instanceOf(BadJOSEException.class)); + assertThat(e.getCause().getMessage(), containsString("Another algorithm expected, or no matching key(s) found")); + } + + public void testImplicitFlowFailsWithUnsignedJwt() throws Exception { + final Tuple keyMaterial = getRandomJwkForType(randomFrom("HS", "ES", "RS")); + final JWK jwk = keyMaterial.v2().getKeys().get(0); + RelyingPartyConfiguration rpConfig = getRpConfigNoAccessToken(jwk.getAlgorithm().getName()); + OpenIdConnectProviderConfiguration opConfig = getOpConfig(); + if (jwk.getAlgorithm().getName().startsWith("HS")) { + authenticator = buildAuthenticator(opConfig, rpConfig); + } else { + OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = + mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); + when(privilegedResourceRetriever.retrieveResource(any())) + .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); + authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + } + final State state = new State(); + final Nonce nonce = new Nonce(); + final String subject = "janedoe"; + JWTClaimsSet.Builder idTokenBuilder = new JWTClaimsSet.Builder() + .jwtID(randomAlphaOfLength(8)) + .audience(rpConfig.getClientId().getValue()) + .expirationTime(Date.from(now().plusSeconds(3600))) + .issuer(opConfig.getIssuer().getValue()) + .issueTime(Date.from(now().minusSeconds(200))) + .notBeforeTime(Date.from(now().minusSeconds(200))) + .claim("nonce", nonce) + .subject(subject); + + final String responseUrl = buildAuthResponse(new PlainJWT(idTokenBuilder.build()), null, state, + rpConfig.getRedirectUri()); + final OpenIdConnectToken token = new OpenIdConnectToken(responseUrl, state, nonce); + final PlainActionFuture future = new PlainActionFuture<>(); + authenticator.authenticate(token, future); + ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, + future::actionGet); + assertThat(e.getMessage(), containsString("Failed to parse or validate the ID Token")); + assertThat(e.getCause(), instanceOf(BadJWTException.class)); + assertThat(e.getCause().getMessage(), containsString("Signed ID token expected")); + } + private Settings.Builder getBasicRealmSettings() { return Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.org/login") @@ -449,6 +725,16 @@ private RelyingPartyConfiguration getRpConfig(String alg) throws URISyntaxExcept JWSAlgorithm.parse(alg)); } + private RelyingPartyConfiguration getRpConfigNoAccessToken(String alg) throws URISyntaxException { + return new RelyingPartyConfiguration( + new ClientID("rp-my"), + new SecureString("thisismysupersupersupersupersupersuperlongsecret".toCharArray()), + new URI("https://rp.elastic.co/cb"), + new ResponseType("id_token"), + new Scope("openid"), + JWSAlgorithm.parse(alg)); + } + private RealmConfig buildConfig(Settings realmSettings) { final Settings settings = Settings.builder() .put("path.home", createTempDir()) @@ -457,8 +743,20 @@ private RealmConfig buildConfig(Settings realmSettings) { return new RealmConfig(new RealmConfig.RealmIdentifier("oidc", REALM_NAME), settings, env, threadContext); } - private String buildAndSignResponseUrl(JWTClaimsSet idToken, State state, Key key, String alg, String keyId, - String subject, boolean withAccessToken, boolean forged) throws Exception { + private String buildAuthResponse(JWT idToken, @Nullable AccessToken accessToken, State state, URI redirectUri) { + AuthenticationSuccessResponse response = new AuthenticationSuccessResponse( + redirectUri, + null, + idToken, + accessToken, + state, + null, + null); + return response.toURI().toString(); + } + + private Tuple buildTokens(JWTClaimsSet idToken, Key key, String alg, String keyId, + String subject, boolean withAccessToken, boolean forged) throws Exception { AccessToken accessToken = null; if (withAccessToken) { accessToken = new BearerAccessToken(Base64.getUrlEncoder().encodeToString(randomByteArrayOfLength(32))); @@ -486,23 +784,11 @@ private String buildAndSignResponseUrl(JWTClaimsSet idToken, State state, Key ke String fordedTokenString = serializedParts[0] + "." + encodedForgedPayload + "." + serializedParts[2]; jwt = SignedJWT.parse(fordedTokenString); } - RelyingPartyConfiguration rpConfig = getRpConfig(alg); - AuthenticationSuccessResponse response = new AuthenticationSuccessResponse( - rpConfig.getRedirectUri(), - null, - jwt, - accessToken, - state, - null, - null); - return response.toURI().toString(); - + return new Tuple<>(accessToken, jwt); } - private String buildAndSignResponseUrl(State state, Nonce nonce, Key key, String alg, String keyId, String subject, - boolean withAccessToken, boolean forged) - throws Exception { - AccessToken accessToken = null; + private Tuple buildTokens(Nonce nonce, Key key, String alg, String keyId, String subject, boolean withAccessToken, + boolean forged) throws Exception { RelyingPartyConfiguration rpConfig = getRpConfig(alg); OpenIdConnectProviderConfiguration opConfig = getOpConfig(); JWTClaimsSet.Builder idTokenBuilder = new JWTClaimsSet.Builder() @@ -515,7 +801,7 @@ private String buildAndSignResponseUrl(State state, Nonce nonce, Key key, String .claim("nonce", nonce) .subject(subject); - return buildAndSignResponseUrl(idTokenBuilder.build(), state, key, alg, keyId, subject, withAccessToken, forged); + return buildTokens(idTokenBuilder.build(), key, alg, keyId, subject, withAccessToken, forged); } private Tuple getRandomJwkForType(String type) throws Exception { From b3cbd8d97f734b16246a3f4dc3d5f1ae6fb884a2 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Wed, 30 Jan 2019 22:15:23 +0200 Subject: [PATCH 09/20] Fix checkstyle --- .../xpack/security/authc/oidc/OpenIdConnectAuthenticator.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java index d7af96ba08b6e..54f00c4fa4898 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java @@ -206,7 +206,8 @@ public void authenticate(OpenIdConnectToken token, final ActionListener claimsListener) { + private void getUserClaims(@Nullable AccessToken accessToken, JWT idToken, Nonce expectedNonce, + ActionListener claimsListener) { try { JWTClaimsSet verifiedIdTokenClaims = idTokenValidator.validate(idToken, expectedNonce).toJWTClaimsSet(); if (logger.isTraceEnabled()) { From 0a0ae0e47f0d29b7b764126e73d49f2aae57d6d7 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Fri, 1 Feb 2019 14:28:58 +0200 Subject: [PATCH 10/20] Make JWKSource reloading async --- x-pack/plugin/security/build.gradle | 2 +- .../security/forbidden/oidc-signatures.txt | 3 + .../oidc/OpenIdConnectAuthenticator.java | 176 ++++++++++++------ .../authc/oidc/OpenIdConnectRealm.java | 2 - .../oidc/OpenIdConnectAuthenticatorTests.java | 128 +++++-------- 5 files changed, 168 insertions(+), 143 deletions(-) create mode 100644 x-pack/plugin/security/forbidden/oidc-signatures.txt diff --git a/x-pack/plugin/security/build.gradle b/x-pack/plugin/security/build.gradle index 4857a66560edd..f5303857db4d7 100644 --- a/x-pack/plugin/security/build.gradle +++ b/x-pack/plugin/security/build.gradle @@ -170,7 +170,7 @@ forbiddenPatterns { } forbiddenApisMain { - signaturesFiles += files('forbidden/ldap-signatures.txt', 'forbidden/xml-signatures.txt') + signaturesFiles += files('forbidden/ldap-signatures.txt', 'forbidden/xml-signatures.txt', 'forbidden/oidc-signatures.txt') } // classes are missing, e.g. com.ibm.icu.lang.UCharacter diff --git a/x-pack/plugin/security/forbidden/oidc-signatures.txt b/x-pack/plugin/security/forbidden/oidc-signatures.txt new file mode 100644 index 0000000000000..05a2babdbe73c --- /dev/null +++ b/x-pack/plugin/security/forbidden/oidc-signatures.txt @@ -0,0 +1,3 @@ +@defaultMessage Blocking methods should not be used for HTTP requests. Use CloseableHttpAsyncClient instead +com.nimbusds.oauth2.sdk.http.HTTPRequest#send(javax.net.ssl.HostnameVerifier, javax.net.ssl.SSLSocketFactory) +com.nimbusds.oauth2.sdk.http.HTTPRequest#send() \ No newline at end of file diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java index 54f00c4fa4898..01c0b9f9a74c3 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java @@ -7,11 +7,14 @@ import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.jwk.JWK; +import com.nimbusds.jose.jwk.JWKSelector; import com.nimbusds.jose.jwk.JWKSet; +import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.BadJOSEException; -import com.nimbusds.jose.util.DefaultResourceRetriever; +import com.nimbusds.jose.proc.JWSVerificationKeySelector; +import com.nimbusds.jose.proc.SecurityContext; import com.nimbusds.jose.util.IOUtils; -import com.nimbusds.jose.util.Resource; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.oauth2.sdk.AuthorizationCode; @@ -51,15 +54,12 @@ import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.entity.ContentType; import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.message.BasicNameValuePair; import org.apache.http.nio.reactor.ConnectingIOReactor; -import org.apache.http.protocol.BasicHttpContext; import org.apache.http.util.EntityUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -72,6 +72,8 @@ import org.elasticsearch.common.Strings; import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.collect.Tuple; +import org.elasticsearch.common.util.concurrent.EsExecutors; +import org.elasticsearch.common.util.concurrent.ListenableFuture; import org.elasticsearch.watcher.FileChangesListener; import org.elasticsearch.watcher.FileWatcher; import org.elasticsearch.watcher.ResourceWatcherService; @@ -85,6 +87,7 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -97,6 +100,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.ALLOWED_CLOCK_SKEW; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.HTTP_CONNECT_TIMEOUT; @@ -129,7 +133,7 @@ public OpenIdConnectAuthenticator(RealmConfig realmConfig, OpenIdConnectProvider this.rpConfig = rpConfig; this.sslService = sslService; this.httpClient = createHttpClient(); - this.idTokenValidator = createIdTokenValidator(getPrivilegedResourceRetriever()); + this.idTokenValidator = createIdTokenValidator(); this.watcherService = watcherService; } @@ -167,6 +171,7 @@ public void authenticate(OpenIdConnectToken token, final ActionListener *

  • First we attempt to validate the Id Token we have received and get any claims it contains
  • *
  • If we have received an Access Token and the UserInfo endpoint is configured, we also attempt to get the user info response - * from there and parse the returned claims
  • + * from there and parse the returned claims, + * see {@link OpenIdConnectAuthenticator#getAndCombineUserInfoClaims(AccessToken, JWTClaimsSet, ActionListener)} * * * @param accessToken The {@link AccessToken} that the OP has issued for this user @@ -206,7 +212,7 @@ public void authenticate(OpenIdConnectToken token, final ActionListener claimsListener) { try { JWTClaimsSet verifiedIdTokenClaims = idTokenValidator.validate(idToken, expectedNonce).toJWTClaimsSet(); @@ -219,11 +225,26 @@ private void getUserClaims(@Nullable AccessToken accessToken, JWT idToken, Nonce claimsListener.onResponse(verifiedIdTokenClaims); } } catch (com.nimbusds.oauth2.sdk.ParseException | JOSEException | BadJOSEException e) { - claimsListener.onFailure(new ElasticsearchSecurityException("Failed to parse or validate the ID Token", e)); + // We only try to update the cached JWK set once if a remote source is used and + // RSA or ECDSA is used for signatures + if (shouldRetry + && JWSAlgorithm.Family.HMAC_SHA.contains(rpConfig.getSignatureAlgorithm()) == false + && e instanceof BadJOSEException + && "Signed JWT rejected: Another algorithm expected, or no matching key(s) found".equals(e.getMessage()) + && opConfig.getJwkSetPath().startsWith("https://")) { + ((ReloadableJWKSource) ((JWSVerificationKeySelector) idTokenValidator.getJWSKeySelector()).getJWKSource()) + .triggerReload(ActionListener.wrap(v -> { + getUserClaims(accessToken, idToken, expectedNonce, false, claimsListener); + }, ex -> { + logger.trace("Attempted and failed to refresh JWK cache upon token validation failure", e); + claimsListener.onFailure(ex); + })); + } else { + claimsListener.onFailure(new ElasticsearchSecurityException("Failed to parse or validate the ID Token", e)); + } } } - /** * Validates an access token according to the * specification. @@ -355,8 +376,12 @@ private void handleUserinfoResponse(HttpResponse httpResponse, JWTClaimsSet veri final Header encodingHeader = entity.getContentEncoding(); final Charset encoding = encodingHeader == null ? StandardCharsets.UTF_8 : Charsets.toCharset(encodingHeader.getValue()); final Header contentHeader = entity.getContentType(); + final String contentAsString = EntityUtils.toString(entity, encoding); + if (logger.isTraceEnabled()) { + logger.trace("Received UserInfo Response from OP with status [{}] and content [{}] ", + httpResponse.getStatusLine().getStatusCode(), contentAsString); + } if (httpResponse.getStatusLine().getStatusCode() == 200) { - final String contentAsString = EntityUtils.toString(entity, encoding); if (ContentType.parse(contentHeader.getValue()).getMimeType().equals("application/json")) { final JWTClaimsSet userInfoClaims = JWTClaimsSet.parse(contentAsString); if (logger.isTraceEnabled()) { @@ -455,6 +480,10 @@ private void handleTokenResponse(HttpResponse httpResponse, ActionListener this.idTokenValidator = createIdTokenValidator(resourceRetriever))); + watcher.addListener(new FileListener(logger, () -> this.idTokenValidator = createIdTokenValidator())); watcherService.add(watcher, ResourceWatcherService.Frequency.MEDIUM); } @@ -596,53 +626,77 @@ public void onFileChanged(Path file) { } /** - * Creates a new {@link PrivilegedResourceRetriever} to be used with the {@link IDTokenValidator} by passing the - * necessary client SSLContext and hostname verification configuration + * Remote JSON Web Key source specified by a JWKSet URL. The retrieved JWK set is cached to + * avoid unnecessary http requests. A single attempt to update the cached set is made + * (with {@ling ReloadableJWKSource#triggerReload}) when the {@link IDTokenValidator} fails + * to validate an ID Token (because of an unknown key) as this might mean that the OpenID + * Connect Provider has rotated the signing keys. */ - private PrivilegedResourceRetriever getPrivilegedResourceRetriever() { - final String sslKey = RealmSettings.realmSslPrefix(realmConfig.identifier()); - final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration(sslKey); - boolean isHostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); - final HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; - return new PrivilegedResourceRetriever(sslService.sslContext(sslConfiguration), verifier, realmConfig); - } + class ReloadableJWKSource implements JWKSource { - static class PrivilegedResourceRetriever extends DefaultResourceRetriever { - private SSLContext clientContext; - private HostnameVerifier verifier; - private RealmConfig config; + private volatile JWKSet cachedJwkSet = null; + private final AtomicReference> reloadFutureRef = new AtomicReference<>(); + private final URL jwkSetPath; - PrivilegedResourceRetriever(final SSLContext clientContext, final HostnameVerifier verifier, final RealmConfig config) { - super(); - this.clientContext = clientContext; - this.verifier = verifier; - this.config = config; + private ReloadableJWKSource(URL jwkSetPath) { + this.jwkSetPath = jwkSetPath; + triggerReload(ActionListener.wrap(success -> logger.trace("Successfully loaded and cached remote JWKSet on startup"), + failure -> logger.trace("Failed to load and cache remote JWKSet on startup", failure))); } @Override - public Resource retrieveResource(final URL url) throws IOException { - SpecialPermission.check(); + public List get(JWKSelector jwkSelector, C context) { + return jwkSelector.select(cachedJwkSet); + } + + void triggerReload(ActionListener toNotify) { + ListenableFuture future = reloadFutureRef.get(); + while (future == null) { + future = new ListenableFuture<>(); + if (reloadFutureRef.compareAndSet(null, future)) { + reloadAsync(future); + } else { + future = reloadFutureRef.get(); + } + } + future.addListener(toNotify, EsExecutors.newDirectExecutorService(), null); + } + + void reloadAsync(final ListenableFuture future) { try { - return AccessController.doPrivileged( - (PrivilegedExceptionAction) () -> { - final BasicHttpContext context = new BasicHttpContext(); - final RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(Math.toIntExact(config.getSetting(HTTP_CONNECT_TIMEOUT).getMillis())) - .setConnectionRequestTimeout(Math.toIntExact(config.getSetting(HTTP_CONNECTION_READ_TIMEOUT).getSeconds())) - .setSocketTimeout(Math.toIntExact(config.getSetting(HTTP_SOCKET_TIMEOUT).getMillis())).build(); - try (CloseableHttpClient client = HttpClients.custom() - .setSSLContext(clientContext) - .setSSLHostnameVerifier(verifier) - .setDefaultRequestConfig(requestConfig) - .build()) { - HttpGet get = new HttpGet(url.toURI()); - HttpResponse response = client.execute(get, context); - return new Resource(IOUtils.readInputStreamToString(response.getEntity().getContent(), - StandardCharsets.UTF_8), response.getEntity().getContentType().getValue()); + final HttpGet httpGet = new HttpGet(jwkSetPath.toURI()); + AccessController.doPrivileged((PrivilegedAction) () -> { + httpClient.execute(httpGet, new FutureCallback() { + @Override + public void completed(HttpResponse result) { + try { + cachedJwkSet = JWKSet.parse(IOUtils.readInputStreamToString(result.getEntity().getContent(), + StandardCharsets.UTF_8)); + reloadFutureRef.set(null); + logger.trace("Successfully refreshed and cached remote JWKSet"); + } catch (IOException | ParseException e) { + failed(e); + } + } + + @Override + public void failed(Exception ex) { + future.onFailure(new ElasticsearchSecurityException("Failed to retrieve remote JWK set.", ex)); + reloadFutureRef.set(null); + } + + @Override + public void cancelled() { + future.onFailure( + new ElasticsearchSecurityException("Failed to retrieve remote JWK set. Request was cancelled.")); + reloadFutureRef.set(null); } }); - } catch (final PrivilegedActionException e) { - throw (IOException) e.getCause(); + return null; + }); + } catch (URISyntaxException e) { + future.onFailure(e); + reloadFutureRef.set(null); } } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index afeecfcea1bb9..256db88ae5970 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -162,7 +162,6 @@ public void authenticate(AuthenticationToken token, ActionListener keyMaterial = getRandomJwkForType(randomFrom("HS", "ES", "RS")); + final Tuple keyMaterial = getRandomJwkForType(randomFrom("HS")); final JWK jwk = keyMaterial.v2().getKeys().get(0); final Key key = keyMaterial.v1(); RelyingPartyConfiguration rpConfig = getRpConfigNoAccessToken(jwk.getAlgorithm().getName()); @@ -575,11 +542,8 @@ public void testImplicitFlowFailsWithNoneAlgorithm() throws Exception { if (jwk.getAlgorithm().getName().startsWith("HS")) { authenticator = buildAuthenticator(opConfig, rpConfig); } else { - OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = - mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); - when(privilegedResourceRetriever.retrieveResource(any())) - .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); - authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); } final State state = new State(); final Nonce nonce = new Nonce(); @@ -614,14 +578,10 @@ public void testImplicitFlowFailsWithNoneAlgorithm() throws Exception { public void testImplicitFlowFailsWithAlgorithmMixupAttack() throws Exception { final Tuple keyMaterial = getRandomJwkForType(randomFrom("ES", "RS")); final JWK jwk = keyMaterial.v2().getKeys().get(0); - final Key key = keyMaterial.v1(); RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); OpenIdConnectProviderConfiguration opConfig = getOpConfig(); - OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = - mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); - when(privilegedResourceRetriever.retrieveResource(any())) - .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); - authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); final State state = new State(); final Nonce nonce = new Nonce(); final String subject = "janedoe"; @@ -648,11 +608,8 @@ public void testImplicitFlowFailsWithUnsignedJwt() throws Exception { if (jwk.getAlgorithm().getName().startsWith("HS")) { authenticator = buildAuthenticator(opConfig, rpConfig); } else { - OpenIdConnectAuthenticator.PrivilegedResourceRetriever privilegedResourceRetriever = - mock(OpenIdConnectAuthenticator.PrivilegedResourceRetriever.class); - when(privilegedResourceRetriever.retrieveResource(any())) - .thenReturn(new Resource(keyMaterial.v2().toString(), "application/json")); - authenticator = buildAuthenticator(opConfig, rpConfig, privilegedResourceRetriever); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); } final State state = new State(); final Nonce nonce = new Nonce(); @@ -755,6 +712,19 @@ private String buildAuthResponse(JWT idToken, @Nullable AccessToken accessToken, return response.toURI().toString(); } + private OpenIdConnectAuthenticator.ReloadableJWKSource mockSource(JWK jwk) { + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = + mock(OpenIdConnectAuthenticator.ReloadableJWKSource.class); + when(jwkSource.get(any(), any())).thenReturn(Collections.singletonList(jwk)); + Mockito.doAnswer(invocation -> { + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) invocation.getArguments()[0]; + listener.onResponse(null); + return null; + }).when(jwkSource).triggerReload(any(ActionListener.class)); + return jwkSource; + } + private Tuple buildTokens(JWTClaimsSet idToken, Key key, String alg, String keyId, String subject, boolean withAccessToken, boolean forged) throws Exception { AccessToken accessToken = null; From baadcdb496dc680670cbca0fad718bbf8717d0d3 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Fri, 1 Feb 2019 15:04:59 +0200 Subject: [PATCH 11/20] fix thirdPartyAudit --- x-pack/plugin/security/build.gradle | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/x-pack/plugin/security/build.gradle b/x-pack/plugin/security/build.gradle index f5303857db4d7..5912ad1b35080 100644 --- a/x-pack/plugin/security/build.gradle +++ b/x-pack/plugin/security/build.gradle @@ -268,12 +268,6 @@ thirdPartyAudit { 'net.sf.ehcache.Element', // [missing classes] SLF4j includes an optional class that depends on an extension class (!) 'org.slf4j.ext.EventData', - 'javax.activation.ActivationDataFlavor', - 'javax.activation.DataContentHandler', - 'javax.activation.DataHandler', - 'javax.activation.DataSource', - 'javax.activation.FileDataSource', - 'javax.activation.FileTypeMap', 'org.cryptomator.siv.SivMode', 'org.objectweb.asm.ClassWriter', 'org.objectweb.asm.Label', @@ -300,7 +294,13 @@ if (project.runtimeJavaVersion > JavaVersion.VERSION_1_8) { 'javax.xml.bind.JAXBElement', 'javax.xml.bind.JAXBException', 'javax.xml.bind.Unmarshaller', - 'javax.xml.bind.UnmarshallerHandler' + 'javax.xml.bind.UnmarshallerHandler', + 'javax.activation.ActivationDataFlavor', + 'javax.activation.DataContentHandler', + 'javax.activation.DataHandler', + 'javax.activation.DataSource', + 'javax.activation.FileDataSource', + 'javax.activation.FileTypeMap' ) } From 09413b500e6f5e93b3357566e9a331d0a1aee612 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Sat, 2 Feb 2019 00:22:27 +0200 Subject: [PATCH 12/20] address feedback --- .../security/authc/oidc/OpenIdConnectAuthenticator.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java index 01c0b9f9a74c3..70dfdb7a6fe5b 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java @@ -224,12 +224,11 @@ private void getUserClaims(@Nullable AccessToken accessToken, JWT idToken, Nonce } else { claimsListener.onResponse(verifiedIdTokenClaims); } - } catch (com.nimbusds.oauth2.sdk.ParseException | JOSEException | BadJOSEException e) { + } catch (BadJOSEException e) { // We only try to update the cached JWK set once if a remote source is used and // RSA or ECDSA is used for signatures if (shouldRetry && JWSAlgorithm.Family.HMAC_SHA.contains(rpConfig.getSignatureAlgorithm()) == false - && e instanceof BadJOSEException && "Signed JWT rejected: Another algorithm expected, or no matching key(s) found".equals(e.getMessage()) && opConfig.getJwkSetPath().startsWith("https://")) { ((ReloadableJWKSource) ((JWSVerificationKeySelector) idTokenValidator.getJWSKeySelector()).getJWKSource()) @@ -242,6 +241,8 @@ private void getUserClaims(@Nullable AccessToken accessToken, JWT idToken, Nonce } else { claimsListener.onFailure(new ElasticsearchSecurityException("Failed to parse or validate the ID Token", e)); } + } catch (com.nimbusds.oauth2.sdk.ParseException | JOSEException e) { + claimsListener.onFailure(new ElasticsearchSecurityException("Failed to parse or validate the ID Token", e)); } } @@ -634,7 +635,7 @@ public void onFileChanged(Path file) { */ class ReloadableJWKSource implements JWKSource { - private volatile JWKSet cachedJwkSet = null; + private volatile JWKSet cachedJwkSet = new JWKSet(); private final AtomicReference> reloadFutureRef = new AtomicReference<>(); private final URL jwkSetPath; From 59bc12244cad30cf74674243bc958b71c4ffc235 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Sat, 2 Feb 2019 12:56:27 +0200 Subject: [PATCH 13/20] cleanup --- .../authc/oidc/OpenIdConnectRealmSettings.java | 13 ++++++------- .../security/authc/oidc/OpenIdConnectRealm.java | 6 +++--- .../authc/oidc/OpenIdConnectRealmSettingsTests.java | 4 +--- 3 files changed, 10 insertions(+), 13 deletions(-) diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java index 06ef9bde82af4..ce944ae3d6fb2 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java @@ -29,7 +29,7 @@ public class OpenIdConnectRealmSettings { private OpenIdConnectRealmSettings() { } - private static final List signingAlgorithms = Collections.unmodifiableList( + private static final List signatureAlgorithms = Collections.unmodifiableList( Arrays.asList("HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "PS256", "PS384", "PS512")); private static final List responseTypes = Arrays.asList("code", "id_token", "id_token token"); public static final String TYPE = "oidc"; @@ -54,12 +54,12 @@ private OpenIdConnectRealmSettings() { throw new IllegalArgumentException("Invalid value [" + v + "] for [" + key + "]. Allowed values are " + responseTypes + ""); } }, Setting.Property.NodeScope)); - public static final Setting.AffixSetting RP_SIGNATURE_VERIFICATION_ALGORITHM - = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "rp.signature_verification_algorithm", + public static final Setting.AffixSetting RP_SIGNATURE_ALGORITHM + = Setting.affixKeySetting(RealmSettings.realmSettingPrefix(TYPE), "rp.signature_algorithm", key -> new Setting<>(key, "RS256", Function.identity(), v -> { - if (signingAlgorithms.contains(v) == false) { + if (signatureAlgorithms.contains(v) == false) { throw new IllegalArgumentException( - "Invalid value [" + v + "] for [" + key + "]. Allowed values are " + signingAlgorithms + "}]"); + "Invalid value [" + v + "] for [" + key + "]. Allowed values are " + signatureAlgorithms + "}]"); } }, Setting.Property.NodeScope)); public static final Setting.AffixSetting> RP_REQUESTED_SCOPES = Setting.affixKeySetting( @@ -131,7 +131,7 @@ private OpenIdConnectRealmSettings() { public static Set> getSettings() { final Set> set = Sets.newHashSet( - RP_CLIENT_ID, RP_REDIRECT_URI, RP_RESPONSE_TYPE, RP_REQUESTED_SCOPES, RP_CLIENT_SECRET, RP_SIGNATURE_VERIFICATION_ALGORITHM, + RP_CLIENT_ID, RP_REDIRECT_URI, RP_RESPONSE_TYPE, RP_REQUESTED_SCOPES, RP_CLIENT_SECRET, RP_SIGNATURE_ALGORITHM, OP_NAME, OP_AUTHORIZATION_ENDPOINT, OP_TOKEN_ENDPOINT, OP_USERINFO_ENDPOINT, OP_ISSUER, OP_JWKSET_PATH, HTTP_CONNECT_TIMEOUT, HTTP_CONNECTION_READ_TIMEOUT, HTTP_SOCKET_TIMEOUT, HTTP_MAX_CONNECTIONS, HTTP_MAX_ENDPOINT_CONNECTIONS, ALLOWED_CLOCK_SKEW); @@ -146,7 +146,6 @@ public static Set> getSettings() { return set; } - /** * The OIDC realm offers a number of settings that rely on claim values that are populated by the OP in the ID Token or the User Info * response. diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index 256db88ae5970..4f2d3f7cc20ce 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -74,7 +74,7 @@ import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_REDIRECT_URI; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_RESPONSE_TYPE; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES; -import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_SIGNATURE_VERIFICATION_ALGORITHM; +import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.RP_SIGNATURE_ALGORITHM; public class OpenIdConnectRealm extends Realm implements Releasable { @@ -232,10 +232,10 @@ private RelyingPartyConfiguration buildRelyingPartyConfiguration(RealmConfig con if (requestedScope.contains("openid") == false) { requestedScope.add("openid"); } - final JWSAlgorithm signatureVerificationAlgorithm = JWSAlgorithm.parse(require(config, RP_SIGNATURE_VERIFICATION_ALGORITHM)); + final JWSAlgorithm signatureAlgorithm = JWSAlgorithm.parse(require(config, RP_SIGNATURE_ALGORITHM)); return new RelyingPartyConfiguration(clientId, clientSecret, redirectUri, responseType, requestedScope, - signatureVerificationAlgorithm); + signatureAlgorithm); } private OpenIdConnectProviderConfiguration buildOpenIdConnectProviderConfiguration(RealmConfig config) { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java index 917df50c89e61..cd92168b3aa95 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmSettingsTests.java @@ -24,13 +24,11 @@ public class OpenIdConnectRealmSettingsTests extends ESTestCase { private static final String REALM_NAME = "oidc1-realm"; - private Settings globalSettings; - private Environment env; private ThreadContext threadContext; @Before public void setupEnv() { - globalSettings = Settings.builder().put("path.home", createTempDir()).build(); + Settings globalSettings = Settings.builder().put("path.home", createTempDir()).build(); threadContext = new ThreadContext(globalSettings); } From b368ffc281c5b3efeb74d0b6e12415e390a48b49 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Sun, 3 Feb 2019 09:42:01 +0200 Subject: [PATCH 14/20] re-introduce the option for facilitators to pass state and nonce values --- .../OpenIdConnectAuthenticateRequest.java | 8 +++---- ...IdConnectPrepareAuthenticationRequest.java | 24 ++++++++++++++++++- ...dConnectPrepareAuthenticationResponse.java | 2 +- ...nIdConnectPrepareAuthenticationAction.java | 6 ++--- .../authc/oidc/OpenIdConnectRealm.java | 22 +++++++++++++---- .../authc/oidc/OpenIdConnectToken.java | 8 +++---- ...nIdConnectPrepareAuthenticationAction.java | 2 ++ ...nectPrepareAuthenticationRequestTests.java | 21 ++++++++++++++-- 8 files changed, 73 insertions(+), 20 deletions(-) diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectAuthenticateRequest.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectAuthenticateRequest.java index 3605e182ca460..2ab5c24d8cab9 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectAuthenticateRequest.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectAuthenticateRequest.java @@ -24,14 +24,14 @@ public class OpenIdConnectAuthenticateRequest extends ActionRequest { private String redirectUri; /** - * The state value that we generated for this specific flow and that should be stored at the user's session with - * the facilitator + * The state value that we generated or the facilitator provided for this specific flow and that should be stored at the user's session + * with the facilitator */ private String state; /** - * The nonce value that we generated for this specific flow and that should be stored at the user's session with - * the facilitator + * The nonce value that we generated or the facilitator provided for this specific flow and that should be stored at the user's session + * with the facilitator */ private String nonce; diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java index af690b606feb3..88e9e82313dcb 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java @@ -21,21 +21,41 @@ public class OpenIdConnectPrepareAuthenticationRequest extends ActionRequest { private String realmName; + private String state; + private String nonce; public String getRealmName() { return realmName; } + public String getState() { + return state; + } + + public String getNonce() { + return nonce; + } + public void setRealmName(String realmName) { this.realmName = realmName; } + public void setState(String state) { + this.state = state; + } + + public void setNonce(String nonce) { + this.nonce = nonce; + } + public OpenIdConnectPrepareAuthenticationRequest() { } public OpenIdConnectPrepareAuthenticationRequest(StreamInput in) throws IOException { super.readFrom(in); realmName = in.readString(); + state = in.readOptionalString(); + nonce = in.readOptionalString(); } @Override @@ -51,6 +71,8 @@ public ActionRequestValidationException validate() { public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(realmName); + out.writeOptionalString(state); + out.writeOptionalString(nonce); } @Override @@ -59,7 +81,7 @@ public void readFrom(StreamInput in) { } public String toString() { - return "{realmName=" + realmName + "}"; + return "{realmName=" + realmName + ", state=" + state + ", nonce=" + nonce + "}"; } } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationResponse.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationResponse.java index cf8bce6896882..c8a70e65b8111 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationResponse.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationResponse.java @@ -74,7 +74,7 @@ public String toString() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); - builder.field("authentication_request_url", authenticationRequestUrl); + builder.field("redirect", authenticationRequestUrl); builder.field("state", state); builder.field("nonce", nonce); builder.endObject(); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java index 5d3930c791982..47a75359b4e07 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java @@ -43,14 +43,14 @@ protected void doExecute(Task task, OpenIdConnectPrepareAuthenticationRequest re listener.onFailure( new ElasticsearchSecurityException("Cannot find OpenID Connect realm with name [{}]", request.getRealmName())); } else { - prepareAuthenticationResponse((OpenIdConnectRealm) realm, listener); + prepareAuthenticationResponse((OpenIdConnectRealm) realm, request.getState(), request.getNonce(), listener); } } - private void prepareAuthenticationResponse(OpenIdConnectRealm realm, + private void prepareAuthenticationResponse(OpenIdConnectRealm realm, String state, String nonce, ActionListener listener) { try { - final OpenIdConnectPrepareAuthenticationResponse authenticationResponse = realm.buildAuthenticationRequestUri(); + final OpenIdConnectPrepareAuthenticationResponse authenticationResponse = realm.buildAuthenticationRequestUri(state, nonce); listener.onResponse(authenticationResponse); } catch (ElasticsearchException e) { listener.onFailure(e); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index 4f2d3f7cc20ce..8d8fcc5537d52 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -20,6 +20,7 @@ import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.ActionListener; +import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.lease.Releasable; import org.elasticsearch.common.settings.SecureString; @@ -282,14 +283,25 @@ private static String require(RealmConfig config, Setting.AffixSetting s /** * Creates the URI for an OIDC Authentication Request from the realm configuration using URI Query String Serialization and - * generates a state parameter and a nonce. It then returns the URI, state and nonce encapsulated in a - * {@link OpenIdConnectPrepareAuthenticationResponse} + * possibly generates a state parameter and a nonce. It then returns the URI, state and nonce encapsulated in a + * {@link OpenIdConnectPrepareAuthenticationResponse}. A facilitator can provide a state and a nonce parameter in two cases: + *
      + *
    • In case of Kibana, it allows for a better UX by ensuring that all requests to an OpenID Connect Provider within + * the same browser context (even across tabs) will use the same state and nonce values.
    • + *
    • In case of custom facilitators, the implementer might require/support generating the state parameter in order + * to tie this to an anti-XSRF token.
    • + *
    + * + * + * @param existingState An existing state that can be reused or null if we need to generate one + * @param existingNonce An existing nonce that can be reused or null if we need to generate one * * @return an {@link OpenIdConnectPrepareAuthenticationResponse} */ - public OpenIdConnectPrepareAuthenticationResponse buildAuthenticationRequestUri() throws ElasticsearchException { - final State state = new State(); - final Nonce nonce = new Nonce(); + public OpenIdConnectPrepareAuthenticationResponse buildAuthenticationRequestUri(@Nullable String existingState, + @Nullable String existingNonce) { + final State state = existingState != null ? new State(existingState) : new State(); + final Nonce nonce = existingNonce != null ? new Nonce(existingNonce) : new Nonce(); final AuthenticationRequest authenticationRequest = new AuthenticationRequest( opConfiguration.getAuthorizationEndpoint(), rpConfiguration.getResponseType(), diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java index f29fd87a67666..ab61fd8fb9d5f 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectToken.java @@ -24,10 +24,10 @@ public class OpenIdConnectToken implements AuthenticationToken { * @param redirectUrl The URI where the OP redirected the browser after the authentication event at the OP. This is passed as is from * the facilitator entity (i.e. Kibana), so it is URL Encoded. It contains either the code or the id_token itself * depending on the flow used - * @param state The state value that we generated for this specific flow and should be stored at the user's session with the - * facilitator. - * @param nonce The nonce value that we generated for this specific flow and should be stored at the user's session with the - * facilitator. + * @param state The state value that we generated or the facilitator provided for this specific flow and should be stored at the + * user's session with the facilitator. + * @param nonce The nonce value that we generated or the facilitator provided for this specific flow and should be stored at the + * user's session with the facilitator. */ public OpenIdConnectToken(String redirectUrl, State state, Nonce nonce) { this.redirectUrl = redirectUrl; diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java index a8775271a879a..a813a772a8e82 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java @@ -36,6 +36,8 @@ public class RestOpenIdConnectPrepareAuthenticationAction extends OpenIdConnectB static { PARSER.declareString(OpenIdConnectPrepareAuthenticationRequest::setRealmName, new ParseField("realm")); + PARSER.declareString(OpenIdConnectPrepareAuthenticationRequest::setState, new ParseField("state")); + PARSER.declareString(OpenIdConnectPrepareAuthenticationRequest::setNonce, new ParseField("nonce")); } public RestOpenIdConnectPrepareAuthenticationAction(Settings settings, RestController controller, XPackLicenseState licenseState) { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/OpenIdConnectPrepareAuthenticationRequestTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/OpenIdConnectPrepareAuthenticationRequestTests.java index bfff933e2c7ad..a87ae85bfae56 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/OpenIdConnectPrepareAuthenticationRequestTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/OpenIdConnectPrepareAuthenticationRequestTests.java @@ -23,9 +23,26 @@ public void testSerialization() throws IOException { final BytesStreamOutput out = new BytesStreamOutput(); request.writeTo(out); - final OpenIdConnectPrepareAuthenticationRequest unserialized = + final OpenIdConnectPrepareAuthenticationRequest deserialized = new OpenIdConnectPrepareAuthenticationRequest(out.bytes().streamInput()); - assertThat(unserialized.getRealmName(), equalTo("oidc-realm1")); + assertThat(deserialized.getRealmName(), equalTo("oidc-realm1")); + } + + public void testSerializationWithStateAndNonce() throws IOException { + final OpenIdConnectPrepareAuthenticationRequest request = new OpenIdConnectPrepareAuthenticationRequest(); + final String nonce = randomAlphaOfLengthBetween(8, 12); + final String state = randomAlphaOfLengthBetween(8, 12); + request.setRealmName("oidc-realm1"); + request.setNonce(nonce); + request.setState(state); + final BytesStreamOutput out = new BytesStreamOutput(); + request.writeTo(out); + + final OpenIdConnectPrepareAuthenticationRequest deserialized = + new OpenIdConnectPrepareAuthenticationRequest(out.bytes().streamInput()); + assertThat(deserialized.getRealmName(), equalTo("oidc-realm1")); + assertThat(deserialized.getState(), equalTo(state)); + assertThat(deserialized.getNonce(), equalTo(nonce)); } public void testValidation() { From 81a177066845e5a826511ded926c2f4d2d2bf98d Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Sun, 3 Feb 2019 21:07:58 +0200 Subject: [PATCH 15/20] remove unused import --- .../xpack/security/authc/oidc/OpenIdConnectRealm.java | 1 - 1 file changed, 1 deletion(-) diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index 8d8fcc5537d52..c3b0bdc797edc 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -17,7 +17,6 @@ import com.nimbusds.openid.connect.sdk.AuthenticationRequest; import com.nimbusds.openid.connect.sdk.Nonce; import org.apache.logging.log4j.Logger; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.Nullable; From 345054115798b085d87b9917ef72dae18ab6f43e Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Sun, 3 Feb 2019 21:44:46 +0200 Subject: [PATCH 16/20] fix tests --- .../authc/oidc/OpenIdConnectRealmTests.java | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java index 15247b19e040b..02b5820ee6219 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java @@ -162,7 +162,7 @@ public void testBuildRelyingPartyConfigWithoutOpenIdScope() { Arrays.asList("scope1", "scope2")); final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); - final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(); + final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null); final String state = response.getState(); final String nonce = response.getNonce(); assertThat(response.getAuthenticationRequestUrl(), @@ -185,7 +185,7 @@ public void testBuilidingAuthenticationRequest() { Arrays.asList("openid", "scope1", "scope2")); final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); - final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(); + final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null); final String state = response.getState(); final String nonce = response.getNonce(); assertThat(response.getAuthenticationRequestUrl(), @@ -207,13 +207,33 @@ public void testBuilidingAuthenticationRequestWithDefaultScope() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); - final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(); + final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null); final String state = response.getState(); final String nonce = response.getNonce(); assertThat(response.getAuthenticationRequestUrl(), equalTo("https://op.example.com/login?scope=openid&response_type=code" + "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state=" + state + "&nonce=" + nonce + "&client_id=rp-my")); } + public void testBuilidingAuthenticationRequestWithExistingStateAndNonce() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, + null); + final String state = new State().getValue(); + final String nonce = new Nonce().getValue(); + final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(state, nonce); + + assertThat(response.getAuthenticationRequestUrl(), equalTo("https://op.example.com/login?scope=openid&response_type=code" + + "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state=" + state + "&nonce=" + nonce + "&client_id=rp-my")); + } private AuthenticationResult authenticateWithOidc(UserRoleMapper roleMapper, boolean notPopulateMetadata, boolean useAuthorizingRealm) throws Exception { From 8fd7f3140cd0e2441b9a0927b13bc58c28f99e26 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Mon, 4 Feb 2019 09:09:17 +0200 Subject: [PATCH 17/20] Support 3rd party initiated authentication --- ...IdConnectPrepareAuthenticationRequest.java | 32 ++++++++++++++++--- ...nIdConnectPrepareAuthenticationAction.java | 30 ++++++++++++++--- .../authc/oidc/OpenIdConnectRealm.java | 4 +++ ...nIdConnectPrepareAuthenticationAction.java | 1 + ...nectPrepareAuthenticationRequestTests.java | 24 ++++++++++++-- 5 files changed, 79 insertions(+), 12 deletions(-) diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java index af690b606feb3..7d156f1985802 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java @@ -20,29 +20,50 @@ */ public class OpenIdConnectPrepareAuthenticationRequest extends ActionRequest { + /** + * The name of the OpenID Connect realm in the configuration that should be used for authentication + */ private String realmName; + /** + * In case of a + * 3rd party initiated authentication, the + * issuer to the UA needs to be redirected for authentication + */ + private String issuer; public String getRealmName() { return realmName; } + public String getIssuer() { + return issuer; + } + public void setRealmName(String realmName) { this.realmName = realmName; } + public void setIssuer(String issuer) { + this.issuer = issuer; + } + public OpenIdConnectPrepareAuthenticationRequest() { } public OpenIdConnectPrepareAuthenticationRequest(StreamInput in) throws IOException { super.readFrom(in); - realmName = in.readString(); + realmName = in.readOptionalString(); + issuer = in.readOptionalString(); } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; - if (Strings.hasText(realmName) == false) { - validationException = addValidationError("realm name must be provided", null); + if (Strings.hasText(realmName) == false && Strings.hasText(issuer) == false) { + validationException = addValidationError("one of [realm, issuer] must be provided", null); + } + if (Strings.hasText(realmName) && Strings.hasText(issuer)) { + validationException = addValidationError("only one of [realm, issuer] can be provided in the same request", null); } return validationException; } @@ -50,7 +71,8 @@ public ActionRequestValidationException validate() { @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); - out.writeString(realmName); + out.writeOptionalString(realmName); + out.writeOptionalString(issuer); } @Override @@ -59,7 +81,7 @@ public void readFrom(StreamInput in) { } public String toString() { - return "{realmName=" + realmName + "}"; + return "{realmName=" + realmName + ", issuer=" + issuer + "}"; } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java index 5d3930c791982..9588e78ef4461 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java @@ -10,6 +10,7 @@ import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.HandledTransportAction; +import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.tasks.Task; @@ -21,6 +22,9 @@ import org.elasticsearch.xpack.security.authc.Realms; import org.elasticsearch.xpack.security.authc.oidc.OpenIdConnectRealm; +import java.util.List; +import java.util.stream.Collectors; + public class TransportOpenIdConnectPrepareAuthenticationAction extends HandledTransportAction { @@ -38,12 +42,30 @@ public TransportOpenIdConnectPrepareAuthenticationAction(TransportService transp @Override protected void doExecute(Task task, OpenIdConnectPrepareAuthenticationRequest request, ActionListener listener) { - final Realm realm = this.realms.realm(request.getRealmName()); - if (null == realm || realm instanceof OpenIdConnectRealm == false) { + Realm realm = null; + if (Strings.hasText(request.getIssuer())) { + List matchingRealms = this.realms.stream().filter(r -> r instanceof OpenIdConnectRealm) + .map(r -> (OpenIdConnectRealm) r) + .filter(r -> r.isIssuerValid(request.getIssuer())) + .collect(Collectors.toList()); + if (matchingRealms.isEmpty()) { + listener.onFailure( + new ElasticsearchSecurityException("Cannot find OpenID Connect realm with issuer [{}]", request.getIssuer())); + } else if (matchingRealms.size() > 1) { + listener.onFailure( + new ElasticsearchSecurityException("Found multiple OpenID Connect realm with issuer [{}]", request.getIssuer())); + } else { + realm = matchingRealms.get(0); + } + } else if (Strings.hasText(request.getRealmName())) { + realm = this.realms.realm(request.getRealmName()); + } + + if (realm instanceof OpenIdConnectRealm) { + prepareAuthenticationResponse((OpenIdConnectRealm) realm, listener); + } else { listener.onFailure( new ElasticsearchSecurityException("Cannot find OpenID Connect realm with name [{}]", request.getRealmName())); - } else { - prepareAuthenticationResponse((OpenIdConnectRealm) realm, listener); } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index 0e6c35456cf9a..7e3e80e105515 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -128,6 +128,10 @@ public OpenIdConnectPrepareAuthenticationResponse buildAuthenticationRequestUri( } } + public boolean isIssuerValid(String issuer) { + return this.opConfiguration.getIssuer().equals(issuer); + } + private void addParameter(StringBuilder builder, String parameter, String value, boolean isFirstParameter) throws UnsupportedEncodingException { char prefix = isFirstParameter ? '?' : '&'; diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java index a8775271a879a..441706b8898f7 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java @@ -36,6 +36,7 @@ public class RestOpenIdConnectPrepareAuthenticationAction extends OpenIdConnectB static { PARSER.declareString(OpenIdConnectPrepareAuthenticationRequest::setRealmName, new ParseField("realm")); + PARSER.declareString(OpenIdConnectPrepareAuthenticationRequest::setRealmName, new ParseField("iss")); } public RestOpenIdConnectPrepareAuthenticationAction(Settings settings, RestController controller, XPackLicenseState licenseState) { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/OpenIdConnectPrepareAuthenticationRequestTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/OpenIdConnectPrepareAuthenticationRequestTests.java index bfff933e2c7ad..5f4b0ced376ec 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/OpenIdConnectPrepareAuthenticationRequestTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/OpenIdConnectPrepareAuthenticationRequestTests.java @@ -23,9 +23,18 @@ public void testSerialization() throws IOException { final BytesStreamOutput out = new BytesStreamOutput(); request.writeTo(out); - final OpenIdConnectPrepareAuthenticationRequest unserialized = + final OpenIdConnectPrepareAuthenticationRequest deserialized = new OpenIdConnectPrepareAuthenticationRequest(out.bytes().streamInput()); - assertThat(unserialized.getRealmName(), equalTo("oidc-realm1")); + assertThat(deserialized.getRealmName(), equalTo("oidc-realm1")); + + final OpenIdConnectPrepareAuthenticationRequest request2 = new OpenIdConnectPrepareAuthenticationRequest(); + request2.setIssuer("https://op.company.org/"); + final BytesStreamOutput out2 = new BytesStreamOutput(); + request2.writeTo(out2); + + final OpenIdConnectPrepareAuthenticationRequest deserialized2 = + new OpenIdConnectPrepareAuthenticationRequest(out2.bytes().streamInput()); + assertThat(deserialized2.getIssuer(), equalTo("https://op.company.org/")); } public void testValidation() { @@ -33,6 +42,15 @@ public void testValidation() { final ActionRequestValidationException validation = request.validate(); assertNotNull(validation); assertThat(validation.validationErrors().size(), equalTo(1)); - assertThat(validation.validationErrors().get(0), containsString("realm name must be provided")); + assertThat(validation.validationErrors().get(0), containsString("one of [realm, issuer] must be provided")); + + final OpenIdConnectPrepareAuthenticationRequest request2 = new OpenIdConnectPrepareAuthenticationRequest(); + request2.setRealmName("oidc-realm1"); + request2.setIssuer("https://op.company.org/"); + final ActionRequestValidationException validation2 = request2.validate(); + assertNotNull(validation2); + assertThat(validation2.validationErrors().size(), equalTo(1)); + assertThat(validation2.validationErrors().get(0), + containsString("only one of [realm, issuer] can be provided in the same request")); } } From 4e0788e52bfb7f72f252f53e88b3ead6d51c4fbb Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Mon, 11 Feb 2019 20:11:02 +0200 Subject: [PATCH 18/20] address feedback --- ...IdConnectPrepareAuthenticationRequest.java | 15 +++++++- ...nIdConnectPrepareAuthenticationAction.java | 8 ++-- .../authc/oidc/OpenIdConnectRealm.java | 21 ++++++----- .../authc/oidc/OpenIdConnectRealmTests.java | 37 +++++++++++++++---- 4 files changed, 61 insertions(+), 20 deletions(-) diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java index fd87514f4f81f..eea84a38fc3ec 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java @@ -30,6 +30,7 @@ public class OpenIdConnectPrepareAuthenticationRequest extends ActionRequest { * issuer to the UA needs to be redirected for authentication */ private String issuer; + private String loginHint; private String state; private String nonce; @@ -49,6 +50,11 @@ public String getIssuer() { return issuer; } + public String getLoginHint() { + return loginHint; + } + + public void setRealmName(String realmName) { this.realmName = realmName; } @@ -65,6 +71,10 @@ public void setNonce(String nonce) { this.nonce = nonce; } + public void setLoginHint(String loginHint) { + this.loginHint = loginHint; + } + public OpenIdConnectPrepareAuthenticationRequest() { } @@ -72,6 +82,7 @@ public OpenIdConnectPrepareAuthenticationRequest(StreamInput in) throws IOExcept super.readFrom(in); realmName = in.readOptionalString(); issuer = in.readOptionalString(); + loginHint = in.readOptionalString(); state = in.readOptionalString(); nonce = in.readOptionalString(); } @@ -93,6 +104,7 @@ public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeOptionalString(realmName); out.writeOptionalString(issuer); + out.writeOptionalString(loginHint); out.writeOptionalString(state); out.writeOptionalString(nonce); } @@ -103,7 +115,8 @@ public void readFrom(StreamInput in) { } public String toString() { - return "{realmName=" + realmName + ", issuer=" + issuer +", state=" + state + ", nonce=" + nonce + "}"; + return "{realmName=" + realmName + ", issuer=" + issuer + ", login_hint=" + + loginHint + ", state=" + state + ", nonce=" + nonce + "}"; } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java index d35a035ca8f5c..4dcfb47c6b0d8 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java @@ -61,17 +61,19 @@ protected void doExecute(Task task, OpenIdConnectPrepareAuthenticationRequest re } if (realm instanceof OpenIdConnectRealm) { - prepareAuthenticationResponse((OpenIdConnectRealm) realm, request.getState(), request.getNonce(), listener); + prepareAuthenticationResponse((OpenIdConnectRealm) realm, request.getState(), request.getNonce(), request.getLoginHint(), + listener); } else { listener.onFailure( new ElasticsearchSecurityException("Cannot find OpenID Connect realm with name [{}]", request.getRealmName())); } } - private void prepareAuthenticationResponse(OpenIdConnectRealm realm, String state, String nonce, + private void prepareAuthenticationResponse(OpenIdConnectRealm realm, String state, String nonce, String loginHint, ActionListener listener) { try { - final OpenIdConnectPrepareAuthenticationResponse authenticationResponse = realm.buildAuthenticationRequestUri(state, nonce); + final OpenIdConnectPrepareAuthenticationResponse authenticationResponse = + realm.buildAuthenticationRequestUri(state, nonce, loginHint); listener.onResponse(authenticationResponse); } catch (ElasticsearchException e) { listener.onFailure(e); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index 7ccdbababf6ed..6cf7f0a568b50 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -294,23 +294,26 @@ private static String require(RealmConfig config, Setting.AffixSetting s * * @param existingState An existing state that can be reused or null if we need to generate one * @param existingNonce An existing nonce that can be reused or null if we need to generate one + * @param loginHint A String with a login hint to add to the authentication request in case of a 3rd party initiated login * * @return an {@link OpenIdConnectPrepareAuthenticationResponse} */ public OpenIdConnectPrepareAuthenticationResponse buildAuthenticationRequestUri(@Nullable String existingState, - @Nullable String existingNonce) { + @Nullable String existingNonce, + @Nullable String loginHint) { final State state = existingState != null ? new State(existingState) : new State(); final Nonce nonce = existingNonce != null ? new Nonce(existingNonce) : new Nonce(); - final AuthenticationRequest authenticationRequest = new AuthenticationRequest( - opConfiguration.getAuthorizationEndpoint(), - rpConfiguration.getResponseType(), + final AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(rpConfiguration.getResponseType(), rpConfiguration.getRequestedScope(), rpConfiguration.getClientId(), - rpConfiguration.getRedirectUri(), - state, - nonce); - - return new OpenIdConnectPrepareAuthenticationResponse(authenticationRequest.toURI().toString(), + rpConfiguration.getRedirectUri()) + .endpointURI(opConfiguration.getAuthorizationEndpoint()) + .state(state) + .nonce(nonce); + if (Strings.hasText(loginHint)) { + builder.loginHint(loginHint); + } + return new OpenIdConnectPrepareAuthenticationResponse(builder.build().toURI().toString(), state.getValue(), nonce.getValue()); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java index 02b5820ee6219..fc3a26780b856 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java @@ -162,7 +162,7 @@ public void testBuildRelyingPartyConfigWithoutOpenIdScope() { Arrays.asList("scope1", "scope2")); final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); - final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null); + final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null, null); final String state = response.getState(); final String nonce = response.getNonce(); assertThat(response.getAuthenticationRequestUrl(), @@ -170,7 +170,7 @@ public void testBuildRelyingPartyConfigWithoutOpenIdScope() { "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state=" + state + "&nonce=" + nonce + "&client_id=rp-my")); } - public void testBuilidingAuthenticationRequest() { + public void testBuildingAuthenticationRequest() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") @@ -185,7 +185,7 @@ public void testBuilidingAuthenticationRequest() { Arrays.asList("openid", "scope1", "scope2")); final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); - final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null); + final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null, null); final String state = response.getState(); final String nonce = response.getNonce(); assertThat(response.getAuthenticationRequestUrl(), @@ -194,7 +194,7 @@ public void testBuilidingAuthenticationRequest() { } - public void testBuilidingAuthenticationRequestWithDefaultScope() { + public void testBuildingAuthenticationRequestWithDefaultScope() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") @@ -207,14 +207,14 @@ public void testBuilidingAuthenticationRequestWithDefaultScope() { .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, null); - final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null); + final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null, null); final String state = response.getState(); final String nonce = response.getNonce(); assertThat(response.getAuthenticationRequestUrl(), equalTo("https://op.example.com/login?scope=openid&response_type=code" + "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state=" + state + "&nonce=" + nonce + "&client_id=rp-my")); } - public void testBuilidingAuthenticationRequestWithExistingStateAndNonce() { + public void testBuildingAuthenticationRequestWithExistingStateAndNonce() { final Settings.Builder settingsBuilder = Settings.builder() .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") @@ -229,12 +229,35 @@ public void testBuilidingAuthenticationRequestWithExistingStateAndNonce() { null); final String state = new State().getValue(); final String nonce = new Nonce().getValue(); - final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(state, nonce); + final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(state, nonce, null); assertThat(response.getAuthenticationRequestUrl(), equalTo("https://op.example.com/login?scope=openid&response_type=code" + "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state=" + state + "&nonce=" + nonce + "&client_id=rp-my")); } + public void testBuildingAuthenticationRequestWithLoginHint() { + final Settings.Builder settingsBuilder = Settings.builder() + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_NAME), "the op") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my") + .put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code"); + final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build()), null, + null); + final String state = new State().getValue(); + final String nonce = new Nonce().getValue(); + final String thehint = randomAlphaOfLength(8); + final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(state, nonce, thehint); + + assertThat(response.getAuthenticationRequestUrl(), equalTo("https://op.example.com/login?login_hint=" + thehint + + "&scope=openid&response_type=code&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state=" + + state + "&nonce=" + nonce + "&client_id=rp-my")); + } + private AuthenticationResult authenticateWithOidc(UserRoleMapper roleMapper, boolean notPopulateMetadata, boolean useAuthorizingRealm) throws Exception { From 0fbe3c79d2757a6026cf1baf0b70702e824eaa37 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Wed, 13 Feb 2019 14:26:13 +0200 Subject: [PATCH 19/20] add parser field --- .../oidc/RestOpenIdConnectPrepareAuthenticationAction.java | 1 + 1 file changed, 1 insertion(+) diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java index fc9ca5bae3e0f..60786c82b56ef 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/oidc/RestOpenIdConnectPrepareAuthenticationAction.java @@ -37,6 +37,7 @@ public class RestOpenIdConnectPrepareAuthenticationAction extends OpenIdConnectB static { PARSER.declareString(OpenIdConnectPrepareAuthenticationRequest::setRealmName, new ParseField("realm")); PARSER.declareString(OpenIdConnectPrepareAuthenticationRequest::setIssuer, new ParseField("iss")); + PARSER.declareString(OpenIdConnectPrepareAuthenticationRequest::setLoginHint, new ParseField("login_hint")); PARSER.declareString(OpenIdConnectPrepareAuthenticationRequest::setState, new ParseField("state")); PARSER.declareString(OpenIdConnectPrepareAuthenticationRequest::setNonce, new ParseField("nonce")); } From 00baca1a8c6b6199550376c49c290d98cef526aa Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Fri, 22 Feb 2019 15:48:22 +0200 Subject: [PATCH 20/20] address feedback --- .../action/oidc/OpenIdConnectPrepareAuthenticationRequest.java | 3 +-- .../TransportOpenIdConnectPrepareAuthenticationAction.java | 3 ++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java index eea84a38fc3ec..8f6d616981b39 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectPrepareAuthenticationRequest.java @@ -27,7 +27,7 @@ public class OpenIdConnectPrepareAuthenticationRequest extends ActionRequest { /** * In case of a * 3rd party initiated authentication, the - * issuer to the UA needs to be redirected for authentication + * issuer that the User Agent needs to be redirected to for authentication */ private String issuer; private String loginHint; @@ -54,7 +54,6 @@ public String getLoginHint() { return loginHint; } - public void setRealmName(String realmName) { this.realmName = realmName; } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java index 4dcfb47c6b0d8..f1d3557f788a0 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectPrepareAuthenticationAction.java @@ -43,7 +43,8 @@ protected void doExecute(Task task, OpenIdConnectPrepareAuthenticationRequest re ActionListener listener) { Realm realm = null; if (Strings.hasText(request.getIssuer())) { - List matchingRealms = this.realms.stream().filter(r -> r instanceof OpenIdConnectRealm) + List matchingRealms = this.realms.stream() + .filter(r -> r instanceof OpenIdConnectRealm && ((OpenIdConnectRealm) r).isIssuerValid(request.getIssuer())) .map(r -> (OpenIdConnectRealm) r) .filter(r -> r.isIssuerValid(request.getIssuer())) .collect(Collectors.toList());