Compare languages | The user-authn module: FAQ

How to secure my application?

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

It is possible to hide your application behind Dex authentication by using the DexAuthenticator custom resource (CR). In fact, by creating the DexAuthenticator in a cluster, user creates an instance oauth2-proxy, which is already connected to Dex.

Существует возможность спрятать ваше приложение за аутентификацией через Dex при помощи пользовательского ресурса DexAuthenticator (CR). По факту, создавая DexAuthenticator в кластере, пользователь создает экземпляр oauth2-proxy, который уже подключен к Dex.

An example of the DexAuthenticator CR

Пример CR DexAuthenticator

yaml apiVersion: deckhouse.io/v1 kind: DexAuthenticator metadata: name: my-cool-app # the authenticator’s Pods will be prefixed with my-cool-app namespace: my-cool-namespace # the namespace where the dex-authenticator will be deployed spec: applicationDomain: “my-app.kube.my-domain.com” # the domain used for your app sendAuthorizationHeader: false # whether to send the Authorization: Bearer header to the application (comes in handy with auth_request in nginx) applicationIngressCertificateSecretName: “ingress-tls” # the name of the secret with the tls certificate applicationIngressClassName: “nginx” keepUsersLoggedInFor: “720h” allowedGroups:

  • everyone
  • admins whitelistSourceRanges:
  • 1.1.1.1
  • 192.168.0.0/24

yaml apiVersion: deckhouse.io/v1 kind: DexAuthenticator metadata: name: my-cool-app # Pod’ы аутентификатора будут иметь префикс my-cool-app namespace: my-cool-namespace # namespace, в котором будет развернут dex-authenticator spec: applicationDomain: “my-app.kube.my-domain.com” # домен, на котором висит ваше приложение sendAuthorizationHeader: false # отправлять ли Authorization: Bearer header приложению, полезно в связке с auth_request в nginx applicationIngressCertificateSecretName: “ingress-tls” # имя секрета с tls сертификатом applicationIngressClassName: “nginx” keepUsersLoggedInFor: “720h” allowedGroups:

  • everyone
  • admins whitelistSourceRanges:
  • 1.1.1.1
  • 192.168.0.0/24

After the DexAuthenticator CR is created in the cluster, Kubernetes will make the necessary deployment, service, ingress, secret in the specified namespace. Add the following annotations to your app’s Ingress resource to connect your application to dex:

После появления CR DexAuthenticator в кластере, в указанном namespace’е появятся необходимые deployment, service, ingress, secret. Чтобы подключить своё приложение к dex, достаточно будет добавить в Ingress-ресурс вашего приложения следующие аннотации:

yaml annotations: nginx.ingress.kubernetes.io/auth-signin: https://$host/dex-authenticator/sign_in nginx.ingress.kubernetes.io/auth-url: https://my-cool-app-dex-authenticator.my-cool-namespace.svc.{{ cluster domain, e.g., | cluster.local }}/dex-authenticator/auth nginx.ingress.kubernetes.io/auth-response-headers: X-Auth-Request-User,X-Auth-Request-Email,Authorization

yaml annotations: nginx.ingress.kubernetes.io/auth-signin: https://$host/dex-authenticator/sign_in nginx.ingress.kubernetes.io/auth-url: https://my-cool-app-dex-authenticator.my-cool-namespace.svc.{{ домен вашего кластера, например | cluster.local }}/dex-authenticator/auth nginx.ingress.kubernetes.io/auth-response-headers: X-Auth-Request-User,X-Auth-Request-Email

Setting up CIDR-based restrictions

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

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:

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

  • 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:
  • Если нужно ограничить доступ по IP и оставить прохождение аутентификации в dex, добавьте аннотацию с указанием разрешенных CIDR через запятую:

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`

  • 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:
  • Если вы хотите, чтобы пользователи из указанных сетей были освобождены от прохождения аутентификации в dex, а пользователи из остальных сетей были обязаны аутентифицироваться в Dex - добавьте следующую аннотацию:

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

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

Authentication flow with DexAuthenticator

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

Authentication flow with DexAuthenticator

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

  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. Dex в большинстве случаев перенаправляет пользователя на страницу входа провайдера и ожидает, что пользователь будет перенаправлен на его /callback URL. Однако, такие провайдеры как LDAP или Atlassian Crowd не поддерживают этот вариант. Вместо этого пользователь должен ввести свои логин и пароль в форму входа в Dex, и Dex сам проверит их верность сделав запрос к API провайдера.
  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 устанавливает cookie с целым refresh token (вместо того чтобы выдать тикет, как для id token) потому что Redis не сохраняет данные на диск. Если по тикету в Redis не найден id token, пользователь сможет запросить новый id token предоставив refresh token из cookie.
  1. DexAuthenticator sets the Authorization 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.
  1. DexAuthenticator выставляет хидер Authorization равный значению id token из Redis. Это не обязательно для сервисов по типу Upmeter, потому что права доступа к Upmeter не такие проработанные. С другой стороны, для Kubernetes Dashboard это критичный функционал, потому что она отправляет id token дальше для доступа к Kubernetes API.

How can I generate a kubeconfig and access Kubernetes API?

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

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

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

Configure the publishAPI parameter:

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

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

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

shell kubectl edit mc user-authn

shell kubectl edit mc user-authn

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

yaml publishAPI: enable: true

yaml publishAPI: enable: true

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).

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

Configuring kube-apiserver

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

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.

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

  • --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

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:

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

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

The flow of accessing Kubernetes API with generated kubeconfig

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

  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. До начала работы, kube-apiserver необходимо запросить конфигурационный endpoint OIDC провайдера (в нашем случае Dex) чтобы получить issuer и настройки JWKS endpoint.
  1. Kubeconfig generator stores id token and refresh token to the kubeconfig file.
  1. Kubeconfig generator сохраняет id token и refresh token в файл kubeconfig.
  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.
  1. После получения запроса с id token, kube-apiserver идет проверять, что token подписан провайдером, который мы настроили на первом шаге, при помощи ключей полученных с точки доступа JWKS. В качестве следующего шага, он сравнивает значения claim’ов iss и aud из token’а со значениями из конфигурации.

How secure is Dex from brute-forcing my credentials?

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

Only 20 authentication requests are allowed for a single user. If the limit exceeds, another login attempt will be allowed each six seconds.

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