K8s-pki

Материал из noname.com.ua
Перейти к навигацииПерейти к поиску

Заметка о PKI/CA в kubernetes

Эта заметка появилась для того что бы раз и навсегда прояснить какие CA и сертификаты используются в control-plane, для чего они используются и почему именно такие.


Предполагается что у читающего есть базовое понимание TLS/SSL/CA/PKI/OpenSSL


Julia Evans - мой герой! https://jvns.ca/blog/2017/08/05/how-kubernetes-certificates-work/
Далее - частичный перевод а частично мои собственные мысли.


Почему возникла эта заметка

Официальная документация гласит:
Kubernetes requires PKI for the following operations:

  • Client certificates for the kubelet to authenticate to the API server
  • Server certificate for the API server endpoint
  • Client certificates for administrators of the cluster to authenticate to the API server
  • Client certificates for the API server to talk to the kubelets
  • Client certificate for the API server to talk to etcd
  • Client certificate/kubeconfig for the controller manager to talk to the API server
  • Client certificate/kubeconfig for the scheduler to talk to the API server.
  • Client and server certificates for the front-proxy

Note: front-proxy certificates are required only if you run kube-proxy to support an extension API server. etcd also implements mutual TLS to authenticate clients and peers.
При этом я не нашел никакой информации о том каким свойствами должны обладать сертификаты, должны ли они быть подписаны одним CA?

Вот что пишет по этому поводу Джулия (перевод мой):

В различных компонентах Kubernetes есть ТЫЩИ разных мест,
где вы можете разместить a certificate/certificate authority.
Когда мы настраивали кластер, я чувствовал, что существует 
около 10 миллиардов различных аргументов командной 
строки для сертификатов, ключей и центров сертификации, и 
я не понимал, как все они сочетаются друг с другом.

На самом деле нет 10 миллиардов аргументов командной строки, 
но их довольно много. Например! Давайте просто посмотрим на 
аргументы командной строки для сервера API.

У API сервера 16 (ШЕСТНАДЦАТЬ, КАРЛ) аргументов которые так или иначе относятся к шифрованию:

  1. --cert-dir string
    The directory where the TLS certs are located. If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored. (default "/var/run/kubernetes")
  2. --client-ca-file string
    If set, any request presenting a client certificate signed by one of the authorities in the client-ca-file is authenticated with an identity corresponding to the CommonName of the client certificate.
  3. --etcd-certfile string
    SSL certification file used to secure etcd communication.
  4. --etcd-keyfile string
    SSL key file used to secure etcd communication.
  5. --etcd-cafile string
    SSL Certificate Authority file used to secure etcd communication.
  6. --kubelet-certificate-authority string
    Path to a cert file for the certificate authority.
  7. --kubelet-client-certificate string
    Path to a client cert file for TLS.
  8. --kubelet-client-key string
    Path to a client key file for TLS.
  9. --proxy-client-cert-file string
    Client certificate used to prove the identity of the aggregator or kube-apiserver when it must call out during a request. This includes proxying requests to a user api-server and calling out to webhook admission plugins. It is expected that this cert includes a signature from the CA in the --requestheader-client-ca-file flag. That CA is published in the 'extension-apiserver-authentication' configmap in the kube-system namespace. Components recieving calls from kube-aggregator should use that CA to perform their half of the mutual TLS verification.
  10. --proxy-client-key-file string
    Private key for the client certificate used to prove the identity of the aggregator or kube-apiserver when it must call out during a request. This includes proxying requests to a user api-server and calling out to webhook admission plugins.
  11. --requestheader-allowed-names stringSlice
    List of client certificate common names to allow to provide usernames in headers specified by --requestheader-username-headers. If empty, any client certificate validated by the authorities in --requestheader-client-ca-file is allowed.
  12. --requestheader-client-ca-file string
    Root certificate bundle to use to verify client certificates on incoming requests before trusting usernames in headers specified by --requestheader-username-headers
  13. --service-account-key-file stringArray
    File containing PEM-encoded x509 RSA or ECDSA private or public keys, used to verify ServiceAccount tokens. If unspecified, --tls-private-key-file is used. The specified file can contain multiple keys, and the flag can be specified multiple times with different files.
  14. --ssh-keyfile string
    If non-empty, use secure SSH proxy to the nodes, using this user keyfile
  15. --tls-ca-file string
    If set, this certificate authority will used for secure access from Admission Controllers. This must be a valid PEM-encoded CA bundle. Alternatively, the certificate authority can be appended to the certificate provided by --tls-cert-file.
  16. --tls-cert-file string
    File containing the default x509 Certificate for HTTPS. (CA cert, if any, concatenated after server cert). If HTTPS serving is enabled, and --tls-cert-file and --tls-private-key-file are not provided, a self-signed certificate and key are generated for the public address and saved to /var/run/kubernetes.
  17. --tls-private-key-file string
    File containing the default x509 private key matching --tls-cert-file.
  18. --tls-sni-cert-key namedCertKey
    A pair of x509 certificate

Отдельно радует именование, блять, параметров: ca-file или cafile???
А может лучше certificate-authority.
Не можем решить и оставим все три варианта!
Четыреждыблядская ярость. На этом месте я подумал что может ну его нахуй и не так уж сильно я хочу изучить Kubernetes.

Еще информация к размышлению (да я тоже был очень удивлен!):

One thing I found surprising about this is – almost everything else in the universe that uses TLS will look in /etc/ssl to find a list of certificate authorities the computer trusts by default. But Kubernetes doesn’t do that, instead it mandates “no, you have to say exactly which CA issued the API server’s TLS cert”.

Другими словами использовать добавленные в систему доверенные CA не получится.


Нужен ли единый CA для кластера (нет)

Такой вопрос возник не только у меня:

Does a Kubernetes cluster have to have a single root certificate authority? (no)

Дальше мой вольный перевод:

Если вы прочитали кучу мануалов про установку кластера, то в каждом из них есть шаг "Постройте свой СА" ("set up a certificate authority".
Kelsey Hightower’s c его прекрасной, но недостаточно подробной инструкцией “kubernetes the hard way” делает это на втором шаге.
инструкция гласит

Every Kubernetes cluster has a cluster root Certificate Authority (CA).
The CA is generally used by cluster components to validate the API server’s certificate, by the API server to validate kubelet client certificates, etc.

В общих чертах это работает так

  • Настройте свой центр выдачи сертефикатов (обычно предлагают скрипты cfssl)
  • Нагенерите сертификатов подписанных своим СА для разных частей кластера

Тут сразу же возникает вопрос - а что делать если я не хочу городить новый PKI для каждого кластера
Фраза (“every Kubernetes cluster has a [single] cluster root Certificate Authority”) ошибочна полностью - можно как использовать один CA для нескольких кластеров так и несколько СА для одного кластера.

kube-apiserver

The API server’s TLS certificate (and certificate authority)

Параметры

  • --tls-cert-file string File containing the default x509 Certificate for HTTPS. (CA cert, if any, concatenated after server cert). If HTTPS serving is enabled, and --tls-cert-file and --tls-private-key-file are not provided, a self-signed certificate and key are generated for the public address and saved to /var/run/kubernetes.
  • --tls-private-key-filestring File containing the default x509 private key matching --tls-cert-file.

Относительно простая часть - эти параметры отвечают за серверный сертификат и его ключ который будет на Endpoint. В общем случае неплохо сделать так что бы curl мог подключиться туда без проблем - т е добавить CА который подписал этот сертификат в доверенные (или сделать bundle с промежуточным CA).
Так же важно что бы тут был правильныйдомен(и IP в SAN)

После устновки TLS для API требуется подготовить kubeconfig для других компонетов (таких как kubelet and kubectl) которым требуется коммуникация с API.

kubeconfig выглядит примерно так

current-context: my-context
apiVersion: v1
clusters:
- cluster:
    certificate-authority: /path/to/my/ca.crt # Путь к CA  которым был подписан сертификат для API указанный в параметре --tls-cert-file kube-apiserver
    server: https://horse.org:4443            # Доменное имя должно быьть указано в сертификате, который  указан в параметре --tls-cert-file kube-apiserver
  name: my-cluster
kind: Config
users:
- name: green-user
  user:
    client-certificate: path/to/my/client/cert # РАССМОТРЕНО НИЖЕ
    client-key: path/to/my/client/key          #  РАССМОТРЕНО НИЖЕ

Напоминаю что системные СА игнорируются и нужно ЯВНО указать путь к СА которым подписан сертификат


Вопросы пока без ответа

  • current-context
  • name: my-cluster



Файл kubeconfig передается компонентам как парамерт --kubeconfig /path/to/kubeconfig.yaml

Итого - первый СА это СА для TLS на API (при этом сам корневой сертификат используется только для проверки подлиности сервера а его ключ нигде не присутствует. (назовем этот СА - СА1) Этот СА может использоваться ТОЛЬКО для указанных целей и не совпадать ни с одним другим СА кластера.

The API server client certificate authority (+ certificates)

--client-ca-file string    
    If set, any request presenting a client certificate signed by one of the
    authorities in the client-ca-file is authenticated with an identity
    corresponding to the CommonName of the client certificate.

Один из возможных способов для компонентов Kubernetes авторизоваться (в оригинале в to authenticate что правильно но я не знаю русского аналога) у API это использовать клиентские сертификаты.
Все эти клиентские сертификаты должны быть выпущены одним и тем же СA, который, повторюсь может отличаться от того СА который выпустил сертификат для HTTPS сервера API

Когда используется файл kubeconfig клиентские сертификаты можно указать примерно так:

kind: Config
users:
- name: green-user
  user:
    client-certificate: path/to/my/client/cert
    client-key: path/to/my/client/key

Kubernetes makes a lot of assumptions about how you’ve set up your client certificates. (it sets the user to be the Common Name field and the group to be the Organization field). If those assumptions don’t match what you want, the right thing to do is to not use client cert auth and instead use an authenticating proxy.

Ссылки