Usar restrições da política CIS do Google Kubernetes Engine Benchmark v1.4.0

O Policy Controller vem com uma biblioteca padrão demodelos de restrição que pode ser usado com o Pacote de políticas do Center for Internet Security (CIS) GKE v1.4.0 para auditar a conformidade do cluster do GKE no Google Cloud em relação aos Comparativos de mercado CIS do Google Kubernetes Engine (GKE) v1.4.0. Esse comparativo de mercado é um conjunto de controles de segurança recomendados para configurar o GKE.

Esse pacote de restrições inclui controles nos seguintes domínios:

  • RBAC e contas de serviço
  • políticas de segurança de pods
  • Políticas de rede e CNI
  • Gerenciamento de secrets
  • Controle de admissão extensível
  • Políticas gerais
  • Serviços gerenciados

Restrições do pacote de políticas CIS GKE v1.4.0

Nome da restrição Descrição da restrição IDs de controle
cis-gke-v1.4.0-restrict-apparmor Restringe o perfil AppArmor para pods. 4.6.3
cis-gke-v1.4.0-restrict-creation-with-default-serviceaccount Restrinja a criação de recursos usando um ServiceAccount padrão. 4.1.5
cis-gke-v1.4.0-restrict-loadbalancer Bloqueia todos os serviços com o tipo LoadBalancer. 5.6.8
cis-gke-v1.4.0-restrict-secrets-of-type-basic-auth Restringe o uso de secrets do tipo de autenticação básica. 4.4.2
cis-gke-v1.4.0-require-binauthz Requer a autorização binária que valida o webhook de admissão. 4.5.1, 5.1.1, 5.1.4 e 5.10.5
cis-gke-v1.4.0-require-cos-node-image Requer o Container-Optimized OS como a imagem do SO do nó. 5.5.1
cis-gke-v1.4.0-require-gke-metadata-server-enabled Requer que o serviço de metadados do GKE esteja ativado em cada nó no cluster. 5.4.2
cis-gke-v1.4.0-require-ingress.class-gce Requer que todos os objetos Ingress tenham uma anotação kubernetes.io/ingress.class: gce. 5.6.8
cis-gke-v1.4.0-require-managed-certificates Requer que todos os objetos Ingress tenham uma anotação networking.gke.io/managed-certificates. 5.6.8
cis-gke-v1.4.0-require-namespace-networkpolicy Requer que cada Namespace definido no cluster tenha um NetworkPolicy. 4.3.2
cis-gke-v1.4.0-require-seccomp-default Requer que todos os objetos Ingress tenham uma anotação networking.gke.io/managed-certificates. 4.6.2
cis-gke-v1.4.0-require-securitycontext Requer que os pods definam securityContext. 4.6.3
cis-gke-v1.4.0-restrict-capabilities Os contêineres precisam descartar todos os recursos e não podem adicionar novamente nenhum outro. 4.2.7, 4.2.8, 4.6.3 e 5.10.3
cis-gke-v1.4.0-restrict-cluster-admin-role Restringe o uso do papel cluster-admin. 4.1.1
cis-gke-v1.4.0-restrict-default-namespace Restringe que os pods usem o Namespace padrão. 4.6.1 ou 4.6.4
cis-gke-v1.4.0-restrict-env-var-secrets Restringe o uso de secrets como variáveis de ambiente em definições de contêiner. 4.4.1
cis-gke-v1.4.0-restrict-host-namespace Restringe contêineres com hostPID ou hostIPC definido como verdadeiro. 4.2.2, 4.2.3 e 5.10.3
cis-gke-v1.4.0-restrict-hostnetwork Restringe a execução de contêineres com a sinalização hostNetwork definida como true. 4.2.4 ou 5.10.3
cis-gke-v1.4.0-restrict-pods-create Restringe a criação de pods em Roles e ClusterRoles. 4.1.4
cis-gke-v1.4.0-restrict-privilege-escalation Restringe contêineres com allowPrivilegeEscalation definido como verdadeiro. 4.2.5 ou 5.10.3
cis-gke-v1.4.0-restrict-privileged-containers Restringe contêineres com securityContext.privileged definido como verdadeiro. 4.2.1 e 5.10.3
cis-gke-v1.4.0-restrict-rbac-subjects Restringe o uso de nomes nos assuntos do RBAC a valores permitidos. 5.8.3
cis-gke-v1.4.0-restrict-role-wildcards Restringe o uso de caracteres curinga em Roles e ClusterRoles. 4.1.3
cis-gke-v1.4.0-restrict-root-containers Restringe a execução de contêineres como usuário raiz. 4.2.6 ou 5.10.3
cis-gke-v1.4.0-restrict-role-secrets Restringe o uso de secrets em Roles e ClusterRoles. 4.1.2
cis-gke-v1.4.0-restrict-automountserviceaccounttoken Restringe o uso de tokens da conta de serviço para pods. 4.1.5, 4.1.6
cis-gke-v1.4.0-restrict-selinux Não é possível definir o tipo de SELinux ou uma opção de papel ou usuário personalizado do SELinux. 4.6.3

Antes de começar

  1. Instale e inicialize a Google Cloud CLI, que fornece os comandos gcloud e kubectl usados nestas instruções. Se você usa o Cloud Shell, a Google Cloud CLI já vem pré-instalada.
  2. Instale o Policy Controller no cluster com a biblioteca padrão de modelos de restrição. Você também precisa ativar a compatibilidade com restrições referenciais, já que este pacote contém restrições referenciais.

Configurar o Policy Controller com restrições referenciais

  1. Salve o seguinte manifesto YAML em um arquivo como policycontroller-config.yaml. O manifesto configura o Policy Controller para observar tipos específicos de objetos.

    apiVersion: config.gatekeeper.sh/v1alpha1
    kind: Config
    metadata:
      name: config
      namespace: "gatekeeper-system"
    spec:
      sync:
        syncOnly:
          - group: "admissionregistration.k8s.io"
            version: "v1"
            kind: "ValidatingWebhookConfiguration"
          - group: "networking.k8s.io"
            version: "v1"
            kind: "NetworkPolicy"
    
  2. Aplique o manifesto policycontroller-config.yaml:

    kubectl apply -f policycontroller-config.yaml
    

Configurar o cluster e a carga de trabalho

  1. A ativação e a configuração dos Grupos do Google para RBAC são necessárias em cis-gke-v1.4.0-restrict-rbac-subjects.
  2. A ativação e a configuração da autorização binária são necessárias em cis-gke-v1.4.0-require-binauthz.

Como auditar políticas CIS do GKE v1.4.0 com o Policy Controller

O Policy Controller permite aplicar políticas ao cluster do Kubernetes. Para ajudar a testar suas cargas de trabalho e a conformidade delas em relação às políticas CIS GKE v1.4.0 descritas na tabela anterior, implante essas restrições no modo "auditoria" para revelar e resolver violações.

É possível aplicar essas políticas com spec.enforcementAction definido como dryrun usando kubectl, kpt ou Config Sync.

kubectl

  1. (Opcional) Visualize as restrições de política com o kubectl:

    kubectl kustomize https://github.com/GoogleCloudPlatform/gke-policy-library.git/anthos-bundles/cis-gke-v1.4.0
    
  2. Aplique as restrições da política com o kubectl:

    kubectl apply -k https://github.com/GoogleCloudPlatform/gke-policy-library.git/anthos-bundles/cis-gke-v1.4.0
    

    A saída é esta:

    k8sblockcreationwithdefaultserviceaccount.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-creation-with-default-serviceaccount created
    k8sblockloadbalancer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-loadbalancer created
    k8sblockobjectsoftype.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-secrets-of-type-basic-auth created
    k8snoenvvarsecrets.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-env-var-secrets created
    k8spspallowprivilegeescalationcontainer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-privilege-escalation created
    k8spspallowedusers.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-root-containers created
    k8spspapparmor.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-apparmor created
    k8spspcapabilities.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-capabilities created
    k8spsphostnamespace.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-host-namespace created
    k8spsphostnetworkingports.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-hostnetwork created
    k8spspprivilegedcontainer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-privileged-containers created
    k8spspselinuxv2.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-selinux created
    k8spspseccomp.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-seccomp-default created
    k8spodsrequiresecuritycontext.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-securitycontext created
    k8sprohibitrolewildcardaccess.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-role-wildcards created
    k8srequirebinauthz.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-binauthz created
    k8srequirecosnodeimage.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-cos-node-image created
    k8srequirenamespacenetworkpolicies.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-namespace-networkpolicy created
    k8srequiredannotations.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-ingress.class-gce created
    k8srequiredannotations.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-managed-certificates created
    k8srequiredlabels.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-gke-metadata-server-enabled created
    k8srestrictautomountserviceaccounttokens.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-automountserviceaccounttoken created
    k8srestrictnamespaces.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-default-namespace created
    k8srestrictrbacsubjects.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-rbac-subjects created
    k8srestrictrolebindings.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-cluster-admin-role created
    k8srestrictrolerules.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-pods-create created
    k8srestrictrolerules.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-role-secrets created
    
  3. Verifique se as restrições da política foram instaladas e se existem violações no cluster:

    kubectl get constraints -l policycontroller.gke.io/bundleName=cis-gke-v1.4.0
    

    O resultado será assim:

    NAME                                                                                                                               ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8sblockcreationwithdefaultserviceaccount.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-creation-with-default-serviceaccount   dryrun               0
    
    NAME                                                                                  ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8sblockloadbalancer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-loadbalancer   dryrun               0
    
    NAME                                                                                                 ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8sblockobjectsoftype.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-secrets-of-type-basic-auth   dryrun               0
    
    NAME                                                                                   ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8snoenvvarsecrets.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-env-var-secrets   dryrun               0
    
    NAME                                                                                             ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8spodsrequiresecuritycontext.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-securitycontext   dryrun               0
    
    NAME                                                                                             ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8sprohibitrolewildcardaccess.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-role-wildcards   dryrun               0
    
    NAME                                                                                   ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8spspallowedusers.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-root-containers   dryrun               0
    
    NAME                                                                                                             ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8spspallowprivilegeescalationcontainer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-privilege-escalation   dryrun               0
    
    NAME                                                                        ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8spspapparmor.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-apparmor   dryrun               0
    
    NAME                                                                                ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8spspcapabilities.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-capabilities   dryrun               0
    
    NAME                                                                                   ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8spsphostnamespace.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-host-namespace   dryrun               0
    
    NAME                                                                                      ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8spsphostnetworkingports.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-hostnetwork   dryrun               0
    
    NAME                                                                                                ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8spspprivilegedcontainer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-privileged-containers   dryrun               0
    
    NAME                                                                             ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8spspseccomp.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-seccomp-default   dryrun               0
    
    NAME                                                                        ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8spspselinuxv2.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-selinux   dryrun               0
    
    NAME                                                                           ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8srequirebinauthz.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-binauthz   dryrun               0
    
    NAME                                                                                     ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8srequirecosnodeimage.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-cos-node-image   dryrun               0
    
    NAME                                                                                           ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8srequiredannotations.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-ingress.class-gce      dryrun               0
    k8srequiredannotations.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-managed-certificates   dryrun               0
    
    NAME                                                                                             ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8srequiredlabels.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-gke-metadata-server-enabled   dryrun               0
    
    NAME                                                                                                          ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8srequirenamespacenetworkpolicies.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-namespace-networkpolicy   dryrun               0
    
    NAME                                                                                                                      ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8srestrictautomountserviceaccounttokens.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-automountserviceaccounttoken   dryrun               0
    
    NAME                                                                                        ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8srestrictnamespaces.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-default-namespace   dryrun               0
    
    NAME                                                                                      ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8srestrictrbacsubjects.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-rbac-subjects   dryrun               0
    
    NAME                                                                                           ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8srestrictrolebindings.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-cluster-admin-role   dryrun               0
    
    NAME                                                                                  ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
    k8srestrictrolerules.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-pods-create    dryrun               0
    k8srestrictrolerules.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-role-secrets   dryrun               0
    

kpt

  1. Instale e configure o kpt. O kpt é usado nestas instruções para personalizar e implantar recursos do Kubernetes.

  2. Faça o download do pacote de políticas do CIS no GitHub usando o kpt:

    kpt pkg get https://github.com/GoogleCloudPlatform/gke-policy-library.git/anthos-bundles/cis-gke-v1.4.0
    
  3. Execute a função set-enforcement-action do kpt para definir a ação de aplicação das políticas como dryrun:

    kpt fn eval cis-gke-v1.4.0 -i gcr.io/kpt-fn/set-enforcement-action:v0.1 \
      -- enforcementAction=dryrun
    
  4. Inicialize o diretório de trabalho com o kpt, que cria um recurso para acompanhar as alterações:

    cd cis-gke-v1.4.0
    kpt live init
    
  5. Aplique as restrições da política ao kpt:

    kpt live apply
    

    A saída é esta:

    k8sblockcreationwithdefaultserviceaccount.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-creation-with-default-serviceaccount created
    k8sblockloadbalancer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-loadbalancer created
    k8sblockobjectsoftype.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-secrets-of-type-basic-auth created
    k8snoenvvarsecrets.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-env-var-secrets created
    k8spspallowprivilegeescalationcontainer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-privilege-escalation created
    k8spspallowedusers.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-root-containers created
    k8spspapparmor.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-apparmor created
    k8spspcapabilities.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-capabilities created
    k8spsphostnamespace.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-host-namespace created
    k8spsphostnetworkingports.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-hostnetwork created
    k8spspprivilegedcontainer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-privileged-containers created
    k8spspselinuxv2.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-selinux created
    k8spspseccomp.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-seccomp-default created
    k8spodsrequiresecuritycontext.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-securitycontext created
    k8sprohibitrolewildcardaccess.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-role-wildcards created
    k8srequirebinauthz.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-binauthz created
    k8srequirecosnodeimage.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-cos-node-image created
    k8srequirenamespacenetworkpolicies.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-namespace-networkpolicy created
    k8srequiredannotations.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-ingress.class-gce created
    k8srequiredannotations.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-managed-certificates created
    k8srequiredlabels.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-gke-metadata-server-enabled created
    k8srestrictautomountserviceaccounttokens.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-automountserviceaccounttoken created
    k8srestrictnamespaces.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-default-namespace created
    k8srestrictrbacsubjects.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-rbac-subjects created
    k8srestrictrolebindings.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-cluster-admin-role created
    k8srestrictrolerules.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-pods-create created
    k8srestrictrolerules.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-role-secrets created
    27 resource(s) applied. 27 created, 0 unchanged, 0 configured, 0 failed
    
  6. Verifique se as restrições da política foram instaladas e se existem violações no cluster:

    kpt live status --output table --poll-until current
    

    O status CURRENT confirma a instalação bem-sucedida das restrições.

Config Sync

  1. Instale e configure o kpt. O kpt é usado nestas instruções para personalizar e implantar recursos do Kubernetes.

Os operadores que usam o Config Sync para implantar políticas nos clusters podem usar as seguintes instruções:

  1. Altere para o diretório de sincronização do Config Sync:

    cd SYNC_ROOT_DIR
    

    Para criar ou anexar .gitignore com resourcegroup.yaml:

    echo resourcegroup.yaml >> .gitignore
    

  2. Crie um diretório policies dedicado:

    mkdir -p policies
    
  3. Faça o download do pacote de políticas CIS GKE v1.4.0 no GitHub usando o kpt:

    kpt pkg get https://github.com/GoogleCloudPlatform/gke-policy-library.git/anthos-bundles/cis-gke-v1.4.0 policies/cis-gke-v1.4.0
    
  4. Execute a função set-enforcement-action do kpt para definir a ação de aplicação das políticas como dryrun:

    kpt fn eval policies/cis-gke-v1.4.0 -i gcr.io/kpt-fn/set-enforcement-action:v0.1 -- enforcementAction=dryrun
    
  5. (Opcional) Visualize as restrições de política a serem criadas:

    kpt live init policies/cis-gke-v1.4.0
    kpt live apply --dry-run policies/cis-gke-v1.4.0
    

    A saída é esta:

    Dry-run strategy: client
    inventory update started
    inventory update finished
    apply phase started
    k8sblockcreationwithdefaultserviceaccount.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-creation-with-default-serviceaccount successful
    k8sblockloadbalancer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-loadbalancer successful
    k8sblockobjectsoftype.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-secrets-of-type-basic-auth successful
    k8snoenvvarsecrets.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-env-var-secrets successful
    k8spspallowprivilegeescalationcontainer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-privilege-escalation successful
    k8spspallowedusers.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-root-containers successful
    k8spspapparmor.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-apparmor successful
    k8spspcapabilities.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-capabilities successful
    k8spsphostnamespace.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-host-namespace successful
    k8spsphostnetworkingports.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-hostnetwork successful
    k8spspprivilegedcontainer.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-privileged-containers successful
    k8spspselinuxv2.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-selinux successful
    k8spspseccomp.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-seccomp-default successful
    k8spodsrequiresecuritycontext.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-securitycontext successful
    k8sprohibitrolewildcardaccess.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-role-wildcards successful
    k8srequirebinauthz.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-binauthz successful
    k8srequirecosnodeimage.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-cos-node-image successful
    k8srequirenamespacenetworkpolicies.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-namespace-networkpolicy successful
    k8srequiredannotations.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-ingress.class-gce successful
    k8srequiredannotations.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-managed-certificates successful
    k8srequiredlabels.constraints.gatekeeper.sh/cis-gke-v1.4.0-require-gke-metadata-server-enabled successful
    k8srestrictautomountserviceaccounttokens.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-automountserviceaccounttoken successful
    k8srestrictnamespaces.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-default-namespace successful
    k8srestrictrbacsubjects.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-rbac-subjects successful
    k8srestrictrolebindings.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-cluster-admin-role successful
    k8srestrictrolerules.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-pods-create successful
    k8srestrictrolerules.constraints.gatekeeper.sh/cis-gke-v1.4.0-restrict-role-secrets successful
    apply phase finished
    inventory update started
    inventory update finished
    apply result: 27 attempted, 27 successful, 0 skipped, 0 failed
    
  6. Se o diretório de sincronização do Config Sync usar Kustomize, adicione policies/cis-gke-v1.4.0 à raiz kustomization.yaml. Caso contrário, remova o arquivo policies/cis-gke-v1.4.0/kustomization.yaml:

    rm SYNC_ROOT_DIR/policies/cis-gke-v1.4.0/kustomization.yaml
    
  7. Envie as alterações para o repositório do Config Sync:

    git add SYNC_ROOT_DIR/policies/cis-gke-v1.4.0
    git commit -m 'Adding CIS GKE v1.4.0 policy bundle'
    git push
    
  8. Verifique o status da instalação:

    watch gcloud beta container fleet config-management status --project PROJECT_ID
    

    O status SYNCED confirma a instalação das políticas.

Visualizar violações de políticas

Depois que as restrições de política são instaladas no modo de auditoria, as violações no cluster podem ser visualizadas na interface usando o Painel do Controlador de políticas.

Também é possível usar kubectl para visualizar violações no cluster usando o seguinte comando:

kubectl get constraint -l policycontroller.gke.io/bundleName=cis-gke-v1.4.0 -o json | jq -cC '.items[]| [.metadata.name,.status.totalViolations]'

Se houver violações, uma lista das mensagens de violação por restrição poderá ser visualizada com:

kubectl get constraint -l policycontroller.gke.io/bundleName=cis-gke-v1.4.0 -o json | jq -C '.items[]| select(.status.totalViolations>0)| [.metadata.name,.status.violations[]?]'

Alterar ação de aplicação do pacote de políticas CIS GKE v1.4.0

Depois de analisar as violações de políticas no cluster, considere alterar o modo de aplicação para que o controlador de admissão warn ou deny bloqueie a aplicação de recursos sem compliance no cluster.

kubectl

  1. Use o kubectl para definir a ação de cumprimento das políticas como warn:

    kubectl get constraint -l policycontroller.gke.io/bundleName=cis-gke-v1.4.0 -o name | xargs -I {} kubectl patch {} --type='json' -p='[{"op":"replace","path":"/spec/enforcementAction","value":"warn"}]'
    
  2. Verifique se a ação de cumprimento das restrições da política foi atualizada:

    kubectl get constraints -l policycontroller.gke.io/bundleName=cis-gke-v1.4.0
    

kpt

  1. Execute a função set-enforcement-action do kpt para definir a ação de aplicação das políticas como warn:

    kpt fn eval -i gcr.io/kpt-fn/set-enforcement-action:v0.1 -- enforcementAction=warn
    
  2. Aplique as restrições da política:

    kpt live apply
    

Config Sync

Os operadores que usam o Config Sync para implantar políticas nos clusters podem usar as seguintes instruções:

  1. Altere para o diretório de sincronização do Config Sync:

    cd SYNC_ROOT_DIR
    
  2. Execute a função set-enforcement-action do kpt para definir a ação de aplicação das políticas como warn:

    kpt fn eval policies/cis-gke-v1.4.0 -i gcr.io/kpt-fn/set-enforcement-action:v0.1 -- enforcementAction=warn
    
  3. Envie as alterações para o repositório do Config Sync:

    git add SYNC_ROOT_DIR/policies/cis-gke-v1.4.0
    git commit -m 'Adding CIS GKE v1.4.0 policy bundle warn enforcement'
    git push
    
  4. Verifique o status da instalação:

    gcloud alpha anthos config sync repo list --project PROJECT_ID
    

    Seu repo que aparece na coluna SYNCED confirma a instalação das políticas.

Aplicação da política de testes

Crie um recurso não compatível no cluster usando o seguinte comando:

cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  namespace: default
  name: wp-non-compliant
  labels:
    app: wordpress
spec:
  containers:
    - image: wordpress
      name: wordpress
      ports:
      - containerPort: 80
        name: wordpress
EOF

O controlador de admissão produzirá um alerta listando as violações da política que esse recurso viola, conforme mostrado no exemplo a seguir:

Warning: [cis-gke-v1.4.0-restrict-default-namespace] <default> namespace is restricted
Warning: [cis-gke-v1.4.0-restrict-root-containers] Container wordpress is attempting to run without a required securityContext/runAsNonRoot or securityContext/runAsUser != 0
Warning: [cis-gke-v1.4.0-restrict-privilege-escalation] Privilege escalation container is not allowed: wordpress
Warning: [cis-gke-v1.4.0-require-seccomp-default] Seccomp profile 'not configured' is not allowed for container 'wordpress'. Found at: no explicit profile found. Allowed profiles: {"RuntimeDefault", "docker/default", "runtime/default"}
Warning: [cis-gke-v1.4.0-restrict-capabilities] container <wordpress> is not dropping all required capabilities. Container must drop all of ["ALL"] or "ALL"
Warning: [cis-gke-v1.4.0-require-securitycontext] securityContext must be defined for all Pod containers
pod/wp-non-compliant created

Remover o pacote de políticas CIS GKE v1.4.0

Se necessário, o pacote de políticas CIS GKE v1.4.0 pode ser removido do cluster.

kubectl

Use o kubectl para remover as políticas:

  kubectl delete constraint -l policycontroller.gke.io/bundleName=cis-gke-v1.4.0
  

kpt

Remova as políticas:

  kpt live destroy
  

Config Sync

Os operadores que usam o Config Sync para implantar políticas nos clusters podem usar as seguintes instruções:

  1. Envie as alterações para o repositório do Config Sync:

    git rm -r SYNC_ROOT_DIR/policies/cis-gke-v1.4.0
    git commit -m 'Removing CIS GKE v1.4.0 policy bundle'
    git push
    
  2. Verifique o status:

    gcloud alpha anthos config sync repo list --project PROJECT_ID
    

    Seu repo que aparece na coluna SYNCED confirma a remoção das políticas.