Excluir autoridades de certificação

Com o Certificate Authority Service, é possível excluir uma autoridade de certificação (CA) atual. A CA será excluída permanentemente após um período de carência de 30 dias a partir da data de início do processo de exclusão. Após o período de carência, o serviço de CA exclui permanentemente a CA e todos os artefatos aninhados, como certificados e listas de revogação de certificados (CRLs).

Os recursos Google Cloud gerenciados pelo cliente que estavam sendo usados pela AC excluída, como buckets do Cloud Storage ou chaves do Cloud Key Management Service, não são excluídos. Para mais informações sobre recursos gerenciados pelo Google e pelo cliente, consulte Gerenciar recursos.

Uma CA excluída não é faturada durante o período de carência. No entanto, se você restaurar a CA, será cobrado no nível de faturamento da CA pelo tempo em que ela ficou no estado DELETED.

Antes de começar

  • Verifique se você tem o papel do IAM de Gerente de operações do serviço de CA (roles/privateca.caManager) ou Administrador do serviço de CA (roles/privateca.admin). Para mais informações sobre os papéis predefinidos do IAM para o CA Service, consulte Controle de acesso com o IAM.

    Para informações sobre como conceder um papel do IAM, consulte Conceder um único papel.

  • Verifique se a CA atende às seguintes condições:

    • A CA não pode ter certificados ativos. Um certificado é considerado ativo quando atende às seguintes condições:

    • O certificado tem datas de início e término válidas.

    • O certificado não foi revogado.

    • O dispositivo ou sistema que usa o certificado confia na autoridade de certificação (CA) que o emitiu.

    Antes de excluir a CA, verifique se todos os certificados ativos emitidos por ela foram revogados. Não é possível revogar certificados de uma CA excluída.

Excluir uma CA

Para iniciar a exclusão da CA, faça o seguinte:

Console

  1. Acesse a página Autoridades certificadoras no console do Google Cloud .

    Acessar "Autoridades de certificação"

  2. Na lista de ACs, selecione a que você quer excluir.
  3. Clique em Excluir. A caixa de diálogo Excluir autoridade certificadora aparece.
  4. Opcional: marque uma ou ambas as caixas de seleção a seguir se as condições se aplicarem a você:
    • Excluir esta CA, mesmo se houver certificados ativos

      Essa opção permite excluir uma CA com certificados ativos. A exclusão de uma CA com certificados ativos pode causar falhas em sites, aplicativos ou sistemas que dependem desses certificados. Recomendamos revogar todos os certificados ativos emitidos por uma CA antes de excluir a CA.

    • Pule o período de carência de 30 dias e exclua essa CA imediatamente

      O período de carência de 30 dias permite revogar todos os certificados emitidos por essa CA e verificar se nenhum sistema depende dela. Recomendamos usar essa opção apenas em ambientes de teste ou que não sejam de produção para evitar possíveis interrupções e perda de dados.

  5. Clique em Confirmar.

gcloud

  1. Verifique se o estado da CA está desativado. Só é possível excluir as CAs que estão no estado DISABLED.

    gcloud privateca roots describe CA_ID --pool=POOL_ID --location=LOCATION --format="value(state)"
    

    Substitua:

    • CA_ID: o identificador exclusivo da CA.
    • POOL_ID: o nome do pool de ACs que contém a CA.
    • LOCATION: o local do pool de ACs. Para a lista completa de locais, consulte Locais.

    Para mais informações sobre o comando gcloud privateca roots describe, consulte gcloud privateca roots describe.

  2. Se a CA não estiver desativada, execute o seguinte comando para desativá-la.

    gcloud privateca roots disable CA_ID --pool=POOL_ID --location=LOCATION
    

    Para mais informações sobre o comando gcloud privateca roots disable, consulte gcloud privateca roots disable.

  3. Exclua a CA.

    gcloud privateca roots delete CA_ID --pool=POOL_ID --location=LOCATION
    

    É possível excluir a CA mesmo que ela tenha certificados ativos incluindo a flag --ignore-active-certificates no comando gcloud.

    Para mais informações sobre o comando gcloud privateca roots delete, consulte gcloud privateca roots delete.

  4. Quando solicitado, confirme que você quer excluir a CA.

    Depois da confirmação, a CA é programada para exclusão, e o período de carência de 30 dias começa. O comando gera a data e a hora esperadas para a exclusão da CA.

        Deleted Root CA [projects/PROJECT_ID/locations/us-west1/caPools/POOL_ID/certificateAuthorities/CA_ID] can be undeleted until 2020-08-14T19:28:39Z.
    

Go

Para autenticar no serviço de CA, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import (
	"context"
	"fmt"
	"io"

	privateca "cloud.google.com/go/security/privateca/apiv1"
	"cloud.google.com/go/security/privateca/apiv1/privatecapb"
)

// Delete a Certificate Authority from the specified CA pool.
// Before deletion, the CA must be disabled or staged and must not contain any active certificates.
func deleteCa(w io.Writer, projectId string, location string, caPoolId string, caId string) error {
	// projectId := "your_project_id"
	// location := "us-central1"	// For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
	// caPoolId := "ca-pool-id"		// The id of the CA pool under which the CA is present.
	// caId := "ca-id"				// The id of the CA to be deleted.

	ctx := context.Background()
	caClient, err := privateca.NewCertificateAuthorityClient(ctx)
	if err != nil {
		return fmt.Errorf("NewCertificateAuthorityClient creation failed: %w", err)
	}
	defer caClient.Close()

	fullCaName := fmt.Sprintf("projects/%s/locations/%s/caPools/%s/certificateAuthorities/%s",
		projectId, location, caPoolId, caId)

	// Check if the CA is disabled or staged.
	// See https://pkg.go.dev/cloud.google.com/go/security/privateca/apiv1/privatecapb#GetCertificateAuthorityRequest.
	caReq := &privatecapb.GetCertificateAuthorityRequest{Name: fullCaName}
	caResp, err := caClient.GetCertificateAuthority(ctx, caReq)
	if err != nil {
		return fmt.Errorf("GetCertificateAuthority failed: %w", err)
	}

	if caResp.State != privatecapb.CertificateAuthority_DISABLED &&
		caResp.State != privatecapb.CertificateAuthority_STAGED {
		return fmt.Errorf("you can only delete disabled or staged Certificate Authorities. %s is not disabled", caId)
	}

	// Create the DeleteCertificateAuthorityRequest.
	// Setting the IgnoreActiveCertificates to True will delete the CA
	// even if it contains active certificates. Care should be taken to re-anchor
	// the certificates to new CA before deleting.
	// See https://pkg.go.dev/cloud.google.com/go/security/privateca/apiv1/privatecapb#DeleteCertificateAuthorityRequest.
	req := &privatecapb.DeleteCertificateAuthorityRequest{
		Name:                     fullCaName,
		IgnoreActiveCertificates: false,
	}

	op, err := caClient.DeleteCertificateAuthority(ctx, req)
	if err != nil {
		return fmt.Errorf("DeleteCertificateAuthority failed: %w", err)
	}

	if caResp, err = op.Wait(ctx); err != nil {
		return fmt.Errorf("DeleteCertificateAuthority failed during wait: %w", err)
	}

	if caResp.State != privatecapb.CertificateAuthority_DELETED {
		return fmt.Errorf("unable to delete Certificate Authority. Current state: %s", caResp.State.String())
	}

	fmt.Fprintf(w, "Successfully deleted Certificate Authority: %s.", caId)
	return nil
}

Java

Para autenticar no serviço de CA, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


import com.google.api.core.ApiFuture;
import com.google.cloud.security.privateca.v1.CertificateAuthority.State;
import com.google.cloud.security.privateca.v1.CertificateAuthorityName;
import com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient;
import com.google.cloud.security.privateca.v1.DeleteCertificateAuthorityRequest;
import com.google.longrunning.Operation;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class DeleteCertificateAuthority {

  public static void main(String[] args)
      throws InterruptedException, ExecutionException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    // location: For a list of locations, see:
    // https://cloud.google.com/certificate-authority-service/docs/locations
    // poolId: The id of the CA pool under which the CA is present.
    // certificateAuthorityName: The name of the CA to be deleted.
    String project = "your-project-id";
    String location = "ca-location";
    String poolId = "ca-pool-id";
    String certificateAuthorityName = "certificate-authority-name";
    deleteCertificateAuthority(project, location, poolId, certificateAuthorityName);
  }

  // Delete the Certificate Authority from the specified CA pool.
  // Before deletion, the CA must be disabled and must not contain any active certificates.
  public static void deleteCertificateAuthority(
      String project, String location, String poolId, String certificateAuthorityName)
      throws IOException, ExecutionException, InterruptedException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `certificateAuthorityServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (CertificateAuthorityServiceClient certificateAuthorityServiceClient =
        CertificateAuthorityServiceClient.create()) {
      // Create the Certificate Authority Name.
      CertificateAuthorityName certificateAuthorityNameParent =
          CertificateAuthorityName.newBuilder()
              .setProject(project)
              .setLocation(location)
              .setCaPool(poolId)
              .setCertificateAuthority(certificateAuthorityName)
              .build();

      // Check if the CA is enabled.
      State caState =
          certificateAuthorityServiceClient
              .getCertificateAuthority(certificateAuthorityNameParent)
              .getState();
      if (caState == State.ENABLED) {
        System.out.println(
            "Please disable the Certificate Authority before deletion ! Current state: " + caState);
        return;
      }

      // Create the DeleteCertificateAuthorityRequest.
      // Setting the setIgnoreActiveCertificates() to true, will delete the CA
      // even if it contains active certificates. Care should be taken to re-anchor
      // the certificates to new CA before deleting.
      DeleteCertificateAuthorityRequest deleteCertificateAuthorityRequest =
          DeleteCertificateAuthorityRequest.newBuilder()
              .setName(certificateAuthorityNameParent.toString())
              .setIgnoreActiveCertificates(false)
              .build();

      // Delete the Certificate Authority.
      ApiFuture<Operation> futureCall =
          certificateAuthorityServiceClient
              .deleteCertificateAuthorityCallable()
              .futureCall(deleteCertificateAuthorityRequest);
      Operation response = futureCall.get();

      if (response.hasError()) {
        System.out.println("Error while deleting Certificate Authority !" + response.getError());
        return;
      }

      // Check if the CA has been deleted.
      caState =
          certificateAuthorityServiceClient
              .getCertificateAuthority(certificateAuthorityNameParent)
              .getState();
      if (caState == State.DELETED) {
        System.out.println(
            "Successfully deleted Certificate Authority : " + certificateAuthorityName);
      } else {
        System.out.println(
            "Unable to delete Certificate Authority. Please try again ! Current state: " + caState);
      }
    }
  }
}

Python

Para autenticar no serviço de CA, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import google.cloud.security.privateca_v1 as privateca_v1


def delete_certificate_authority(
    project_id: str, location: str, ca_pool_name: str, ca_name: str
) -> None:
    """
    Delete the Certificate Authority from the specified CA pool.
    Before deletion, the CA must be disabled and must not contain any active certificates.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations.
        ca_pool_name: the name of the CA pool under which the CA is present.
        ca_name: the name of the CA to be deleted.
    """

    caServiceClient = privateca_v1.CertificateAuthorityServiceClient()
    ca_path = caServiceClient.certificate_authority_path(
        project_id, location, ca_pool_name, ca_name
    )

    # Check if the CA is enabled.
    ca_state = caServiceClient.get_certificate_authority(name=ca_path).state
    if ca_state != privateca_v1.CertificateAuthority.State.DISABLED:
        print(
            "Please disable the Certificate Authority before deletion ! Current state:",
            ca_state,
        )
        raise RuntimeError(
            f"You can only delete disabled Certificate Authorities. "
            f"{ca_name} is not disabled!"
        )

    # Create the DeleteCertificateAuthorityRequest.
    # Setting the ignore_active_certificates to True will delete the CA
    # even if it contains active certificates. Care should be taken to re-anchor
    # the certificates to new CA before deleting.
    request = privateca_v1.DeleteCertificateAuthorityRequest(
        name=ca_path, ignore_active_certificates=False
    )

    # Delete the Certificate Authority.
    operation = caServiceClient.delete_certificate_authority(request=request)
    result = operation.result()

    print("Operation result", result)

    # Get the current CA state.
    ca_state = caServiceClient.get_certificate_authority(name=ca_path).state

    # Check if the CA has been deleted.
    if ca_state == privateca_v1.CertificateAuthority.State.DELETED:
        print("Successfully deleted Certificate Authority:", ca_name)
    else:
        print(
            "Unable to delete Certificate Authority. Please try again ! Current state:",
            ca_state,
        )

Verificar a data de validade de uma CA excluída

Para saber quando uma CA será excluída permanentemente, faça o seguinte:

Console

  1. Clique na guia Gerenciador de pools de CA.
  2. Clique no nome do pool de CAs que continha a CA excluída.

A data de validade da CA aparece na tabela da página Pool de CA.

Confira a data de validade de uma AC excluída.

gcloud

Para verificar o tempo de exclusão esperado de uma CA, execute o seguinte comando:

gcloud privateca roots describe CA_ID \
    --pool=POOL_ID \
    --location=LOCATION \
    --format="value(expireTime.date())"

Substitua:

  • CA_ID: o nome da CA.
  • POOL_ID: o nome do pool de ACs que continha a CA.
  • LOCATION: o local do pool de ACs. Para a lista completa de locais, consulte Locais.

O comando retorna a data e a hora esperadas quando o CA Service exclui a AC.

2020-08-14T19:28:39

Para verificar se a CA foi excluída permanentemente, execute o seguinte comando:

gcloud privateca roots describe CA_ID --pool=POOL_ID --location=LOCATION

Se a exclusão for bem-sucedida, o comando vai retornar o seguinte erro:

ERROR: (gcloud.privateca.roots.describe) NOT_FOUND: Resource 'projects/PROJECT_ID/locations/LOCATION/caPools/POOL_ID/certificateAuthorities/CA_ID' was not found

A seguir