Compare languages | Модуль user-authn: FAQ

Как защитить мое приложение?

How to secure my application?

Чтобы включить аутентификацию через Dex для приложения, выполните следующие шаги:

  1. Создайте custom resource DexAuthenticator.

To enable Dex authentication for your application, follow these steps:

  1. Create a DexAuthenticator custom resource.

Создание DexAuthenticator в кластере приводит к созданию экземпляра oauth2-proxy, подключенного к Dex. После появления custom resource DexAuthenticator в указанном namespace появятся необходимые объекты Deployment, Service, Ingress, Secret.

Creating DexAuthenticator in a cluster results in an oauth2-proxy instance being created. The latter is connected to Dex. Once the DexAuthenticator custom resource becomes available, the necessary Deployment, Service, Ingress, Secret objects will be created in the specified namespace.

Пример custom resource DexAuthenticator:

An example of the DexAuthenticator custom resource:

yaml apiVersion: deckhouse.io/v1 kind: DexAuthenticator metadata: Префикс имени подов Dex authenticator. Например, если префикс имени app-name, то поды Dex authenticator будут вида app-name-dex-authenticator-7f698684c8-c5cjg. name: app-name Namespace, в котором будет развернут Dex authenticator. namespace: app-ns spec: Домен вашего приложения. Запросы на него будут перенаправляться для прохождения аутентификацию в Dex. applicationDomain: “app-name.kube.my-domain.com” Отправлять ли Authorization: Bearer header приложению. Полезно в связке с auth_request в NGINX. sendAuthorizationHeader: false Имя Secret’а с SSL-сертификатом. applicationIngressCertificateSecretName: “ingress-tls” Название Ingress-класса, которое будет использоваться в создаваемом для Dex authenticator Ingress-ресурсе. applicationIngressClassName: “nginx” Время, на протяжении которого пользовательская сессия будет считаться активной. keepUsersLoggedInFor: “720h” Список групп, пользователям которых разрешено проходить аутентификацию. allowedGroups:

  • everyone
  • admins Список адресов и сетей, с которых разрешено проходить аутентификацию. whitelistSourceRanges:
  • 1.1.1.1/32
  • 192.168.0.0/24

yaml apiVersion: deckhouse.io/v1 kind: DexAuthenticator metadata: Dex authenticator pod name prefix. For example, if the name prefix is app-name, then Dex authenticator pods will look like app-name-dex-authenticator-7f698684c8-c5cjg. name: app-name Namespace to deploy Dex authenticator to. namespace: app-ns spec: Your application’s domain. Requests to it will be redirected for Dex authentication. applicationDomain: “app-name.kube.my-domain.com” A parameter that determines whether to send the Authorization: Bearer header to the application. This one is useful in combination with auth_request in NGINX. sendAuthorizationHeader: false The name of the Secret containing the SSL certificate. applicationIngressCertificateSecretName: “ingress-tls” The name of the Ingress class to use in the Ingress resource created for the Dex authenticator. applicationIngressClassName: “nginx” The duration of the active user session. keepUsersLoggedInFor: “720h” The list of groups whose users are allowed to authenticate. allowedGroups:

  • everyone
  • admins The list of addresses and networks for which authentication is allowed. whitelistSourceRanges:
  • 1.1.1.1/32
  • 192.168.0.0/24
  1. Подключите приложение к Dex.
  1. Connect your application to Dex.

Для этого добавьте в Ingress-ресурс приложения следующие аннотации:

For this, add the following annotations to the application’s Ingress resource:

  • nginx.ingress.kubernetes.io/auth-signin: https://$host/dex-authenticator/sign_in
  • nginx.ingress.kubernetes.io/auth-response-headers: X-Auth-Request-User,X-Auth-Request-Email
  • nginx.ingress.kubernetes.io/auth-url: https://<NAME>-dex-authenticator.<NS>.svc.{{ C_DOMAIN }}/dex-authenticator/auth, где:
  • NAME — значение параметра metadata.name ресурса DexAuthenticator;
  • NS — значение параметра metadata.namespace ресурса DexAuthenticator;
  • C_DOMAIN — домен кластера (параметр clusterDomain ресурса ClusterConfiguration).
  • nginx.ingress.kubernetes.io/auth-signin: https://$host/dex-authenticator/sign_in
  • nginx.ingress.kubernetes.io/auth-response-headers: X-Auth-Request-User,X-Auth-Request-Email
  • nginx.ingress.kubernetes.io/auth-url: https://<NAME>-dex-authenticator.<NS>.svc.{{ C_DOMAIN }}/dex-authenticator/auth, where:
  • NAME — the value of the metadata.name parameter of the DexAuthenticator resource;
  • NS — the value of the metadata.namespace parameter of the DexAuthenticator resource;
  • C_DOMAIN — the cluster domain (the clusterDomain parameter of the ClusterConfiguration resource).

Ниже представлен пример аннотаций на Ingress-ресурсе приложения, для подключения его к Dex:

Below is an example of annotations added to an application’s Ingress resource so that it can be connected to Dex:

yaml annotations: nginx.ingress.kubernetes.io/auth-signin: https://$host/dex-authenticator/sign_in nginx.ingress.kubernetes.io/auth-url: https://app-name-dex-authenticator.app-ns.svc.cluster.local/dex-authenticator/auth nginx.ingress.kubernetes.io/auth-response-headers: X-Auth-Request-User,X-Auth-Request-Email

yaml annotations: nginx.ingress.kubernetes.io/auth-signin: https://$host/dex-authenticator/sign_in nginx.ingress.kubernetes.io/auth-url: https://app-name-dex-authenticator.app-ns.svc.cluster.local/dex-authenticator/auth nginx.ingress.kubernetes.io/auth-response-headers: X-Auth-Request-User,X-Auth-Request-Email

Настройка ограничений на основе CIDR

Setting up CIDR-based restrictions

В DexAuthenticator нет встроенной системы управления разрешением аутентификации на основе IP-адреса пользователя. Вместо этого вы можете воспользоваться аннотациями для Ingress-ресурсов:

DexAuthenticator does not have a built-in system for allowing the user authentication based on its IP address. Instead, you can use annotations for Ingress resources:

  • Если нужно ограничить доступ по IP и оставить прохождение аутентификации в Dex, добавьте аннотацию с указанием разрешенных CIDR через запятую:
  • If you want to restrict access by IP and use Dex for authentication, add the following annotation with a comma-separated list of allowed CIDRs:

yaml nginx.ingress.kubernetes.io/whitelist-source-range: 192.168.0.0/32,1.1.1.1

yaml nginx.ingress.kubernetes.io/whitelist-source-range: 192.168.0.0/32,1.1.1.1

  • Если необходимо, чтобы пользователи из указанных сетей освобождались от прохождения аутентификации в Dex, а пользователи из остальных сетей обязательно аутентифицировались в Dex, добавьте следующую аннотацию:
  • Add the following annotation if you want to exclude users from specific networks from passing authentication via Dex and force users from all other networks to authenticate via Dex:

yaml nginx.ingress.kubernetes.io/satisfy: “any”

yaml nginx.ingress.kubernetes.io/satisfy: “any”

Как работает аутентификация с помощью DexAuthenticator

Authentication flow with DexAuthenticator

Как работает аутентификация с помощью DexAuthenticator

Authentication flow with DexAuthenticator

  1. Dex в большинстве случаев перенаправляет пользователя на страницу входа провайдера и ожидает, что пользователь будет перенаправлен на его /callback URL. Однако такие провайдеры, как LDAP или Atlassian Crowd, не поддерживают этот вариант. Вместо этого пользователь должен ввести свои логин и пароль в форму входа в Dex, и Dex сам проверит их верность, сделав запрос к API провайдера.
  1. Dex redirects the user to the provider’s login page in most cases and wait for the user to be redirected back to the /callback URL. However, some providers like LDAP or Atlassian Crowd do not support this flow. The user should write credentials to the Dex login form instead, and Dex will make a request to the provider’s API to validate them.
  1. DexAuthenticator устанавливает cookie с целым refresh token (вместо того чтобы выдать тикет, как для ID token) потому что Redis не сохраняет данные на диск. Если по тикету в Redis не найден ID token, пользователь сможет запросить новый ID token, предоставив refresh token из cookie.
  1. DexAuthenticator sets the cookie with the whole refresh token (instead of storing it in Redis like an id token) because Redis does not persist data. If there is no id token by the id token ticket in Redis, the user will be able to get the new id token by providing the refresh token from the cookie.
  1. DexAuthenticator выставляет HTTP-заголовок Authorization, равный значению ID token из Redis. Это необязательно для сервисов по типу Upmeter, потому что права доступа к Upmeter не такие проработанные. С другой стороны, для Kubernetes Dashboard это критичный функционал, потому что она отправляет ID token дальше для доступа к Kubernetes API.
  1. DexAuthenticator sets the Authorization HTTP header to the ID token value from Redis. It is not required for services like Upmeter, because permissions to Upmeter entities are not highly grained. On the other hand, for the Kubernetes Dashboard, it is a crucial functionality because it sends the ID token further to access Kubernetes API.

Как я могу сгенерировать kubeconfig для доступа к Kubernetes API?

How can I generate a kubeconfig and access Kubernetes API?

Сгенерировать kubeconfig для удаленного доступа к кластеру через kubectl можно через веб-интерфейс kubeconfigurator.

You can generate kubeconfig for remote access to the cluster via kubectl via the kubeconfigurator web interface.

Настройте параметр publishAPI:

  • Откройте настройки модуля user-authn (создайте ресурс moduleConfig user-authn, если его нет):

Configure the publishAPI parameter:

  • Open the user-authn module settings (create the moduleConfig user-authn resource if there is none):

shell kubectl edit mc user-authn

shell kubectl edit mc user-authn

  • Добавьте следующую секцию в блок settings и сохраните изменения:
  • Add the following section to the settings block and save the changes:

yaml publishAPI: enable: true

yaml publishAPI: enable: true

Для доступа к веб-интерфейсу, позволяющему сгенерировать kubeconfig, зарезервировано имя kubeconfig. URL для доступа зависит от значения параметра publicDomainTemplate (например, для publicDomainTemplate: %s.kube.my это будет kubeconfig.kube.my, а для publicDomainTemplate: %s-kube.company.mykubeconfig-kube.company.my)

The name kubeconfig is reserved for accessing the web interface that allows generating kubeconfig. The URL for access depends on the value of the parameter publicDomainTemplate (for example, for publicDomainTemplate: %s.kube.my it will be kubeconfig.kube.my, and for publicDomainTemplate: %s-kube.company.my it will be kubeconfig-kube.company.my).

Настройка kube-apiserver

Configuring kube-apiserver

С помощью функционала модуля control-plane-manager Deckhouse автоматически настраивает kube-apiserver, выставляя следующие флаги так, чтобы модули dashboard и kubeconfig-generator могли работать в кластере.

With the functional of the control-plane-manager module, Deckhouse automatically configures kube-apiserver by providing the following flags, so that dashboard and kubeconfig-generator modules can work in the cluster.

  • --oidc-client-id=kubernetes
  • --oidc-groups-claim=groups
  • --oidc-issuer-url=https://dex.%addonsPublicDomainTemplate%/
  • --oidc-username-claim=email
  • --oidc-client-id=kubernetes
  • --oidc-groups-claim=groups
  • --oidc-issuer-url=https://dex.%addonsPublicDomainTemplate%/
  • --oidc-username-claim=email

В случае использования самоподписанных сертификатов для Dex будет добавлен еще один аргумент, а также в под с apiserver будет смонтирован файл с CA:

If self-signed certificates are used, Dex will get one more argument. At the same time, the CA file will be mounted to the apiserver’s Pod:

  • --oidc-ca-file=/etc/kubernetes/oidc-ca.crt
  • --oidc-ca-file=/etc/kubernetes/oidc-ca.crt

Как работает подключение к Kubernetes API с помощью сгенерированного kubeconfig

The flow of accessing Kubernetes API with generated kubeconfig

  1. До начала работы kube-apiserver необходимо запросить конфигурационный endpoint OIDC провайдера (в нашем случае — Dex), чтобы получить issuer и настройки JWKS endpoint.
  1. Before the start, kube-apiserver needs to request the configuration endpoint of the OIDC provider (Dex in our case) to get the issuer and JWKS endpoint settings.
  1. Kubeconfig generator сохраняет ID token и refresh token в файл kubeconfig.
  1. Kubeconfig generator stores id token and refresh token to the kubeconfig file.
  1. После получения запроса с ID token kube-apiserver идет проверять, что token подписан провайдером, который мы настроили на первом шаге, с помощью ключей, полученных с точки доступа JWKS. В качестве следующего шага он сравнивает значения claim’ов iss и aud из token’а со значениями из конфигурации.
  1. After receiving request with an id token, kube-apiserver goes to validate, that the token is signed by the provider configured on the first step by getting keys from the JWKS endpoint. As the next step, it compares iss and aud claims values of the token with the values from configuration.

Как Dex защищен от подбора логина и пароля?

How secure is Dex from brute-forcing my credentials?

Одному пользователю разрешено только 20 попыток входа. Если указанный лимит израсходован, одна дополнительная попытка будет добавляться каждые 6 секунд.

Only 20 login attempts are allowed per user. If this limit is used up, one additional attempt will be added every 6 seconds.