top of page
Foto do escritorRafael Natali

Lidando com vulnerabilidades no Kubernetes com o CIS Benchmark

O CIS (Center for Internet Security) é uma organização independente e sem fins lucrativos, responsável por criar práticas recomendadas de segurança, benchmarks e controles reconhecidos mundialmente. Em relação ao Kubernetes, eles possuem benchmarks para proteger clusters Kubernetes nos principais provedores de nuvem, como AWS, e em instalações on-premises.


Neste artigo, utilizarei uma ferramenta chamada kube-bench para avaliar um cluster Kubernetes quanto a vulnerabilidades cobertas pelo benchmark do CIS. Vou mostrar como acessar o relatório gerado pelo kube-bench e corrigir algumas dessas vulnerabilidades.


Gerar o relatório de vulnerabilidades

Para gerar o relatório usando a linha de comando, instale o binário do kube-bench de acordo com seu sistema operacional:

> sudo apt install ./kube-bench_0.7.3_linux_amd64.deb -f

Para gerar o relatório de vulnerabilidades do cluster Kubernetes, execute o comando kube-bench run:

>kube-bench run

[[INFO] 1 Master Node Security Configuration
[INFO] 1.1 Master Node Configuration Files
[PASS] 1.1.1 Ensure that the API server pod specification file permissions are set to 644 or more restrictive (Automated)
[PASS] 1.1.2 Ensure that the API server pod specification file ownership is set to root:root (Automated)
[PASS] 1.1.3 Ensure that the controller manager pod specification file permissions are set to 644 or more restrictive (Automated)
...
== Remediations node
4.2.6 If using a Kubelet config file, edit the file to set protectKernelDefaults: true.
If using command line arguments, edit the kubelet service file
/lib/systemd/system/kubelet.service on each worker node and
set the below parameter in KUBELET_SYSTEM_PODS_ARGS variable.
--protect-kernel-defaults=true
Based on your system, restart the kubelet service. For example:
systemctl daemon-reload
systemctl restart kubelet.service
...
== Summary total ==
68 checks PASS
12 checks FAIL
43 checks WARN
0 checks INFO

Outra opção de instalação é executar o kube-bench como um Job no cluster Kubernetes. Para isso, crie um arquivo local baseado no arquivo job.yaml encontrado em https://github.com/aquasecurity/kube-bench/blob/main/job.yaml e aplique-o no seu cluster:

> kubectl apply -f job.yamljob.batch/kube-bench created

Um Pod será criado e gerará o relatório do kube-bench. Para visualizar o relatório, acesse os logs do Pod:

> kubectl logs kube-bench-wddkj

A saída será a mesma de quando executado via linha de comando. O relatório possui cinco partes: master, etcd, control plane, worker node e policies. O resumo do relatório indica que 12 verificações falharam e 43 geraram avisos. Agora, vamos abordar algumas dessas questões.


Como corrigir vulnerabilidades do CIS


O relatório do kube-bench nos fornece recomendações para corrigir as vulnerabilidades. Nesta subseção, resolveremos duas vulnerabilidades: uma para o control plane e outra para um worker node.


Control Plane


Neste exemplo, resolveremos a vulnerabilidade 1.1.12:

[FAIL] 1.1.12 Ensure that the etcd data directory ownership is set to etcd:etcd (Automated)

No relatório, você pode ver a recomendação sobre como corrigir essa vulnerabilidade:

1.1.12 On the etcd server node, get the etcd data directory, passed as an argument --data-dir, from the below command:

ps -ef | grep etcd

Run the below command (based on the etcd data directory found above).

For example, chown etcd:etcd /var/lib/etcd

Execute as instruções conforme orientado. Primeiro, no plano de controle, localize o diretório data-dir do etcd:

> ps -ef | grep etcd

root        1594    1296  2 09:24 ?        00:01:05 etcd --advertise-client-urls=https://172.31.119.105:2379 --cert-file=/etc/kubernetes/pki/etcd/server.crt --client-cert-auth=true --data-dir=/var/lib/etcd 

Altere as permissões no diretório /var/lib/etcd e execute o kube-bench novamente, filtrando pela vulnerabilidade 1.1.12:

>chown etcd:etcd /var/lib/etcd
>kube-bench run | grep -i 1.1.12[PASS] 1.1.12 Ensure that the etcd data directory ownership is set to etcd:etcd (Automated)

Agora, a vulnerabilidade relacionada à propriedade do diretório data-dir do etcd está resolvida.


Worker node


Para o worker node, vamos resolver a vulnerabilidade 4.2.10:

[FAIL] 4.2.10 Ensure that the --rotate-certificates argument is not set to false (Automated)

Revisando as recomendações:

4.2.10 If using a Kubelet config file, edit the file to add the line `rotateCertificates` to `true` or remove it altogether to use the default value.

If using command line arguments, edit the kubelet service file/lib/systemd/system/kubelet.service on each worker node andremove --rotate-certificates=false argument from the KUBELET_CERTIFICATE_ARGS variable.

Based on your system, restart the kubelet service. For example,

systemctl daemon-reload
systemctl restart kubelet.service

Para corrigir isso, precisamos fazer login no worker node:

> ssh <user>@<node_name/ip address>

Uma vez conectado ao worker, encontre o arquivo de configuração do kubelet:

> ps -auxwww | grep -i kubeletroot        4016  1.3  4.2 2140228 83988 ?       Ssl  19:00   0:14 /usr/bin/kubelet --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf --config=/var/lib/kubelet/config.yaml --container-runtime-endpoint=unix:///var/run/containerd/containerd.sock --pod-infra-container-image=registry.k8s.io/pause:3.9

Abra o arquivo de configuração no editor:

> sudo vi /var/lib/kubelet/config.yaml

Altere o parâmetro --rotate-certificates=false para true:

rotateCertificates: false  #change from false to true

Reinicie o serviço kubelet:

> sudo systemctl daemon-reload
> sudo systemctl restart kubelet

Volte ao control plane e gere um novo relatório para validar as alterações. Para fazer isso com o Job do Kubernetes, exclua o Job atual e aplique-o novamente:

> kubectl delete jobs.batch kube-bench
job.batch "kube-bench" deleted

> kubectl apply -f job.yaml
job.batch/kube-bench created

Nos logs do Pod, procure pela vulnerabilidade 4.2.10:

> kubectl logs kube-bench-n52f8 | grep -i 4.2.10
[PASS] 4.2.10 Ensure that the --rotate-certificates argument is not set to false (Automated)

Mais uma vulnerabilidade resolvida com sucesso!


Resumo


O kube-bench é uma ferramenta fácil de usar e direta, que ajuda os administradores a identificar as vulnerabilidades atuais do seu cluster Kubernetes e a definir prioridades para resolvê-las. A ferramenta fornece as informações necessárias sobre como corrigir as vulnerabilidades. Além disso, você pode acessar os relatórios de Benchmarks do CIS para Kubernetes e baixar um PDF completo com todas as instruções.


Experimente o kube-bench e melhore a segurança do seu cluster hoje mesmo!



1 visualização0 comentário

Comentários


bottom of page