From 130f7d919b67ea9efd4fd541b479b36bdbccd73a Mon Sep 17 00:00:00 2001 From: Tim Walter Date: Wed, 2 Oct 2024 09:35:04 +0200 Subject: [PATCH] Improve formatting of the docs (#39) * Disable maximum line length for Markdown files to allow semantic line breaks Signed-off-by: Tim Walter * Fix some Markdown formatting Signed-off-by: Tim Walter * Use semantic line breaks and fix some typos and phrasing issues Signed-off-by: Tim Walter --------- Signed-off-by: Tim Walter --- .editorconfig | 17 ++ README.md | 16 +- docs/auditors/clients.md | 242 +++++++++-------------- docs/auditors/idp.md | 61 +++--- docs/auditors/index.md | 18 +- docs/auditors/realm.md | 88 ++++----- docs/auditors/scope.md | 32 ++- docs/development.md | 21 +- docs/index.md | 5 +- docs/installation.md | 5 +- docs/monitors/client_monitor.md | 7 +- docs/monitors/group_monitor.md | 4 +- docs/monitors/index.md | 29 ++- docs/monitors/protocol_mapper_monitor.md | 8 +- docs/monitors/service_account_monitor.md | 4 +- docs/usage.md | 8 +- 16 files changed, 249 insertions(+), 316 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..2f5169a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,17 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 + +[*.py] +indent_style = space +indent_size = 4 + +[*.md] +indent_size = 4 +max_line_length = off +ij_markdown_wrap_text_if_long = false diff --git a/README.md b/README.md index 8781fa8..0800510 100644 --- a/README.md +++ b/README.md @@ -9,16 +9,15 @@ [![last release status](https://github.com/iteratec/kcwarden/actions/workflows/publish.yaml/badge.svg)](https://github.com/iteratec/kcwarden/actions/workflows/publish.yaml) -**[kcwarden](https://iteratec.github.io/kcwarden/) checks your Keycloak configuration for common misconfigurations and -security vulnerabilities.** +**[kcwarden](https://iteratec.github.io/kcwarden/) checks your Keycloak configuration for common misconfigurations and security vulnerabilities.** ## 🚀 Getting started Install it using Python: -````shell +```shell pip install kcwarden -```` +``` For details and other methods, see our [documentation](https://iteratec.github.io/kcwarden/installation/). @@ -26,15 +25,14 @@ For details and other methods, see our [documentation](https://iteratec.github.i Download your Keycloak's config: -````shell +```shell kcwarden download --realm $REALM --user admin --output config.json $KEYCLOAK_BASE_URL -```` +``` and run the checks against it: -````shell +```shell kcwarden audit config.json -```` +``` For more information, see the [documentation on the project website](https://iteratec.github.io/kcwarden/). - diff --git a/docs/auditors/clients.md b/docs/auditors/clients.md index da26bc8..b77af47 100644 --- a/docs/auditors/clients.md +++ b/docs/auditors/clients.md @@ -5,8 +5,7 @@ title: Clients # Client Misconfigurations These auditors consider misconfigurations in OIDC Clients configured in Keycloak. -These OIDC clients are used by other applications to interact with Keycloak, authenticate users, obtain and exchange -access tokens, and perform other tasks. +These OIDC clients are used by other applications to interact with Keycloak, authenticate users, obtain and exchange access tokens, and perform other tasks. !!! important @@ -15,36 +14,32 @@ access tokens, and perform other tasks. ## PublicClientsMustEnforcePKCE -This auditor checks if public clients (clients that cannot securely store credentials) are enforcing the use of Proof -Key for Code Exchange (PKCE). PKCE adds an additional layer of security, especially important for public clients, to -mitigate authorization code interception attacks. Its use is strongly recommended, as it protects against several types -of attacks. It should be implemented by the client, and enforced on the Keycloak server. The only allowed value is " -S256", as this is the only secure mode of PKCE. +This auditor checks if public clients (clients that cannot securely store credentials) are enforcing the use of Proof Key for Code Exchange (PKCE). +PKCE adds an additional layer of security, especially important for public clients, to mitigate authorization code interception attacks. +Its use is strongly recommended, as it protects against several types of attacks. +It should be implemented by the client and enforced on the Keycloak server. +The only allowed value is `S256`, as this is the only secure mode of PKCE. ## ConfidentialClientShouldEnforcePKCE -While PKCE is primarily recommended for public clients, this auditor verifies if confidential clients (clients that can -securely store credentials) also enforce PKCE. Enforcing PKCE for confidential clients provides an extra security -measure, safeguarding against certain attack vectors. +While PKCE is primarily recommended for public clients, this auditor verifies if confidential clients (clients that can securely store credentials) also enforce PKCE. +Enforcing PKCE for confidential clients provides an extra security measure, safeguarding against certain attack vectors. ## ClientShouldDisableImplicitGrantFlow -This auditor identifies OIDC clients within Keycloak that have the implicit grant flow enabled. The implicit grant flow -is discouraged because it exposes the access token in the URL. This exposure can lead to vulnerabilities, such as access -token leakage or replay attacks. Instead, the "Authorization Code" flow (referred to as "Standard Flow" in Keycloak) is -recommended. The implicit flow should be disabled to prevent these security risks and ensure the confidentiality and -integrity of the access token. +This auditor identifies OIDC clients within Keycloak that have the implicit grant flow enabled. +The implicit grant flow is discouraged because it exposes the access token in the URL. +This exposure can lead to vulnerabilities, such as access token leakage or replay attacks. +Instead, the "Authorization Code" flow (referred to as "Standard Flow" in Keycloak) is recommended. +The implicit flow should be disabled to prevent these security risks and ensure the confidentiality and integrity of the access token. ## PublicClientShouldDisableDirectAccessGrants -This auditor focuses on identifying OIDC clients, specifically public clients within Keycloak, that have the direct -access grant flow enabled. The direct access grant flow, known in OAuth as the resource owner password credentials -grant, poses significant security risks by requiring clients to handle user credentials directly. This not only -increases the attack surface for credential exposure but also often conflicts with advanced authentication mechanisms -such as two-factor authentication (2FA) methods, including WebAuthN or SMS tokens. Given these considerations, the -direct access grant flow should be explicitly disabled for all clients, especially for public clients. Public clients -are particularly vulnerable as they can be used by anyone, not just the client's rightful users, making the misuse of -direct access grants a significant concern. +This auditor focuses on identifying OIDC clients, specifically public clients within Keycloak, that have the direct access grant flow enabled. +The direct access grant flow, known in OAuth as the resource owner password credentials grant, poses significant security risks by requiring clients to handle user credentials directly. +This not only increases the attack surface for credential exposure but also often conflicts with advanced authentication mechanisms such as two-factor authentication (2FA) methods, including WebAuthN or SMS tokens. +Given these considerations, the direct access grant flow should be explicitly disabled for all clients, especially for public clients. +Public clients are particularly vulnerable as they can be used by anyone, not just the client's rightful users, making the misuse of direct access grants a significant concern. !!! info @@ -53,16 +48,13 @@ direct access grants a significant concern. ## ConfidentialClientShouldDisableDirectAccessGrants -This auditor targets confidential OIDC clients within Keycloak that have enabled the direct access grant flow. The -direct access grant flow, also known in OAuth 2.0 as the resource owner password credentials grant, poses significant -security risks. It necessitates clients to directly handle user credentials, substantially increasing the vulnerability -of these credentials to exposure outside of Keycloak's managed authentication environment. Moreover, this flow often -cannot be integrated with two-factor authentication (2FA) methods, such as WebAuthN or SMS tokens, potentially -undermining modern security practices. +This auditor targets confidential OIDC clients within Keycloak that have enabled the direct access grant flow. +The direct access grant flow, also known in OAuth 2.0 as the resource owner password credentials grant, poses significant security risks. +It requires clients to directly handle user credentials, substantially increasing the vulnerability of these credentials to exposure outside of Keycloak's managed authentication environment. +Moreover, this flow often cannot be integrated with two-factor authentication (2FA) methods, such as WebAuthN or SMS tokens, potentially undermining modern security practices. -While the use of direct access grants might seem less perilous for confidential clients, due to the requirement of a -client secret for interaction, the fundamental security concerns remain. The exposure of user credentials outside of a -controlled environment and the potential bypass of advanced authentication mechanisms advise against the use of this +While the use of direct access grants might seem less perilous for confidential clients, due to the requirement of a client secret for interaction, the fundamental security concerns remain. +The exposure of user credentials outside a controlled environment and the potential bypass of advanced authentication mechanisms advise against the use of this flow for any client type, public or confidential. !!! info @@ -72,162 +64,122 @@ flow for any client type, public or confidential. ## ClientAuthenticationViaMTLSOrJWTRecommended -This auditor evaluates whether confidential OIDC clients within Keycloak are utilizing mutual TLS (mTLS) or signed JWTs -for client authentication, as opposed to the default 'shared client secret' method. Confidential clients are those that -can securely hold credentials, making them responsible for authenticating to Keycloak to access its features. While -using a shared client secret is common, it's recommended to opt for more secure authentication methods such as mTLS or -signed JWTs. These methods provide enhanced security by ensuring that client credentials are not exposed and are -authenticated in a manner that is both secure and verifiable. This recommendation aligns with best practices for -securing OAuth clients and protecting resource access. For more detailed guidance on implementing these recommended -authentication methods, refer to the Keycloak documentation. If switching to these methods is impossible in your setup, -you can silence this auditor in the configuration. +This auditor evaluates whether confidential OIDC clients within Keycloak are using mutual TLS (mTLS) or signed JWTs for client authentication, as opposed to the default _shared client secret_ method. +Confidential clients are those that can securely hold credentials, making them responsible for authenticating to Keycloak to access its features. +While using a shared client secret is common, it's recommended to opt for more secure authentication methods such as mTLS or signed JWTs. +These methods provide enhanced security by ensuring that client credentials are not exposed and are authenticated in a manner that is both secure and verifiable. +This recommendation aligns with best practices for securing OAuth clients and protecting resource access. +For more detailed guidance on implementing these recommended authentication methods, refer to the Keycloak documentation. +If switching to these methods is impossible in your setup, you can silence this auditor in the configuration. ## ClientMustNotUseUnencryptedNonlocalRedirectUri -This auditor checks for OIDC clients that transmit authorization responses over unencrypted connections, a practice -strongly discouraged due to the sensitivity of the data involved, such as the OAuth Response Code. To safeguard this -data, `redirect_uri`s must be configured to use HTTPS URIs exclusively, or, in the case of native applications, a -localhost address. This measure is crucial for protecting authorization responses from potential exposure and -interception. The auditor evaluates OIDC clients with active flows utilizing `redirect_uri`s, specifically those with -standard or implicit flows enabled, ensuring they adhere to these security standards. It focuses on identifying and -reporting clients that use `http` in their redirect URIs for non-local addresses, as these present a significant -security risk. Localhost addresses (`localhost`, `127.0.0.1`, `::1`) using `http` are considered exceptions due to their -nature. +This auditor checks for OIDC clients that transmit authorization responses over unencrypted connections, a practice strongly discouraged due to the sensitivity of the data involved, such as the OAuth Response Code. +To safeguard this data, `redirect_uri`s must be configured to use HTTPS URIs exclusively, or, in the case of native applications, a localhost address. +This measure is crucial for protecting authorization responses from potential exposure and interception. +The auditor evaluates OIDC clients with active flows utilizing `redirect_uri`s, specifically those with standard or implicit flows enabled, ensuring they adhere to these security standards. +It focuses on identifying and reporting clients that use `http` in their redirect URIs for non-local addresses, as these present a significant security risk. +Localhost addresses (`localhost`, `127.0.0.1`, `::1`) using `http` are considered exceptions due to their nature. ## ClientUsesCustomRedirectUriScheme -This auditor identifies OIDC clients that utilize custom protocol schemes in their `redirect_uri` configurations, -diverging from the standard `http://` or `https://`. Authorization responses, which include sensitive data such as the -OAuth Response Code, must be securely managed to prevent unauthorized exposure. The employment of custom protocols, -especially when integrating with mobile apps on smartphones (like `myapp://login`), introduces a potential security -risk. +This auditor identifies OIDC clients that use custom protocol schemes in their `redirect_uri` configurations, diverging from the standard `http://` or `https://`. +Authorization responses, which include sensitive data such as the OAuth Response Code, must be securely managed to prevent unauthorized exposure. +The employment of custom protocols, especially when integrating with mobile apps on smartphones (like `myapp://login`), introduces a potential security risk. ## ClientHasUndefinedBaseDomainAndSchema -This auditor checks if OIDC clients have undefined or insufficiently specified redirect URI schemes, which cannot be -effectively audited. Redirect URIs are critical for ensuring the security of OAuth response codes and must be protected -from exposure. Ideally, the `redirect_uri` should be an HTTPS URI or, for native applications, a localhost address. This -auditor identifies clients where the redirect URI, in combination with the client's root URL, does not adequately define -the scheme used. This often indicates that a fully qualified domain name, including the scheme ( -e.g., 'https://example.com/login'), is not defined for either the client root URL or the redirect URIs. To address this -issue, clients should specify clear redirect URIs with proper schemes to enhance security. +This auditor checks if OIDC clients have undefined or insufficiently specified redirect URI schemes, which cannot be effectively audited. +Redirect URIs are critical for ensuring the security of OAuth response codes and must be protected from exposure. +Ideally, the `redirect_uri` should be an HTTPS URI or, for native applications, a localhost address. +This auditor identifies clients where the redirect URI, in combination with the client's root URL, does not adequately define the scheme used. +This often indicates that a fully qualified domain name, including the scheme (e.g., 'https://example.com/login'), is not defined for either the client root URL or the redirect URIs. +To address this issue, clients should specify clear redirect URIs with proper schemes to enhance security. ## ClientShouldNotUseWildcardRedirectURI -This auditor focuses on identifying OIDC clients within Keycloak that utilize wildcard characters in their -`redirect_uri` configurations. Authorization responses, which include sensitive data such as the OAuth Response Code, -necessitate secure handling to prevent unauthorized disclosure. The use of wildcards in redirect URIs introduces -security risks by potentially allowing responses to be redirected to unintended or malicious URLs, thus compromising the -confidentiality and integrity of the exchanged data. +This auditor focuses on identifying OIDC clients within Keycloak that use wildcard characters in their `redirect_uri` configurations. +Authorization responses, which include sensitive data such as the OAuth Response Code, require secure handling to prevent unauthorized disclosure. +The use of wildcards in redirect URIs introduces security risks by potentially allowing responses to be redirected to unintended or malicious URLs, thus compromising the confidentiality and integrity of the exchanged data. -The recommendation is to avoid wildcards in `redirect_uri` settings whenever possible to ensure that authorization -responses are directed to explicitly trusted and predefined locations. If the use of a wildcard is absolutely necessary -for a client's operation, it should be employed with the greatest possible specificity to limit the scope of acceptable -redirect destinations (e.g., `https://example.com/login/token/*` instead of `https://example.com/*`), thereby reducing -the attack surface for data leakage or redirection attacks. +The recommendation is to avoid wildcards in `redirect_uri` settings whenever possible to ensure that authorization responses are directed to explicitly trusted and predefined locations. +If the use of a wildcard is absolutely necessary for a client's operation, it should be employed with the greatest possible specificity to limit the scope of acceptable redirect destinations (e.g., `https://example.com/login/token/*` instead of `https://example.com/*`), thereby reducing the attack surface for data leakage or redirection attacks. -Clients found to employ wildcards in their redirect URIs are flagged for review. Administrators are encouraged to refine -these configurations, removing or narrowing the use of wildcards, to enhance the security of OAuth flows and protect -sensitive information inherent to the authorization process. Once a client has been reviewed, further warnings for it -can be silenced using the tool configuration. +Clients found to employ wildcards in their redirect URIs are flagged for review. +Administrators are encouraged to refine these configurations, removing or narrowing the use of wildcards, to enhance the security of OAuth flows and protect sensitive information inherent to the authorization process. +Once a client has been reviewed, further warnings for it can be silenced using the tool configuration. ## ClientHasErroneouslyConfiguredWildcardURI -This auditor identifies clients with dangerously configured redirect URIs that potentially allow redirects to arbitrary -domains, posing a significant security risk. In OAuth, redirect URIs are crucial for directing the user-agent back to -the application with the authorization code. Keycloak mandates specifying allowed redirect URIs to prevent unauthorized -redirects. However, a configuration error like specifying a wildcard in the domain part of the redirect URI (e.g., -`https://example.com*`) instead of after a path delimiter (e.g., `https://example.com/*`) could let an attacker specify -a malicious domain that still matches the configured pattern (e.g., `https://example.com.attacker.com/`). +This auditor identifies clients with dangerously configured redirect URIs that potentially allow redirects to arbitrary domains, posing a significant security risk. +In OAuth, redirect URIs are crucial for directing the user-agent back to the application with the authorization code. +Keycloak mandates specifying allowed redirect URIs to prevent unauthorized redirects. +However, a configuration error like specifying a wildcard in the domain part of the redirect URI (e.g., `https://example.com*`) instead of after a path delimiter (e.g., `https://example.com/*`) could let an attacker specify a malicious domain that still matches the configured pattern (e.g., `https://example.com.attacker.com/`). ## ClientWithServiceAccountAndOtherFlowEnabled -This auditor examines confidential OIDC clients that have service accounts enabled alongside other authorization flows, -such as standard, implicit, or direct access grants. Typically, confidential clients with service accounts are utilized -solely for server-to-server interactions via the service account. In these scenarios, enabling additional authorization -flows may not be necessary and could potentially increase the client's attack surface. +This auditor examines confidential OIDC clients that have service accounts enabled alongside other authorization flows, such as standard, implicit, or direct access grants. +Typically, confidential clients with service accounts are used solely for server-to-server interactions via the service account. +In these scenarios, enabling additional authorization flows may not be necessary and could potentially increase the client's attack surface. -The recommendation is to disable any extraneous flows for clients primarily used for service account purposes. This -audit generates informational findings to highlight clients where service accounts and additional flows are -simultaneously active, prompting a review to ensure that this configuration aligns with the intended use of the client. +The recommendation is to disable any extraneous flows for clients primarily used for service accounts. +This audit generates informational findings to highlight clients where service accounts and additional flows are simultaneously active, prompting a review to ensure that this configuration aligns with the intended use of the client. -If a client is intentionally using both service accounts and other authorization flows for valid use cases, the finding -can be disregarded. However, we would still recommend splitting the functionality into two clients whenever possible, to -avoid the chance of misconfigurations leading to overprivileged tokens. +If a client is intentionally using both service accounts and other authorization flows for valid use cases, the finding can be disregarded. +However, we would still recommend splitting the functionality into two clients whenever possible, to avoid the chance of misconfigurations leading to overprivileged tokens. ## UsingNonDefaultUserAttributesInClientsWithoutUserProfilesFeatureIsDangerous -This auditor identifies a critical configuration issue where Keycloak clients use custom user attributes without -enabling the User Profiles feature. Keycloak permits the addition of custom attributes to user accounts beyond the -default ones like name, email, and phone number. However, by default, users can edit their own attributes, which poses a -risk if these attributes contain sensitive information used in external systems, such as customer numbers linking -Keycloak accounts to other databases. +This auditor identifies a critical configuration issue where Keycloak clients use custom user attributes without enabling the User Profiles feature. +Keycloak permits the addition of custom attributes to user accounts beyond the default ones like name, email, and phone number. +However, by default, users can edit their own attributes, which pose a risk if these attributes contain sensitive information used in external systems, such as customer numbers linking Keycloak accounts to other databases. -The use of custom user attributes without restrictions is hazardous because it allows users to alter information that -external systems rely on for important operations or access control decisions. This practice must be avoided to ensure -the integrity of the data shared across integrated systems. +The use of custom user attributes without restrictions is hazardous because it allows users to alter information that external systems rely on for important operations or access control decisions. +This practice must be avoided to ensure the integrity of the data shared across integrated systems. -To mitigate this risk, Keycloak introduced the User Profiles feature, allowing administrators to define policies that -restrict user ability to edit specific attributes. This auditor flags clients that utilize custom user attributes -without activating the User Profiles feature, signaling a potential security vulnerability. It encourages the use of the -User Profiles feature to securely manage user attributes and prevent unauthorized modifications, as detailed in -Keycloak's documentation. +To mitigate this risk, Keycloak introduced the User Profiles feature, allowing administrators to define policies that restrict the user's ability to edit specific attributes. +This auditor flags clients that use custom user attributes without activating the User Profiles feature, signaling a potential security vulnerability. +It encourages the use of the User Profiles feature to securely manage user attributes and prevent unauthorized modifications, as detailed in Keycloak's documentation. !!! info - + The user profiles feature was an experimental feature for many versions of Keycloak that was disabled by default. It was enabled by default for newly created realms starting with Keycloak version 24. ## ClientWithDefaultOfflineAccessScope -This auditor warns against clients that include the `offline_access` scope in their default client scopes within -Keycloak, and that have refresh tokens enabled. The `offline_access` scope grants the use of offline tokens, which are -an extended and more potent form of refresh tokens. Offline tokens maintain user login sessions for extended periods, -often lasting several months, and are typically utilized by native applications (e.g., mobile apps) or for -server-to-server connections that require access to a user's account in the user's absence. +This auditor warns against clients that include the `offline_access` scope in their default client scopes within Keycloak, and that have refresh tokens enabled. +The `offline_access` scope grants the use of offline tokens, which are an extended and more potent form of refresh tokens. +Offline tokens maintain user login sessions for extended periods, often lasting several months, and are typically used by native applications (e.g., mobile apps) or for server-to-server connections that require access to a user's account in the user's absence. -While offline tokens are beneficial for certain use cases, their inclusion as a default scope for clients that do not -require such extended access poses a significant security risk. If an offline token is compromised, it could allow an -attacker to maintain unauthorized access to a user's account for an extended period, potentially bypassing regular -session expiration mechanisms. +While offline tokens are beneficial for certain use cases, their inclusion as a default scope for clients that do not require such extended access poses a significant security risk. +If an offline token is compromised, it could allow an attacker to maintain unauthorized access to a user's account for an extended period, potentially bypassing regular session expiration mechanisms. -Clients should be carefully reviewed to ensure that the use of offline tokens is genuinely necessary for their -operation. If not required, it is advisable to remove the `offline_access` scope from the default client scopes, disable -refresh tokens for the client, and/or adjust the configuration to mitigate the potential security risks associated with -long-lived access tokens. This auditor aims to highlight clients with potentially unnecessary default offline access to -prompt a security review and adjustment of their configuration. +Clients should be carefully reviewed to ensure that the use of offline tokens is genuinely necessary for their operation. +If not required, it is advisable to remove the `offline_access` scope from the default client scopes, disable refresh tokens for the client, and/or adjust the configuration to mitigate the potential security risks associated with long-lived access tokens. +This auditor aims to highlight clients with potentially unnecessary default offline access to prompt a security review and adjustment of their configuration. ## ClientWithOptionalOfflineAccessScope -This auditor alerts on Keycloak clients that have the `offline_access` scope set as an optional client scope, and that -have refresh tokens enabled. The `offline_access` scope grants applications the ability to use offline tokens, which -are enhanced versions of refresh tokens with significantly longer lifespans. These tokens are especially useful for -applications requiring prolonged access to a user's account without active user participation, such as mobile -pplications or server-to-server communications. +This auditor alerts on Keycloak clients that have the `offline_access` scope set as an optional client scope, and that have refresh tokens enabled. +The `offline_access` scope grants applications the ability to use offline tokens, which are enhanced versions of refresh tokens with significantly longer lifespans. +These tokens are especially useful for applications requiring prolonged access to a user's account without active user participation, such as mobile applications or server-to-server communications. -However, the inclusion of the `offline_access` scope, even as an optional one, raises security concerns for clients that -do not necessitate such extended access capabilities. The potential exposure of offline tokens poses a risk of long-term -unauthorized access to user accounts if these tokens are compromised. +However, the inclusion of the `offline_access` scope, even as an optional one, raises security concerns for clients that do not require such extended access capabilities. +The potential exposure of offline tokens poses a risk of long-term unauthorized access to user accounts if these tokens are compromised. -Clients leveraging the `offline_access` scope should undergo a thorough review to ensure the necessity of this -capability for their functionality. If the use of offline tokens is not required, it's recommended to either remove -this scope from the list of optional scopes, disable refresh tokens to prevent the issuance of offline tokens, or adjust -the client's configuration to ensure that the use of offline tokens aligns with the security requirements and -operational needs. This warning aims to prompt a reevaluation of the need for offline access, advocating for tighter -control and minimization of potential security vulnerabilities associated with long-lived token usage. +Clients leveraging the `offline_access` scope should undergo a thorough review to ensure the necessity of this capability for their functionality. +If the use of offline tokens is not required, it's recommended to either remove this scope from the list of optional scopes, disable refresh tokens to prevent the issuance of offline tokens, or adjust the client's configuration to ensure that the use of offline tokens aligns with the security requirements and operational needs. +This warning aims to prompt a reevaluation of the need for offline access, advocating for tighter control and minimization of potential security vulnerabilities associated with long-lived token usage. ## ClientWithFullScopeAllowed -This auditor identifies Keycloak clients configured with the 'full scope allowed' setting enabled. In Keycloak, scopes -dictate the breadth of information and roles appended to an access token. Adhering to the principle of least privilege -is crucial in access token configuration, ensuring tokens are granted only the permissions necessary for their intended -tasks. +This auditor identifies Keycloak clients configured with the 'full scope allowed' setting enabled. +In Keycloak, scopes dictate the breadth of information and roles appended to an access token. +Adhering to the principle of least privilege is crucial in access token configuration, ensuring tokens are granted only the permissions necessary for their intended tasks. -When 'full scope allowed' is activated for a client, Keycloak bypasses the scoped limitations and indiscriminately -includes all user roles in the token, effectively treating it as if all possible scopes were granted. This configuration -can lead to the issuance of access tokens with excessive privileges, escalating the risk of unauthorized actions if such -tokens were to be compromised. +When _full scope allowed_ is activated for a client, Keycloak bypasses the scoped limitations and indiscriminately includes all user roles in the token, effectively treating it as if all possible scopes were granted. +This configuration can lead to the issuance of access tokens with excessive privileges, escalating the risk of unauthorized actions if such tokens were to be compromised. -The finding prompts a review of client configurations, encouraging administrators to specifically tailor access token -scopes to match the minimal requirements of each client. Adjusting the scope settings to disable 'full scope allowed' -mitigates the risk associated with overly permissive tokens, aligning with best practices for secure token management. +The finding prompts a review of client configurations, encouraging administrators to specifically tailor access token scopes to match the minimal requirements of each client. +Adjusting the scope settings to disable _full scope allowed_ mitigates the risk associated with overly permissive tokens, aligning with best practices for secure token management. diff --git a/docs/auditors/idp.md b/docs/auditors/idp.md index cb091f1..03c2d6f 100644 --- a/docs/auditors/idp.md +++ b/docs/auditors/idp.md @@ -3,7 +3,8 @@ title: IDP --- # IDP Misconfigurations -Keycloak can be configured to delegate user authentication to an upstream Identity Provider (IDP) like Google, Azure AD, or an LDAP server. The IDP auditors check for problems related to how this integration is configured. +Keycloak can be configured to delegate user authentication to an upstream Identity Provider (IDP) like Google, Azure AD, or an LDAP server. +The IDP auditors check for problems related to how this integration is configured. !!! info @@ -14,60 +15,44 @@ Keycloak can be configured to delegate user authentication to an upstream Identi This auditor warns about Identity Providers configured not to check the signatures of the upstream IDP. Not checking the signatures of the tokens the IDP provides is dangerous, as the tokens are no longer cryptographically protected against tampering. This may lead to an account takeover or other attacks. -We strongly recommend to set up signature checks. +We strongly recommend setting up signature checks. The auditor supports OIDC, Keycloak OIDC, and SAML IDPs. Provider-specific IDPs (like GitHub, GitLab, etc.) do not have an option to disable signature verification and should thus be safe by default. ## OIDCIdentityProviderWithoutPKCE -This auditor warns about OIDC Identity Providers configured within a realm that do not have the Proof Key for Code -Exchange (PKCE) enabled. PKCE is a security enhancement for the authorization code flow in OAuth 2.0 and OpenID -Connect (OIDC) protocols, designed to mitigate several attack vectors, including interception and unauthorized use of -authorization codes. +This auditor warns about OIDC Identity Providers configured within a realm that do not have the Proof Key for Code Exchange (PKCE) enabled. +PKCE is a security enhancement for the authorization code flow in OAuth 2.0 and OpenID Connect (OIDC) protocols, designed to mitigate several attack vectors, including interception and unauthorized use of authorization codes. -The recommendation is for all OIDC Identity Providers, particularly those utilizing the "oidc" or "keycloak-oidc" -provider types, to enable PKCE and set it to use the "S256" method. This configuration is crucial for protecting against -attacks on the OIDC protocol by ensuring that the code challenge and verifier mechanism is securely implemented. +The recommendation is for all OIDC Identity Providers, particularly those using the `oidc` or `keycloak-oidc` provider types, to enable PKCE and set it to use the `S256` method. +This configuration is crucial for protecting against attacks on the OIDC protocol by ensuring that the _code challenge and verifier mechanism_ is securely implemented. -Identity Providers failing to enable PKCE, leaving it unset (which defaults to disabled), or incorrectly using the " -plain" method instead of "S256" are flagged by this auditor. Such configurations expose the authentication process to -potential vulnerabilities, emphasizing the need for immediate corrective actions to uphold security best practices in -authentication flows. +Identity Providers failing to enable PKCE, leaving it unset (which defaults to disabled), or incorrectly using the `plain` method instead of `S256` are flagged by this auditor. +Such configurations expose the authentication process to potential vulnerabilities, emphasizing the need for immediate corrective actions to uphold security best practices in authentication flows. ## IdentityProviderWithOneTimeSync -This auditor highlights external identity providers (IDPs) configured within Keycloak that are set to only synchronize -user information from the upstream IDP at the time of the user's first login, without accepting updates on subsequent -logins. Keycloak's default behavior imports user details (such as name and email address) from the external IDP during -the user's initial login, but it does not automatically update these details based on subsequent changes in the upstream -IDP. +This auditor highlights external identity providers (IDPs) configured within Keycloak that are set to only synchronize user information from the upstream IDP at the time of the user's first login, without accepting updates on later logins. +Keycloak's default behavior imports user details (such as name and email address) from the external IDP during the user's initial login, but it does not automatically update these details based on later changes in the upstream IDP. This setup might be by design, intending to prevent overwriting local modifications to user attributes within Keycloak. -However, if keeping user information in sync with the upstream IDP is required, the auditor recommends considering the -synchronization mode 'Force'. The 'Force' mode ensures that updates made to a user's information in the upstream IDP are -imported into Keycloak at every login, potentially overwriting any local changes. +However, if keeping user information in sync with the upstream IDP is required, the auditor recommends considering the synchronization mode `Force`. +The `Force` mode ensures that updates made to a user's information in the upstream IDP are imported into Keycloak at every login, potentially overwriting any local changes. -Entities configured without the 'Force' sync mode are identified by this auditor to encourage a review of the intended -behavior regarding user data synchronization. If the current setup aligns with the organizational requirements, the -finding can be ignored. Otherwise, updating the sync mode to 'Force' may be advisable to ensure consistent and -up-to-date user information across systems. +Entities configured without the `Force` sync mode are identified by this auditor to encourage a review of the intended behavior regarding user data synchronization. +If the current setup aligns with the organizational requirements, the finding can be ignored. +Otherwise, updating the sync mode to `Force` may be advisable to ensure consistent and up-to-date user information across systems. ## IdentityProviderWithMappersWithoutForceSyncMode -This auditor targets Keycloak configurations where external identity providers are set up with Identity Provider Mappers -but are not configured to update user information from the upstream IDP beyond the initial login. Keycloak's default -behavior for Identity Provider Mappers is to import data (e.g., group assignments or roles) from the upstream IDP's -access token only once, during the user's first login, without reflecting any subsequent changes in the upstream IDP. +This auditor targets Keycloak configurations where external identity providers are set up with Identity Provider Mappers but are not configured to update user information from the upstream IDP beyond the initial login. +Keycloak's default behavior for Identity Provider Mappers is to import data (e.g., group assignments or roles) from the upstream IDP's access token only once, during the user's first login, without reflecting any later changes in the upstream IDP. -This configuration could lead to security issues or inconsistencies in user permissions if the upstream IDP modifies -user roles, groups, or other attributes that affect access control within Keycloak-managed services. If the use of -mappers to assign static groups or roles without future updates is intentional, this finding may be disregarded. +This configuration could lead to security issues or inconsistencies in user permissions if the upstream IDP modifies user roles, groups, or other attributes that affect access control within Keycloak-managed services. +If the use of mappers to assign static groups or roles without future updates is intentional, this finding may be disregarded. -However, if dynamic synchronization of user attributes and roles with the upstream IDP is required, it's advised to -adjust the sync mode to 'Force'. This setting can be applied globally to the IDP, affecting all user data, including -name and email, or specifically to relevant mappers, allowing for selective updates based on upstream changes. +However, if dynamic synchronization of user attributes and roles with the upstream IDP is required, it's advised to adjust the sync mode to `Force`. +This setting can be applied globally to the IDP, affecting all user data, including name and email, or specifically to relevant mappers, allowing for selective updates based on upstream changes. -This finding carries a higher severity compared to the general recommendation for enabling 'Force' sync mode due to the -explicit use of Identity Provider Mappers, indicating a reliance on upstream IDP data for crucial access control -decisions. \ No newline at end of file +This finding carries a higher severity compared to the general recommendation for enabling `Force` sync mode due to the explicit use of Identity Provider Mappers, indicating a reliance on upstream IDP data for crucial access control decisions. diff --git a/docs/auditors/index.md b/docs/auditors/index.md index 72cb737..3734a81 100644 --- a/docs/auditors/index.md +++ b/docs/auditors/index.md @@ -7,9 +7,7 @@ title: Introduction kcwarden comes with a number of pre-built detection rules that can detect common Keycloak misconfigurations. We call these _auditors_, and each auditor checks for one specific problem. There are auditors for OAuth clients, scopes, upstream Identity Provider (IDP) configurations, and realm settings. -The auditors are based on a combination of -the [OAuth 2.0 Security Best Current Practices RFC Draft (Version 24)](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-24), -and additional, Keycloak-specific checks. +The auditors are based on a combination of the [OAuth 2.0 Security Best Current Practices RFC Draft (Version 24)](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-24), and additional, Keycloak-specific checks. ## Running Auditors @@ -47,21 +45,21 @@ The following areas aren't covered at all: - Required Actions - Anything related to the implementation of the applications working with the clients (out of scope) -We would be grateful for input on which checks you would like to see - ideally with a description of what exactly to check for, what a good and an insecure configuration would look like, and what the impact of the misconfiguration would be. -Feel free to open an issue in our GitHub and we'll be happy to add it to the code. +We would be grateful for input on which checks you would like to see—ideally with a description of what exactly to check for, what a good and an insecure configuration would look like, and what the impact of the misconfiguration would be. +Feel free to open an issue in our GitHub, and we'll be happy to add it to the code. ## Silencing Findings If you run kcwarden for the first time on a Keycloak configuration, chances are that you will receive a large number of findings. -kcwarden tends to err on the side of reporting too much instead of too little, so there are likely to be some findings -that you don't want to act on because you have good reasons to configure the system in this way, even though it may not -be 100% compliant with official recommendations. +kcwarden tends to err on the side of reporting too much instead of too little. +Thus, there are likely to be some findings that you don't want to act on because you have good reasons to configure the system in this way, even though it may not be 100% compliant with official recommendations. In these cases, you can ignore specific findings or entire auditors to prevent kcwarden from reporting them again. ### Ignoring a Specific Finding -To ignore a specific finding, you can [create a config file](../usage.md#generate-config-template) and add the specific entity that was flagged to the allowlist. For example, if you have a client `mobile_app` that is used by a native mobile application that requires the use of offline access tokens, you can silence the warning about the use of these tokens for this specific client with the following configuration entry: +To ignore a specific finding, you can [create a config file](../usage.md#generate-config-template) and add the specific entity that was flagged to the allowlist. +For example, if you have a client `mobile_app` that is used by a native mobile application that requires the use of offline access tokens, you can silence the warning about the use of these tokens for this specific client with the following configuration entry: ```yaml auditors: @@ -84,4 +82,4 @@ auditors: # Due to the use of legacy software, we need to allow client-secret # auth for the forseeable future. Allowlist all clients. - .* -``` \ No newline at end of file +``` diff --git a/docs/auditors/realm.md b/docs/auditors/realm.md index d10e9b8..3040656 100644 --- a/docs/auditors/realm.md +++ b/docs/auditors/realm.md @@ -7,77 +7,57 @@ These auditors check the realm-wide settings, like token lifetimes and global se ## RefreshTokensShouldBeRevokedAfterUse -This auditor warns about the configuration within Keycloak realms where refresh tokens are not invalidated after each -use. Refresh tokens are critical for maintaining active user sessions by allowing clients to request new access tokens -once the current ones expire. While this mechanism supports seamless user experiences, especially in long-lived -sessions, it introduces security risks if refresh tokens are compromised. An exposed refresh token could potentially -allow attackers to gain prolonged unauthorized access to user accounts. +This auditor warns about the configuration within Keycloak realms where refresh tokens are not invalidated after each use. +Refresh tokens are critical for maintaining active user sessions by allowing clients to request new access tokens once the current ones expire. +While this mechanism supports seamless user experiences, especially in long-lived sessions, it introduces security risks if refresh tokens are compromised. +An exposed refresh token could potentially allow attackers to gain prolonged unauthorized access to user accounts. -To mitigate such risks, it is strongly recommended that refresh tokens be configured to rotate upon each use, thereby -invalidating the old token and issuing a new one for subsequent requests. This practice ensures that even if a refresh -token were to be leaked, it would be quickly rendered useless once used by the legitimate client. +To mitigate such risks, it is strongly recommended that refresh tokens be configured to rotate upon each use, thereby invalidating the old token and issuing a new one for later requests. +This practice ensures that even if a refresh token were to be leaked, it would be quickly rendered useless once used by the legitimate client. -However, it's important to note that enabling refresh token rotation may lead to complications under certain -circumstances, such as when a client issues multiple refresh tokens to the same user. This can result in unexpected -behavior and potential session disruptions. Administrators are advised to review relevant Keycloak issues and -documentation, such as the one mentioned in the auditor's reference, to understand the implications fully and configure -their realms in a manner that balances usability and security effectively. +However, it's important to note that enabling refresh token rotation may lead to complications under certain circumstances, such as when a client issues multiple refresh tokens to the same user. +This can result in unexpected behavior and potential session disruptions. +Administrators are advised to review relevant Keycloak issues and documentation, such as the one mentioned in the auditor's reference, to understand the implications fully and configure their realms in a manner that balances usability and security effectively. -Realms identified with refresh token revocation disabled are highlighted by this auditor to encourage a review of their -token management policies, aiming to enhance security without significantly impacting user experience. +This auditor highlights realms identified with refresh token revocation disabled to encourage a review of their token management policies, aiming to enhance security without significantly impacting user experience. ## RefreshTokenReuseCountShouldBeZero -This auditor raises a warning about Keycloak realms configured to allow refresh tokens to be used more than once before -being revoked. Refresh tokens play a vital role in OAuth 2.0 by enabling clients to obtain new access tokens, thus -facilitating long-lived sessions without requiring the user to re-authenticate frequently. While this feature enhances -user experience, improperly managed refresh tokens can pose significant security risks, particularly if they are leaked -or exposed to malicious actors. +This auditor raises a warning about Keycloak realms configured to allow refresh tokens to be used more than once before being revoked. +Refresh tokens play a vital role in OAuth 2.0 by enabling clients to get new access tokens, thus facilitating long-lived sessions without requiring the user to re-authenticate frequently. +While this feature enhances user experience, improperly managed refresh tokens can pose significant security risks, particularly if they are leaked or exposed to malicious actors. -The recommended security practice is to rotate refresh tokens after each use, immediately invalidating the previous -token upon issuing a new one. This approach minimizes the window of opportunity for unauthorized use of a leaked token. -However, in configurations where the refresh token maximum reuse count is set to allow multiple uses, the effectiveness -of token rotation as a security measure is diminished. +The recommended security practice is to rotate refresh tokens after each use, immediately invalidating the previous token upon issuing a new one. +This approach minimizes the window of opportunity for unauthorized use of a leaked token. +However, in configurations where the refresh token maximum reuse count is set to allow multiple uses, the effectiveness of token rotation as a security measure is diminished. -Administrators should consider setting the refresh token maximum reuse count to zero, enforcing token rotation and -revocation after a single use. While mindful of potential challenges such as disruptions in user sessions, especially in -scenarios where multiple refresh tokens might be issued to the same user by the same client, it's crucial to balance -usability with security. +Administrators should consider setting the refresh token maximum reuse count to zero, enforcing token rotation and revocation after a single use. +While mindful of potential challenges such as disruptions in user sessions, especially in scenarios where the same client might issue multiple refresh tokens to the same user, it's crucial to balance usability with security. -Realms found to permit refresh token reuse, contrary to best practices for secure token management, are flagged for -review. Administrators are encouraged to reassess their token revocation settings in light of security recommendations -and the potential implications for application behavior, aiming to enhance the overall security posture of their -Keycloak deployments. +Realms found to permit refresh token reuse, contrary to best practices for secure token management, are flagged for review. +Administrators are encouraged to reassess their token revocation settings in light of security recommendations and the potential implications for application behavior, aiming to enhance the overall security posture of their Keycloak deployments. ## RealmSelfRegistrationEnabled This auditor flags realms within Keycloak where self-registration is enabled, allowing anyone to create an account. -While self-registration can be a convenient feature for public applications or services aiming to simplify the user -onboarding process, it might not be appropriate for all contexts. Enabling self-registration can expose the system to -risks such as unauthorized access, fake account creation, and potential abuse. +While self-registration can be a convenient feature for public applications or services aiming to simplify the user onboarding process, it might not be appropriate for all contexts. +Enabling self-registration can expose the system to risks such as unauthorized access, fake account creation, and potential abuse. -The decision to allow self-registration should be carefully considered, taking into account the nature of the -application, the expected user base, and the potential security implications. In scenarios where strict control over -user access is required, or where user verification is critical, it may be advisable to disable self-registration and -opt for a more controlled account creation process. +The decision to allow self-registration should be carefully considered, taking into account the nature of the application, the expected user base, and the potential security implications. +In scenarios where strict control over user access is required, or where user verification is critical, it may be advisable to disable self-registration and opt for a more controlled account creation process. -Realms identified with self-registration enabled are brought to attention for review. Administrators should evaluate -whether this setting aligns with their security policies and operational requirements, adjusting the configuration as -necessary to safeguard against unintended or unauthorized access. +Realms identified with self-registration enabled are brought to attention for review. +Administrators should evaluate whether this setting aligns with their security policies and operational requirements, adjusting the configuration as necessary to safeguard against unintended or unauthorized access. ## RealmEmailVerificationDisabled -This auditor brings attention to Keycloak realms where email verification is disabled. Email verification is a crucial -feature that ensures the authenticity of the email addresses provided by users during registration. It typically -involves sending a verification link or code to the user's email address, which the user must acknowledge to complete -their registration process. This double opt-in mechanism helps in confirming that the email address is valid and -accessible by the user, adding a layer of trustworthiness to user accounts. +This auditor brings attention to Keycloak realms where email verification is disabled. +Email verification is a crucial feature that ensures the authenticity of the email addresses provided by users during registration. +It typically involves sending a verification link or code to the user's email address, which the user must acknowledge to complete their registration process. +This double opt-in mechanism helps in confirming that the email address is valid and accessible by the user, adding a layer of trustworthiness to user accounts. -Disabling email verification can lead to several issues, including the inability to communicate reliably with users, -increased risk of fraudulent account creation, and potential challenges in implementing effective password recovery -mechanisms. It may also compromise the integrity of user data, especially in applications where the email address is a -critical component of the user's identity. +Disabling email verification can lead to several issues, including the inability to communicate reliably with users, increased risk of fraudulent account creation, and potential challenges in implementing effective password recovery mechanisms. +It may also compromise the integrity of user data, especially in applications where the email address is a critical part of the user's identity. -Realms detected with email verification turned off are highlighted for administrators to reassess this configuration -choice. Depending on the application's requirements and the level of trust needed in user-provided email addresses, -enabling email verification may be advisable to enhance security and ensure the credibility of user accounts. +Realms detected with email verification turned off are highlighted for administrators to reassess this configuration choice. +Depending on the application's requirements and the level of trust needed in user-provided email addresses, enabling email verification may be advisable to enhance security and ensure the credibility of user accounts. diff --git a/docs/auditors/scope.md b/docs/auditors/scope.md index 9422753..6eadd29 100644 --- a/docs/auditors/scope.md +++ b/docs/auditors/scope.md @@ -11,22 +11,16 @@ These auditors check the configuration of the OIDC scopes configured in Keycloak ## UsingNonDefaultUserAttributesInScopesWithoutUserProfilesFeatureIsDangerous -This auditor focuses on the usage of non-default user attributes in client scopes within Keycloak, particularly when the -server does not have the User Profiles feature enabled. Keycloak permits the assignment of custom attributes to user -profiles beyond the standard attributes (e.g., name, email, and phone number). However, without proper restrictions, -users might modify their own attributes via the user console, potentially affecting the reliability of these attributes -in external systems. For instance, a customer number stored as a custom attribute could be altered, disrupting the -linkage between a Keycloak account and a customer database. - -The danger arises when these custom attributes are employed in client scopes without enabling Keycloak's experimental -User Profiles feature. This feature allows administrators to define policies controlling attribute editability, thus -preventing users from altering sensitive information. - -This auditor raises a flag when client scopes utilize custom user attributes, and the realm lacks the User Profiles -feature activation. It suggests a review of the utilization of these attributes within scopes, advocating for the -activation of User Profiles and the establishment of attribute editing policies to safeguard sensitive information. - -The finding is particularly severe because the lack of restriction could lead to security vulnerabilities, where -critical information stored in user attributes could be tampered with by the users themselves or exploited by attackers. -Implementing the User Profiles feature and adjusting scope configurations accordingly is recommended to ensure data -integrity and security. \ No newline at end of file +This auditor focuses on the usage of non-default user attributes in client scopes within Keycloak, particularly when the server does not have the User Profiles feature enabled. +Keycloak permits the assignment of custom attributes to user profiles beyond the standard attributes (e.g., name, email, and phone number). +However, without proper restrictions, users might modify their own attributes via the user console, potentially affecting the reliability of these attributes in external systems. +For instance, a customer number stored as a custom attribute could be altered, disrupting the linkage between a Keycloak account and a customer database. + +The danger arises when these custom attributes are employed in client scopes without enabling Keycloak's experimental User Profiles feature. +This feature allows administrators to define policies controlling attribute editability, thus preventing users from altering sensitive information. + +This auditor raises a flag when client scopes use custom user attributes, and the realm lacks the User Profiles feature activation. +It suggests reviewing the use of these attributes within scopes, advocating for the activation of User Profiles and the establishment of attribute editing policies to safeguard sensitive information. + +The finding is particularly severe because the lack of restriction could lead to security vulnerabilities, where critical information stored in user attributes could be tampered with by the users themselves or exploited by attackers. +Implementing the User Profiles feature and adjusting scope configurations accordingly is recommended to ensure data integrity and security. diff --git a/docs/development.md b/docs/development.md index afe3566..41a2173 100644 --- a/docs/development.md +++ b/docs/development.md @@ -16,8 +16,7 @@ It also requires that you have git installed on your system. ## Linting and Formatting `ruff` is used as linter and code formatter. -It can be executed using `poetry run ruff . --fix` for linting with automatic fixes and `poetry run ruff format .` for -formatting. +It can be executed using `poetry run ruff . --fix` for linting with automatic fixes and `poetry run ruff format .` for formatting. The pipeline only succeeds if the code is formatted and there are no linting issues. @@ -25,11 +24,9 @@ The pipeline only succeeds if the code is formatted and there are no linting iss The unit tests can be run with `poetry run pytest`. -The integration tests that actually start Keycloak containers using Docker can be executed -with `poetry run pytest --integration`. +The integration tests that actually start Keycloak containers using Docker can be executed with `poetry run pytest --integration`. The Keycloak versions for which the tests are executed can be found in [`conftest.py`](./tests/integration/conftest.py). -It can be overridden by setting the environment variable `INTEGRATION_TEST_KEYCLOAK_VERSIONS` to a space-separated list -of Keycloak container image tags (see [quay.io](https://quay.io/repository/keycloak/keycloak?tab=tags)). +It can be overridden by setting the environment variable `INTEGRATION_TEST_KEYCLOAK_VERSIONS` to a space-separated list of Keycloak container image tags (see [quay.io](https://quay.io/repository/keycloak/keycloak?tab=tags)). ## Docker Image @@ -45,16 +42,13 @@ or buildah build -f Docker/dev.Dockerfile -t kcwarden:latest . ``` -It uses a multi-stage build to first build the application as Python wheel and afterward install this wheel in a second -image. +It uses a multi-stage build to first build the application as Python wheel and afterward install this wheel in a second image. ## Release -kcwarden is released as Python package on [PyPI](https://pypi.org/project/kcwarden/) and as Docker image -on [ghcr.io](https://github.com/iteratec/kcwarden/pkgs/container/kcwarden). +kcwarden is released as Python package on [PyPI](https://pypi.org/project/kcwarden/) and as Docker image on [ghcr.io](https://github.com/iteratec/kcwarden/pkgs/container/kcwarden). -For publishing these artifacts, a release is created on GitHub and then a GitHub workflow creates and publishes the -packages. +For publishing these artifacts, a release is created on GitHub and then a GitHub workflow creates and publishes the packages. ## Build the Docs @@ -62,5 +56,4 @@ The documentation is created using [MkDocs](https://www.mkdocs.org/) and lives i The dependencies for _MkDocs_ can be installed using this command: `poetry install --with docs`. Afterward, the documentation can be built using `poetry run mkdocs build`. The static output is then located in the `site` directory. -A development server that serves the documentation, watches for changes and automatically re-creates the site can be -spun up using `poetry run mkdocs serve`. \ No newline at end of file +A development server that serves the documentation, watches for changes and automatically re-creates the site can be spun up using `poetry run mkdocs serve`. diff --git a/docs/index.md b/docs/index.md index a16443f..36b739f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -5,9 +5,8 @@ title: About # kcwarden—A Keycloak Config Auditor kcwarden is an Open Source [Keycloak](https://www.keycloak.org/) configuration auditor tool, developed by [iteratec](https://iteratec.com). -It aims to automatically detect issues with your Keycloak realms by parsing a realm export and looking for common -misconfigurations. +It aims to automatically detect issues with your Keycloak realms by parsing a realm export and looking for common misconfigurations. Its focus is on security and correctness issues. [Installation](installation.md){: .btn .btn-primary role=button } -[Usage](usage.md){: .btn .btn-primary role=button } \ No newline at end of file +[Usage](usage.md){: .btn .btn-primary role=button } diff --git a/docs/installation.md b/docs/installation.md index 660079a..7ed2ddb 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -14,8 +14,7 @@ You can install _kcwarden_ from PyPI: pip install kcwarden ``` -You might want to use [pipx](https://github.com/pypa/pipx) to automatically encapsulate the dependencies of _kcwarden_ -in a virtual environment. +You might want to use [pipx](https://github.com/pypa/pipx) to automatically encapsulate the dependencies of _kcwarden_ in a virtual environment. ## Docker @@ -25,4 +24,4 @@ Alternatively, _kcwarden_ is provided as a Docker image and can be executed in t docker run --rm ghcr.io/iteratec/kcwarden:latest ``` -Using this way, you need to replace the `kcwarden` call with the Docker command above. \ No newline at end of file +Using this way, you need to replace the `kcwarden` call with the Docker command above. diff --git a/docs/monitors/client_monitor.md b/docs/monitors/client_monitor.md index eff1721..87e3d03 100644 --- a/docs/monitors/client_monitor.md +++ b/docs/monitors/client_monitor.md @@ -4,7 +4,8 @@ title: Clients # Client Monitors -You can use client monitors to keep an eye on the configuration of specific OIDC clients. Please be sure that you have read our [general introduction to Monitors](index.md) to understand the context of this feature. +You can use client monitors to keep an eye on the configuration of specific OIDC clients. +Please be sure that you have read our [general introduction to Monitors](index.md) to understand the context of this feature. ## ClientWithSensitiveRole @@ -37,7 +38,7 @@ monitors: The field `role` and `allowed` fields support the Python RegEx syntax, so you can match all roles beginning with `org_` by writing `^org_.*` as the role name you want to monitor, and similarly use wildcards in your allowlists. If you want to match a realm role (i.e., a role defined on the level of the Keycloak realm), put "realm" as the role-client. If you are using a client role (i.e., a role defined on the level of an individual client, like the built-in realm-management roles), put the name of the client that defines the role in the field. -The role-client field does not support regular expressions and is case-sensitive. +The `role-client` field does not support regular expressions and is case-sensitive. !!! info @@ -57,7 +58,7 @@ In general, to generate an access token containing a specific scope, one of the Additionally, in order for the scope name to appear in the token, the scope must have the option "include in token scope" enabled - however, this auditor does not enforce this setting, as you may want to monitor scope assignments for other reasons than their inclusion into the access token (e.g., because they are used to include additional mappers or other features), and enforcing this limitation would lead to false negatives. -In order to monitor a specific scope, you can add the following to your config file: +To monitor a specific scope, you can add the following to your config file: ```yaml monitors: diff --git a/docs/monitors/group_monitor.md b/docs/monitors/group_monitor.md index 76be015..dde6cfb 100644 --- a/docs/monitors/group_monitor.md +++ b/docs/monitors/group_monitor.md @@ -3,7 +3,7 @@ title: Group --- # Group Monitor -You can use grouo monitors to detect if groups have incorrect configurations. +You can use group monitors to detect if groups have incorrect configurations. Please be sure that you have read our [general introduction to Monitors](index.md) to understand the context of this feature. ## GroupWithSensitiveRole @@ -29,4 +29,4 @@ Set the `role-client` field to `realm` when monitoring realm roles, or to the na !!! info - If you want to create comprehensive monitoring for a single role, we recommend combining this monitor with the [ClientWithSensitiveRole](client_monitor.md#clientwithsensitiverole) and [ServiceAccountWithSensitiveRole](service_account_monitor.md#serviceaccountwithsensitiverole) monitors to achieve more comprehensive coverage. \ No newline at end of file + If you want to create comprehensive monitoring for a single role, we recommend combining this monitor with the [ClientWithSensitiveRole](client_monitor.md#clientwithsensitiverole) and [ServiceAccountWithSensitiveRole](service_account_monitor.md#serviceaccountwithsensitiverole) monitors to achieve more comprehensive coverage. diff --git a/docs/monitors/index.md b/docs/monitors/index.md index 654b995..280a3c5 100644 --- a/docs/monitors/index.md +++ b/docs/monitors/index.md @@ -4,10 +4,18 @@ title: Introduction # Security Guardrails -kcwarden can automatically detect many common misconfigurations using its Auditors feature. However, because it doesn't have any knowledge about your specific context, it cannot detect misconfigurations specific to your setup, like incorrectly assigned roles or scopes. In practice, these can be as bad as (or even worse than) more generic misconfigurations, because it can expose application permissions to unintended users. Additionally, such errors can creep in during operation, meaning that checking for them once isn't enough - ideally, you want to continuously monitor for these problems and be notified as soon as they crop up. +kcwarden can automatically detect many common misconfigurations using its Auditors feature. +However, because it doesn't have any knowledge about your specific context, it cannot detect misconfigurations specific to your setup, like incorrectly assigned roles or scopes. +In practice, these can be as bad as (or even worse than) more generic misconfigurations, because it can expose application permissions to unintended users. +Additionally, such errors can creep in during operation, meaning that checking for them once isn't enough. +Ideally, you want to continuously monitor for these problems and be notified as soon as they crop up. ## Introducing Monitors -To cover this use case, kcwarden contains a feature called _Monitors_, which allows you to configure custom checks using your knowledge of your specific setup. For example, let's say that you have a role `org_admin`, which allows holders to configure organization-wide settings in your application. Clearly, this shouldn't be assigned to just anyone. Since all roles in your Keycloak setup are assigned to groups (instead of directly to users), let's create a monitor that checks which groups the role is assigned to, by adding the following to the configuration file: + +To cover this use case, kcwarden contains a feature called _Monitors_, which allows you to configure custom checks using your knowledge of your specific setup. +For example, let's say that you have a role `org_admin`, which allows holders to configure organization-wide settings in your application. +Clearly, this shouldn't be assigned to just anyone. +Since all roles in your Keycloak setup are assigned to groups (instead of directly to users), let's create a monitor that checks which groups the role is assigned to, by adding the following to the configuration file: ```yaml monitors: @@ -21,18 +29,23 @@ monitors: note: org_admin controls access to org management. Only the group /OrgAdm should have it. ``` -Running kcwarden with this configuration file will flag any groups that have this role assigned and aren't in the allowlist. You can then periodically run it on the current version of the realm configuration to ensure that there hasn't been any dangerous config drift. +Running kcwarden with this configuration file will flag any groups that have this role assigned and aren't in the allowlist. +You can then periodically run it on the current version of the realm configuration to ensure that there hasn't been any dangerous config drift. !!! info We recommend testing monitors with an empty allowlist first to ensure that it returns results. Once you are satisfied that the detecting is working well, add your allowlist entries and test again. -kcwarden supports several different monitors. Check the documentation of the individual monitors on the following pages to see what you can monitor with them. Or contribute your own, if your use case is not yet supported. +kcwarden supports several different monitors. +Check the documentation of the individual monitors on the following pages to see what you can monitor with them. +Or contribute your own if your use case is not yet supported. ## Configuring Monitors -Generally, you can configure monitors as part of the kcwarden config file - generate a template using `kcwarden generate-config-template > config.yaml`, make your changes, and pass in the resulting file using `kcwarden audit -c config.yaml realm-dump.json`. -Monitors are configured under the top-level key `monitors` in the YAML file. -Each monitor has its own entry in the config list, and you can put as many individual monitor configuration into the config list as you want: + +Generally, you can configure monitors as part of the kcwarden config file: +Generate a template using `kcwarden generate-config-template > config.yaml`, make your changes, and pass in the resulting file using `kcwarden audit -c config.yaml realm-dump.json`. +Monitors are configured under the top-level key `monitors` in the YAML configuration file. +Each monitor has its own entry in the config list, and you can put as much individual monitor configuration into the config list as you want: ```yaml monitors: @@ -55,12 +68,14 @@ monitors: Part of the configuration options for each monitor are specific to that monitor, but two are generic: `severity` and `note`. ### Severity + The severity describes how serious a violation of the security guardrail would be. You can set it to one of the following: `Info`, `Low`, `Medium`, `High`, `Critical`. This can be used to prioritize your remediation work. You can also filter the results using the `--min-severity` switch. ### Note + The note is a human-readable description of the semantics of the configuration. It can contain arbitrary text, and will be returned as part of the output of the auditor when it has a finding. Use it to remind yourself why you set up this rule, and what the consequences of violating it are. diff --git a/docs/monitors/protocol_mapper_monitor.md b/docs/monitors/protocol_mapper_monitor.md index 6c6f713..03d1063 100644 --- a/docs/monitors/protocol_mapper_monitor.md +++ b/docs/monitors/protocol_mapper_monitor.md @@ -3,6 +3,7 @@ title: Mappers --- # Protocol Mapper Monitors + You can use protocol mapper monitors to keep an eye on the configuration of specific protocol mappers. Please be sure that you have read our [general introduction to Monitors](index.md) to understand the context of this feature. ## ProtocolMapperWithConfig @@ -44,7 +45,7 @@ One of them may look like this: } ``` -This is a mapper that takes the "user_id" field from the user attributes and writes it to the access token in the `user_id` key (specified by the `claim.name` key of the configuration). +This is a mapper that takes the `user_id` field from the user attributes and writes it to the access token in the `user_id` key (specified by the `claim.name` key of the configuration). For the sake of demonstration, let's say you want to ensure that only a user attribute mapper can write to that key, and no other mapper type can do so. The resulting monitor would look like this: @@ -60,7 +61,8 @@ monitors: note: The user_id claim should only be writable from a user attribute mapper ``` -To further ensure the correctness of that field in the access tokens, you could also write a second detection that ensures that usermodel-attribute-mappers can only write to the field from the user_id user attribute, and cannot use any other attributes. +To further ensure the correctness of that field in the access tokens, you could also write a second monitor. +This second monitor ensures that usermodel-attribute-mappers can only write to the field from the `user_id` user attribute, and cannot use any other attributes. Add the following right below the last line of the previous configuration: ```yaml @@ -75,7 +77,7 @@ Add the following right below the last line of the previous configuration: As seen in the two examples, both the `protocol-mapper-type` and any value below `matched-config` support regular expressions, so you can use negative lookahead to check for violations of your rules. You can perform matching on arbitrary keys in the `config` part of the JSON object. -If a key specified in `matched-config` is not found, the entire protocol mapper is treated as not matching - however, since the config keys should be consistent across different instances of the same protocol mapper type, this should rarely be an issue in practice. +If a key specified in `matched-config` is not found, the entire protocol mapper is treated as not matching—however, since the config keys should be consistent across different instances of the same protocol mapper type, this should rarely be an issue in practice. !!! info diff --git a/docs/monitors/service_account_monitor.md b/docs/monitors/service_account_monitor.md index e09ad80..9783c84 100644 --- a/docs/monitors/service_account_monitor.md +++ b/docs/monitors/service_account_monitor.md @@ -3,12 +3,14 @@ title: Service Accounts --- # Service Account Monitors + Service accounts are often used to authenticate machine-to-machine communication using Keycloak. Thus, they are often set up with fairly powerful roles and can generate highly privileged tokens. Service Account Monitors allow you to keep an eye on their configuration, to detect overprivileged or misconfigured service accounts. Please be sure that you have read our [general introduction to Monitors](index.md) to understand the context of this feature. ## ServiceAccountWithSensitiveRole + In a large deployment with many roles and service accounts, configuration drift can be a real concern. Service accounts may have roles assigned to them that should have been removed months ago, or that were assigned in error. For certain roles, this can pose a threat to the security of the system. @@ -48,7 +50,7 @@ If you are aware of other ways to assign roles to service accounts, let us know ## ServiceAccountWithGroup Service accounts are represented as a special type of user in Keycloak. -This user can be assigned roles, but also also be added to groups and inherit roles and other settings that way. +This user can be assigned roles, but also be added to groups and inherit roles and other settings that way. Thus, it can be useful to monitor the group assignments of service accounts as well. ```yaml diff --git a/docs/usage.md b/docs/usage.md index 76d3283..10419c7 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -13,8 +13,7 @@ It can be acquired using the Keycloak administration interface or using the `dow kcwarden download --realm $REALM --user $USER --output $KEYCLOAK_CONFIG_FILE $KEYCLOAK_BASE_URL ``` -Additionally, you might specify a separate realm for login, e.g., the `master` realm, using the `--auth-realm` -parameter. +Additionally, you might specify a separate realm for login, e.g., the `master` realm, using the `--auth-realm` parameter. ## Running the Audit @@ -30,7 +29,7 @@ There are several optional parameters to customize the execution: |-----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------| | `--format` | The output format of the findings. Can be plain text (`txt`), `csv` or `json`. | | `--output` | The path to the output file. If not provided, the output will be printed on stdout. | -| `--min-severity` | The minimum severity of findings that should be reported. Can be one of INFO, LOW, MEDIUM, HIGH, CRITICAL. | +| `--min-severity` | The minimum severity of findings that should be reported. Can be one of INFO, LOW, MEDIUM, HIGH, CRITICAL. | | `--auditors` | Specify the exact auditors to run, separated by space (others will be ignored). | | `--config` | Provide a config file with auditor-specific exclusions and parameters. Generate a template using [generate-config-template](#generate-config-template). | | `--ignore-disabled-clients` | When set, will not audit disabled OIDC clients. | @@ -52,8 +51,7 @@ If `--output` is not specified, it is printed to stdout. This feature is not part of the main scope of _kcwarden_ and thus only partly maintained. -There is an additional command `review` that outputs roles and its usages on services accounts and groups as matrix for -human analysis. +There is an additional command `review` that outputs roles and its usages on services accounts and groups as matrix for human analysis. ```shell kcwarden review $KEYCLOAK_CONFIG_FILE