8000 Restrict Kubernetes IdP pod-token forwarding by default by atiqur-rahman-pro · Pull Request #54232 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ When an issuer discovery URL is configured, Keycloak invokes its
`<DISCOVERY_URL>/.well-known/openid-configuration` endpoint when the provider is saved or updated and persists the returned JWKS
URL. Otherwise, it discovers keys from `<ISSUER>/.well-known/openid-configuration` when needed. {project_name} uses the token from
`/var/run/secrets/kubernetes.io/serviceaccount/token` to access the in-cluster discovery endpoint. When loading JWKS,
it uses the token when its `iss` claim matches the configured issuer.
by default it forwards the token only to trusted in-cluster Kubernetes API server endpoints when its `iss` claim matches the configured issuer. These are HTTPS endpoints on the default port or port 443 for hosts `kubernetes.default.svc`, `kubernetes.default.svc.cluster.local`, or `kubernetes.default`, and the exact host and HTTPS port configured by the pod environment variables `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT_HTTPS`. Forwarding the token to additional endpoints (such as external or custom JWKS URLs) can be enabled with the `forwardTokenToAdditionalEndpoints` configuration option.

Each identity provider must have a unique issuer. Each client must also have a unique subject identifier for each
issuer. As the subject identifier is built from the namespace and service account name, each client must have its own
Expand Down Expand Up @@ -49,6 +49,9 @@ and make sure tokens can not be intercepted in communication between the client
|Issuer discovery URL
|Optional Kubernetes API server or external OIDC discovery base URL. When configured, {project_name} resolves and persists the issuer and JWKS URL when the provider is saved or updated.

|Forward token to additional endpoints
|Optional setting to control whether the pod's service account token is forwarded to additional endpoints bey 8000 ond the trusted in-cluster Kubernetes API server endpoints listed above. Defaults to `false`.

|===
+
. When you create a new realm with the preview feature `client-auth-federated` enabled, the client authentication flow is already configured correctly. For existing realms, add to the client authentication flow the execution of *Signed JWT - Federated* as an alternative step. As built-in flows can not be updated, and if the default flow is your default, you will first need to duplicate the existing clients
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -985,6 +985,8 @@ kubernetesIssuerUrlHelp=Optional issuer of the Kubernetes service account tokens
kubernetesIssuerUrl=Kubernetes Issuer URL
kubernetesIssuerDiscoveryUrl=Issuer discovery URL
kubernetesIssuerDiscoveryUrlHelp=Optional Kubernetes API server or external OIDC discovery base URL. When configured, Keycloak resolves and persists the issuer and JWKS URL when the identity provider is saved or updated.
forwardTokenToAdditionalEndpoints=Forward token to additional endpoints
forwardTokenToAdditionalEndpointsHelp=When enabled, Keycloak forwards the pod service account token to additional endpoints beyond trusted Kubernetes API server endpoints.
permission=Permission
saveEventListeners=Save Event Listeners
capabilityConfig=Capability config
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { FormGroupField } from "../component/FormGroupField";
import { Controller, useFormContext } from "react-hook-form";
import { TimeSelector } from "../../components/time-selector/TimeSelector";
import IdentityProviderRepresentation from "libs/keycloak-admin-client/lib/defs/identityProviderRepresentation";
import { DefaultSwitchControl } from "../../components/SwitchControl";

export const KubernetesSettings = () => {
const { t } = useTranslation();
Expand All @@ -29,6 +30,13 @@ export const KubernetesSettings = () => {
labelIcon={t("kubernetesIssuerDiscoveryUrlHelp")}
label={t("kubernetesIssuerDiscoveryUrl")}
/>
<DefaultSwitchControl
name="config.forwardTokenToAdditionalEndpoints"
label={t("forwardTokenToAdditionalEndpoints")}
labelIcon={t("forwardTokenToAdditionalEndpointsHelp")}
defaultValue="false"
stringify
/>
<FormGroupField label="fedClientAssertionMaxExp">
<Controller
name="config.fedClientAssertionMaxExp"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ private boolean verifySignature(AbstractJWTClientValidator validator) {

KeyWrapper publicKey;
try {
publicKey = keyStorage.getPublicKey(modelKey, kid, alg, new KubernetesJwksEndpointLoader(session, config.getIssuer(), config.getJwksUrl()));
publicKey = keyStorage.getPublicKey(modelKey, kid, alg, new KubernetesJwksEndpointLoader(session, config));
} catch (Exception e) {
// Indicative of an infrastructure/configuration and can't be
// triggered by a client - worth WARN visibility.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
public class KubernetesIdentityProviderConfig extends IdentityProviderModel implements IssuerValidation {

public static final String ISSUER_DISCOVERY_URL = "issuerDiscoveryUrl";
public static final String FORWARD_TOKEN_TO_ADDITIONAL_ENDPOINTS = "forwardTokenToAdditionalEndpoints";

public KubernetesIdentityProviderConfig() {
}
Expand All @@ -29,6 +30,14 @@ public KubernetesIdentityProviderConfig(IdentityProviderModel model) {
super(model);
}

public boolean isForwardTokenToAdditionalEndpoints() {
return Boolean.parseBoolean(getConfig().get(FORWARD_TOKEN_TO_ADDITIONAL_ENDPOINTS));
}

public void setForwardTokenToAdditionalEndpoints(boolean forwardTokenToAdditionalEndpoints) {
getConfig().put(FORWARD_TOKEN_TO_ADDITIONAL_ENDPOINTS, String.valueOf(forwardTokenToAdditionalEndpoints));
}

public String getIssuer() {
String issuer = getConfig().get(ISSUER);
if (Strings.isEmpty(issuer)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.keycloak.broker.kubernetes;

import java.io.File;
import java.io.IOException;

import org.keycloak.crypto.PublicKeysWrapper;
Expand All @@ -14,30 +15,53 @@
import org.keycloak.util.Strings;

import org.apache.http.HttpHeaders;
import org.jboss.logging.Logger;

public class KubernetesJwksEndpointLoader implements PublicKeyLoader {

private static final Logger logger = Logger.getLogger(KubernetesJwksEndpointLoader.class);

private final KeycloakSession session;
private final String issuer;
private final String jwksUrl;
private final boolean forwardTokenToAdditionalEndpoints;
private final File tokenFile;

public KubernetesJwksEndpointLoader(KeycloakSession session, KubernetesIdentityProviderConfig config) {
this(session, config.getIssuer(), config.getJwksUrl(), config.isForwardTokenToAdditionalEndpoints());
}

public KubernetesJwksEndpointLoader(KeycloakSession session, String issuer, String jwksUrl) {
this(session, issuer, jwksUrl, false);
}

public KubernetesJwksEndpointLoader(KeycloakSession session, String issuer, String jwksUrl, boolean forwardTokenToAdditionalEndpoints) {
this(session, issuer, jwksUrl, forwardTokenToAdditionalEndpoints, new File(KubernetesConstants.SERVICE_ACCOUNT_TOKEN_PATH));
}

KubernetesJwksEndpointLoader(KeycloakSession session, String issuer, String jwksUrl, boolean forwardTokenToAdditionalEndpoints, File tokenFile) {
this.session = session;
this.issuer = issuer;
this.jwksUrl = jwksUrl;
this.forwardTokenToAdditionalEndpoints = forwardTokenToAdditionalEndpoints;
this.tokenFile = tokenFile != null ? tokenFile : new File(KubernetesConstants.SERVICE_ACCOUNT_TOKEN_PATH);
}

@Override
public PublicKeysWrapper loadKeys() throws Exception {
SimpleHttp simpleHttp = SimpleHttp.create(session);

String token = KubernetesUtils.getServiceAccountToken(issuer);
String token = KubernetesUtils.getServiceAccountToken(issuer, tokenFile);
String jwksUri = jwksUrl;
if (Strings.isEmpty(jwksUri)) {
String wellKnownEndpoint = KubernetesUtils.discoveryUrl(issuer);
SimpleHttpRequest wellKnownRequest = simpleHttp.doGet(wellKnownEndpoint).acceptJson();
if (token != null) {
wellKnownRequest.auth(token);
if (isTokenForwardingAllowed(wellKnownEndpoint)) {
wellKnownRequest.auth(token);
} else {
logger.debugf("Not forwarding service account token to '%s' because token forwarding to additional endpoints is disabled", wellKnownEndpoint);
}
}

jwksUri = wellKnownRequest.asJson(OIDCConfigurationRepresentation.class).getJwksUri();
Expand All @@ -48,11 +72,22 @@ public PublicKeysWrapper loadKeys() throws Exception {

SimpleHttpRequest jwksRequest = simpleHttp.doGet(jwksUri).header(HttpHeaders.ACCEPT, "application/jwk-set+json");
if (token != null) {
jwksRequest.auth(token);
if (isTokenForwardingAllowed(jwksUri)) {
jwksRequest.auth(token);
} else {
logger.debugf("Not forwarding service account token to '%s' because token forwarding to additional endpoints is disabled", jwksUri);
}
}

JSONWebKeySet jwks = jwksRequest.asJson(JSONWebKeySet.class);
return JWKSUtils.getKeyWrappersForUse(jwks, JWK.Use.SIG);
}

boolean isTokenForwardingAllowed(String uri) {
if (forwardTokenToAdditionalEndpoints) {
return true;
}
return KubernetesUtils.isTrustedKubernetesEndpoint(uri);
}

}
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package org.keycloak.broker.kubernetes;

import java.io.File;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

import org.keycloak.jose.jws.JWSInput;
import org.keycloak.representations.JsonWebToken;
import org.keycloak.util.Strings;

import org.apache.commons.io.FileUtils;
import org.jboss.logging.Logger;
Expand Down Expand Up @@ -68,4 +71,37 @@ static String getServiceAccountToken(String issuer, File file) {
}
return null;
}

static boolean isTrustedKubernetesEndpoint(String uri) {
return isTrustedKubernetesEndpoint(uri, System.getenv("KUBERNETES_SERVICE_HOST"), System.getenv("KUBERNETES_SERVICE_PORT_HTTPS"));
}

static boolean isTrustedKubernetesEndpoint(String uri, String serviceHost, String servicePort) {
if (Strings.isEmpty(uri)) {
return false;
}
try {
URI parsed = URI.create(uri);
if (!"https".equalsIgnoreCase(parsed.getScheme())) {
return false;
}
String host = parsed.getHost();
if (host == null) {
return false;
}
host = host.toLowerCase(Locale.ROOT);
int port = parsed.getPort() == -1 ? 443 : parsed.getPort();
boolean standardApiHost = host.equals("kubernetes.default.svc")
|| host.equals("kubernetes.default.svc.cluster.local")
|| host.equals("kubernetes.default");
if (standardApiHost && port == 443) {
return true;
}
return !Strings.isEmpty(serviceHost) && !Strings.isEmpty(servicePort)
&& host.equalsIgnoreCase(serviceHost)
&& port == Integer.parseInt(servicePort);
} catch (IllegalArgumentException e) {
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package org.keycloak.broker.kubernetes;

import org.keycloak.models.IdentityProviderModel;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class KubernetesIdentityProviderConfigTest {

@Test
void forwardTokenToAdditionalEndpointsDefaultsToFalse() {
KubernetesIdentityProviderConfig config = new KubernetesIdentityProviderConfig();
assertFalse(config.isForwardTokenToAdditionalEndpoints());
}

@Test
void setForwardTokenToAdditionalEndpoints() {
KubernetesIdentityProviderConfig config = new KubernetesIdentityProviderConfig();

config.setForwardTokenToAdditionalEndpoints(true);
assertTrue(config.isForwardTokenToAdditionalEndpoints());
assertEquals("true", config.getConfig().get(KubernetesIdentityProviderConfig.FORWARD_TOKEN_TO_ADDITIONAL_ENDPOINTS));

config.setForwardTokenToAdditionalEndpoints(false);
assertFalse(config.isForwardTokenToAdditionalEndpoints());
assertEquals("false", config.getConfig().get(KubernetesIdentityProviderConfig.FORWARD_TOKEN_TO_ADDITIONAL_ENDPOINTS));
}

@Test
void forwardTokenToAdditionalEndpointsFromModel() {
IdentityProviderModel model = new IdentityProviderModel();
model.getConfig().put(KubernetesIdentityProviderConfig.FORWARD_TOKEN_TO_ADDITIONAL_ENDPOINTS, "true");

KubernetesIdentityProviderConfig config = new KubernetesIdentityProviderConfig(model);
assertTrue(config.isForwardTokenToAdditionalEndpoints());

model.getConfig().put(KubernetesIdentityProviderConfig.FORWARD_TOKEN_TO_ADDITIONAL_ENDPOINTS, "invalid");
config = new KubernetesIdentityProviderConfig(model);
assertFalse(config.isForwardTokenToAdditionalEndpoints());
}
}
Loading
Loading
0