Ejemplo n.º 1
0
    def Run(self, args):
        client = privateca_base.GetClientInstance()
        messages = privateca_base.GetMessagesModule()

        ca_ref = args.CONCEPTS.certificate_authority.Parse()

        if not console_io.PromptContinue(
                message='You are about to delete Certificate Authority [{}]'.
                format(ca_ref.RelativeName()),
                default=True):
            log.status.Print('Aborted by user.')
            return

        current_ca = client.projects_locations_certificateAuthorities.Get(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest(
                name=ca_ref.RelativeName()))

        resource_args.CheckExpectedCAType(
            messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED,
            current_ca)

        operation = client.projects_locations_certificateAuthorities.Delete(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesDeleteRequest(
                name=ca_ref.RelativeName(),
                requestId=request_utils.GenerateRequestId()))

        operations.Await(operation, 'Deleting Root CA')

        log.status.Print('Deleted Root CA [{}].'.format(ca_ref.RelativeName()))
Ejemplo n.º 2
0
    def Run(self, args):
        client = privateca_base.GetClientInstance('v1')
        messages = privateca_base.GetMessagesModule('v1')

        ca_pool_ref = args.CONCEPTS.ca_pool.Parse()
        issuance_policy = flags_v1.ParseIssuancePolicy(args)
        publishing_options = flags_v1.ParsePublishingOptions(args)
        tier = flags_v1.ParseTierFlag(args)
        labels = labels_util.ParseCreateArgs(args, messages.CaPool.LabelsValue)
        new_ca_pool = messages.CaPool(issuancePolicy=issuance_policy,
                                      publishingOptions=publishing_options,
                                      tier=tier,
                                      labels=labels)
        operation = client.projects_locations_caPools.Create(
            messages.PrivatecaProjectsLocationsCaPoolsCreateRequest(
                caPool=new_ca_pool,
                caPoolId=ca_pool_ref.Name(),
                parent=ca_pool_ref.Parent().RelativeName(),
                requestId=request_utils.GenerateRequestId()))

        ca_pool_response = operations.Await(operation,
                                            'Creating CA Pool.',
                                            api_version='v1')
        ca_pool = operations.GetMessageFromResponse(ca_pool_response,
                                                    messages.CaPool)

        log.status.Print('Created CA Pool [{}].'.format(ca_pool.name))
    def Run(self, args):
        client = privateca_base.GetClientInstance(api_version='v1')
        messages = privateca_base.GetMessagesModule(api_version='v1')

        ca_ref = args.CONCEPTS.certificate_authority.Parse()

        current_ca = client.projects_locations_caPools_certificateAuthorities.Get(
            messages.
            PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesGetRequest(
                name=ca_ref.RelativeName()))

        resource_args.CheckExpectedCAType(
            messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED,
            current_ca,
            version='v1')

        operation = client.projects_locations_caPools_certificateAuthorities.Undelete(
            messages.
            PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesUndeleteRequest(
                name=ca_ref.RelativeName(),
                undeleteCertificateAuthorityRequest=messages.
                UndeleteCertificateAuthorityRequest(
                    requestId=request_utils.GenerateRequestId())))

        operations.Await(operation, 'Undeleting Root CA', api_version='v1')

        log.status.Print('Undeleted Root CA [{}].'.format(
            ca_ref.RelativeName()))
Ejemplo n.º 4
0
    def Run(self, args):
        cert_ref = _ParseCertificateResource(args)

        reason = flags.ParseRevocationChoiceToEnum(args.reason)

        client = privateca_base.GetClientInstance()
        messages = privateca_base.GetMessagesModule()

        operation = client.projects_locations_certificateAuthorities_certificates.Revoke(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesCertificatesRevokeRequest(
                name=cert_ref.RelativeName(),
                revokeCertificateRequest=messages.RevokeCertificateRequest(
                    reason=reason,
                    requestId=request_utils.GenerateRequestId())))

        response = operations.Await(operation, 'Revoking Certificate.')
        certificate = operations.GetMessageFromResponse(
            response, messages.Certificate)

        log.status.Print('Publishing a new Certificate Revocation List.')
        client.projects_locations_certificateAuthorities.PublishCrl(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesPublishCrlRequest(
                name=cert_ref.Parent().RelativeName(),
                publishCertificateRevocationListRequest=messages.
                PublishCertificateRevocationListRequest()))

        revoke_time = times.ParseDateTime(
            certificate.revocationDetails.revocationTime)
        log.status.Print('Revoked certificate [{}] at {}.'.format(
            certificate.name,
            times.FormatDateTime(revoke_time, tzinfo=times.LOCAL)))
    def Run(self, args):
        client = privateca_base.GetClientInstance(api_version='v1')
        messages = privateca_base.GetMessagesModule(api_version='v1')

        template_ref = args.CONCEPTS.certificate_template.Parse()
        template_name = template_ref.RelativeName()

        if not console_io.PromptContinue(
                message='You are about to delete the certificate template [{}]'
                .format(template_ref.RelativeName()),
                default=True):
            log.status.Print('Aborted by user.')
            return

        operation = client.projects_locations_certificateTemplates.Delete(
            messages.
            PrivatecaProjectsLocationsCertificateTemplatesDeleteRequest(
                name=template_name,
                requestId=request_utils.GenerateRequestId()))

        operations.Await(operation,
                         'Deleting Certificate Template',
                         api_version='v1')

        log.status.Print(
            'Deleted Certificate Template [{}].'.format(template_name))
  def Run(self, args):
    new_ca, ca_ref, _ = create_utils.CreateCAFromArgs(
        args, is_subordinate=False)
    project_ref = ca_ref.Parent().Parent()
    key_version_ref = args.CONCEPTS.kms_key_version.Parse()
    kms_key_ref = key_version_ref.Parent() if key_version_ref else None

    iam.CheckCreateCertificateAuthorityPermissions(project_ref, kms_key_ref)

    bucket_ref = None
    if args.IsSpecified('bucket'):
      bucket_ref = storage.ValidateBucketForCertificateAuthority(args.bucket)
      new_ca.gcsBucket = bucket_ref.bucket

    p4sa_email = p4sa.GetOrCreate(project_ref)
    p4sa.AddResourceRoleBindings(p4sa_email, kms_key_ref, bucket_ref)

    create_utils.PrintBetaResourceDeletionDisclaimer('certificate authorities')
    operation = self.client.projects_locations_certificateAuthorities.Create(
        self.messages
        .PrivatecaProjectsLocationsCertificateAuthoritiesCreateRequest(
            certificateAuthority=new_ca,
            certificateAuthorityId=ca_ref.Name(),
            parent=ca_ref.Parent().RelativeName(),
            requestId=request_utils.GenerateRequestId()))

    ca_response = operations.Await(operation, 'Creating Certificate Authority.')
    ca = operations.GetMessageFromResponse(ca_response,
                                           self.messages.CertificateAuthority)

    log.status.Print('Created Certificate Authority [{}].'.format(ca.name))
    def Run(self, args):
        client = privateca_base.GetClientInstance(api_version='v1')
        messages = privateca_base.GetMessagesModule(api_version='v1')

        ca_ref = args.CONCEPTS.certificate_authority.Parse()
        ca_name = ca_ref.RelativeName()

        current_ca = client.projects_locations_caPools_certificateAuthorities.Get(
            messages.
            PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesGetRequest(
                name=ca_name))

        resource_args.CheckExpectedCAType(
            messages.CertificateAuthority.TypeValueValuesEnum.SUBORDINATE,
            current_ca,
            version='v1')

        ca_to_update, update_mask = update_utils_v1.UpdateCAFromArgs(
            args, current_ca.labels)

        # Patch is the gcloud client lib method to update a CA.
        operation = client.projects_locations_caPools_certificateAuthorities.Patch(
            messages.
            PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesPatchRequest(
                name=ca_name,
                certificateAuthority=ca_to_update,
                updateMask=','.join(update_mask),
                requestId=request_utils.GenerateRequestId()))

        return operations.Await(operation,
                                'Updating Subordinate CA.',
                                api_version='v1')
Ejemplo n.º 8
0
    def Run(self, args):
        client = privateca_base.GetClientInstance()
        messages = privateca_base.GetMessagesModule()

        ca_ref = args.CONCEPTS.certificate_authority.Parse()

        current_ca = client.projects_locations_certificateAuthorities.Get(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest(
                name=ca_ref.RelativeName()))

        resource_args.CheckExpectedCAType(
            messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED,
            current_ca)

        ca_to_update, update_mask = update_utils.UpdateCAFromArgs(
            args, current_ca.labels)

        operation = client.projects_locations_certificateAuthorities.Patch(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesPatchRequest(
                name=ca_ref.RelativeName(),
                certificateAuthority=ca_to_update,
                updateMask=','.join(update_mask),
                requestId=request_utils.GenerateRequestId()))

        return operations.Await(operation, 'Updating Root CA.')
Ejemplo n.º 9
0
    def Run(self, args):
        client = privateca_base.GetClientInstance()
        messages = privateca_base.GetMessagesModule()
        ca_ref = args.CONCEPTS.certificate_authority.Parse()

        pem_cert, pem_chain = self._ParsePemChainFromFile(args.pem_chain)

        operation = client.projects_locations_certificateAuthorities.Activate(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesActivateRequest(
                name=ca_ref.RelativeName(),
                activateCertificateAuthorityRequest=messages.
                ActivateCertificateAuthorityRequest(
                    pemCaCertificate=pem_cert,
                    pemCaCertificateChain=pem_chain)))

        operations.Await(operation, 'Activating Certificate Authority.')

        log.status.Print('Creating the initial Certificate Revocation List.')
        client.projects_locations_certificateAuthorities.PublishCrl(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesPublishCrlRequest(
                name=ca_ref.RelativeName(),
                publishCertificateRevocationListRequest=messages.
                PublishCertificateRevocationListRequest()))
Ejemplo n.º 10
0
 def testOperationsInitialFailure(self):
     operation = self.messages.Operation()
     operation.done = True
     operation.error = self.messages.Status(message='failure')
     with self.AssertRaisesExceptionMatches(operations.OperationError,
                                            'failure'):
         operations.Await(operation, 'testing')
Ejemplo n.º 11
0
 def testOperationTimeoutFailure(self, waiter_waitfor_mock):
     operation = self.messages.Operation(
         done=False, name='projects/test/locations/test/operations/test')
     waiter_waitfor_mock.side_effect = waiter.TimeoutError('timeout')
     with self.AssertRaisesExceptionMatches(
             operations.OperationTimeoutError, 'action timed out'):
         operations.Await(operation, 'testing')
Ejemplo n.º 12
0
    def Run(self, args):
        client = privateca_base.GetClientInstance('v1')
        messages = privateca_base.GetMessagesModule('v1')

        cert_template_ref = args.CONCEPTS.certificate_template.Parse()

        flags_v1.ValidateIdentityConstraints(args)

        new_cert_template = messages.CertificateTemplate(
            predefinedValues=flags_v1.ParsePredefinedValues(args),
            identityConstraints=flags_v1.ParseIdentityConstraints(args),
            passthroughExtensions=flags_v1.ParseExtensionConstraints(args),
            description=args.description
            if args.IsSpecified('description') else None)

        operation = client.projects_locations_certificateTemplates.Create(
            messages.
            PrivatecaProjectsLocationsCertificateTemplatesCreateRequest(
                parent=cert_template_ref.Parent().RelativeName(),
                certificateTemplateId=cert_template_ref.Name(),
                certificateTemplate=new_cert_template,
                requestId=request_utils.GenerateRequestId()))

        cert_template_response = operations.Await(
            operation, 'Creating Certificate Template.', api_version='v1')
        cert_template = operations.GetMessageFromResponse(
            cert_template_response, messages.CertificateTemplate)

        log.status.Print('Created Certificate Template [{}].'.format(
            cert_template.name))
Ejemplo n.º 13
0
    def Run(self, args):
        client = privateca_base.GetClientInstance()
        messages = privateca_base.GetMessagesModule()

        ca_ref = args.CONCEPTS.certificate_authority.Parse()

        current_ca = client.projects_locations_certificateAuthorities.Get(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest(
                name=ca_ref.RelativeName()))

        resource_args.CheckExpectedCAType(
            messages.CertificateAuthority.TypeValueValuesEnum.SUBORDINATE,
            current_ca)

        operation = client.projects_locations_certificateAuthorities.Restore(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesRestoreRequest(
                name=ca_ref.RelativeName(),
                restoreCertificateAuthorityRequest=messages.
                RestoreCertificateAuthorityRequest(
                    requestId=request_utils.GenerateRequestId())))

        operations.Await(operation, 'Restoring Subordinate CA')

        log.status.Print('Restored Subordinate CA [{}].'.format(
            ca_ref.RelativeName()))
Ejemplo n.º 14
0
    def Run(self, args):
        kms_key_version_ref, ca_ref = self.ParseResourceArgs(args)
        kms_key_ref = kms_key_version_ref.Parent()
        project_ref = ca_ref.Parent().Parent()

        subject_config = flags.ParseSubjectFlags(args, is_ca=True)
        issuing_options = flags.ParseIssuingOptions(args)
        issuance_policy = flags.ParseIssuancePolicy(args)
        reusable_config_wrapper = flags.ParseReusableConfig(args,
                                                            ca_ref.locationsId,
                                                            is_ca=True)
        lifetime = flags.ParseValidityFlag(args)
        labels = labels_util.ParseCreateArgs(
            args, self.messages.CertificateAuthority.LabelsValue)

        iam.CheckCreateCertificateAuthorityPermissions(project_ref,
                                                       kms_key_ref)

        p4sa_email = p4sa.GetOrCreate(project_ref)
        bucket_ref = storage.CreateBucketForCertificateAuthority(ca_ref)

        p4sa.AddResourceRoleBindings(p4sa_email, kms_key_ref, bucket_ref)

        new_ca = self.messages.CertificateAuthority(
            type=self.messages.CertificateAuthority.TypeValueValuesEnum.
            SELF_SIGNED,
            lifetime=lifetime,
            config=self.messages.CertificateConfig(
                reusableConfig=reusable_config_wrapper,
                subjectConfig=subject_config),
            cloudKmsKeyVersion=kms_key_version_ref.RelativeName(),
            certificatePolicy=issuance_policy,
            issuingOptions=issuing_options,
            gcsBucket=bucket_ref.bucket,
            labels=labels)

        operation = self.client.projects_locations_certificateAuthorities.Create(
            self.messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesCreateRequest(
                certificateAuthority=new_ca,
                certificateAuthorityId=ca_ref.Name(),
                parent=ca_ref.Parent().RelativeName(),
                requestId=request_utils.GenerateRequestId()))

        ca_response = operations.Await(operation,
                                       'Creating Certificate Authority.')
        ca = operations.GetMessageFromResponse(
            ca_response, self.messages.CertificateAuthority)

        log.status.Print('Creating the initial Certificate Revocation List.')
        self.client.projects_locations_certificateAuthorities.PublishCrl(
            self.messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesPublishCrlRequest(
                name=ca.name,
                publishCertificateRevocationListRequest=self.messages.
                PublishCertificateRevocationListRequest()))

        log.status.Print('Created Certificate Authority [{}].'.format(ca.name))
Ejemplo n.º 15
0
    def Run(self, args):
        new_ca, ca_ref, issuer_ref = create_utils.CreateCAFromArgs(
            args, is_subordinate=True)
        project_ref = ca_ref.Parent().Parent()
        key_version_ref = args.CONCEPTS.kms_key_version.Parse()
        kms_key_ref = key_version_ref.Parent() if key_version_ref else None

        iam.CheckCreateCertificateAuthorityPermissions(project_ref,
                                                       kms_key_ref)
        if issuer_ref:
            iam.CheckCreateCertificatePermissions(issuer_ref)
            # Pro-actively look for issuing CA issues to avoid downstream issues.
            create_utils.ValidateIssuingCA(issuer_ref.RelativeName())

        bucket_ref = None
        if args.IsSpecified('bucket'):
            bucket_ref = storage.ValidateBucketForCertificateAuthority(
                args.bucket)
            new_ca.gcsBucket = bucket_ref.bucket

        p4sa_email = p4sa.GetOrCreate(project_ref)
        p4sa.AddResourceRoleBindings(p4sa_email, kms_key_ref, bucket_ref)

        create_utils.PrintBetaResourceDeletionDisclaimer(
            'certificate authorities')
        operations.Await(
            self.client.projects_locations_certificateAuthorities.Create(
                self.messages.
                PrivatecaProjectsLocationsCertificateAuthoritiesCreateRequest(
                    certificateAuthority=new_ca,
                    certificateAuthorityId=ca_ref.Name(),
                    parent=ca_ref.Parent().RelativeName(),
                    requestId=request_utils.GenerateRequestId())),
            'Creating Certificate Authority.')

        csr_response = self.client.projects_locations_certificateAuthorities.Fetch(
            self.messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesFetchRequest(
                name=ca_ref.RelativeName()))
        csr = csr_response.pemCsr

        if args.create_csr:
            files.WriteFileContents(args.csr_output_file, csr)
            log.status.Print(
                "Created Certificate Authority [{}] and saved CSR to '{}'.".
                format(ca_ref.RelativeName(), args.csr_output_file))
            return

        if issuer_ref:
            ca_certificate = self._SignCsr(issuer_ref, csr, new_ca.lifetime)
            self._ActivateCertificateAuthority(ca_ref,
                                               ca_certificate.pemCertificate,
                                               issuer_ref)
            log.status.Print('Created Certificate Authority [{}].'.format(
                ca_ref.RelativeName()))
            return
Ejemplo n.º 16
0
 def _EnableCertificateAuthority(self, ca_name):
   """Enables the given CA."""
   enable_request = self.messages.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesEnableRequest(
       name=ca_name,
       enableCertificateAuthorityRequest=self.messages
       .EnableCertificateAuthorityRequest(
           requestId=request_utils.GenerateRequestId()))
   operation = self.client.projects_locations_caPools_certificateAuthorities.Enable(
       enable_request)
   return operations.Await(operation, 'Enabling CA.', api_version='v1')
Ejemplo n.º 17
0
 def testOperationDelayedFailure(self, cloud_op_poll_mock):
     operation = self.messages.Operation(
         done=False, name='projects/test/locations/test/operations/test')
     cloud_op_poll_mock.return_value = self.messages.Operation(
         done=True,
         name='projects/test/locations/test/operations/test',
         error=self.messages.Status(message='failure'))
     with self.AssertRaisesExceptionMatches(waiter.OperationError,
                                            'failure'):
         operations.Await(operation, 'testing')
Ejemplo n.º 18
0
 def _ActivateCertificateAuthority(self, ca_ref, certificate):
     """Activates the given CA using the given certificate."""
     activate_request = self.messages.PrivatecaProjectsLocationsCertificateAuthoritiesActivateRequest(
         name=ca_ref.RelativeName(),
         activateCertificateAuthorityRequest=self.messages.
         ActivateCertificateAuthorityRequest(
             pemCaCertificate=certificate.pemCertificate,
             pemCaCertificateChain=certificate.pemCertificateChain))
     operation = self.client.projects_locations_certificateAuthorities.Activate(
         activate_request)
     return operations.Await(operation, 'Activating CA.')
Ejemplo n.º 19
0
 def _ActivateCertificateAuthority(self, ca_ref, pem_cert, issuer_ref):
     """Activates the given CA using the given certificate and issuer."""
     activate_request = self.messages.PrivatecaProjectsLocationsCertificateAuthoritiesActivateRequest(
         name=ca_ref.RelativeName(),
         activateCertificateAuthorityRequest=self.messages.
         ActivateCertificateAuthorityRequest(
             pemCaCertificate=pem_cert,
             subordinateConfig=self.messages.SubordinateConfig(
                 certificateAuthority=issuer_ref.RelativeName())))
     operation = self.client.projects_locations_certificateAuthorities.Activate(
         activate_request)
     return operations.Await(operation, 'Activating CA.')
Ejemplo n.º 20
0
 def _ActivateCertificateAuthority(self, ca_name, pem_cert, issuer_ca_name):
   """Activates the given CA using the given certificate and issuing Certificate Authority."""
   activate_request = self.messages.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesActivateRequest(
       name=ca_name,
       activateCertificateAuthorityRequest=self.messages
       .ActivateCertificateAuthorityRequest(
           pemCaCertificate=pem_cert,
           subordinateConfig=self.messages.SubordinateConfig(
               certificateAuthority=issuer_ca_name)))
   operation = self.client.projects_locations_caPools_certificateAuthorities.Activate(
       activate_request)
   return operations.Await(operation, 'Activating CA.', api_version='v1')
Ejemplo n.º 21
0
    def Run(self, args):
        client = privateca_base.GetClientInstance()
        messages = privateca_base.GetMessagesModule()

        cert_ref = args.CONCEPTS.certificate.Parse()
        if not cert_ref:
            raise exceptions.InvalidArgumentException(
                'CERTIFICATE', 'A certificate resource must be specified.')

        labels = labels_util.ParseCreateArgs(args,
                                             messages.Certificate.LabelsValue)

        request = messages.PrivatecaProjectsLocationsCertificateAuthoritiesCertificatesCreateRequest(
        )
        request.certificate = messages.Certificate()
        request.certificateId = cert_ref.Name()
        request.certificate.name = cert_ref.RelativeName()
        request.certificate.lifetime = flags.ParseValidityFlag(args)
        request.certificate.labels = labels
        request.parent = cert_ref.Parent().RelativeName()
        request.requestId = request_utils.GenerateRequestId()

        if args.csr:
            request.certificate.pemCsr = self._ReadCsr(request, args.csr)
        elif args.generate_key:
            request.certificate.config = self._GenerateCertificateConfig(
                request, args, cert_ref.locationsId)
        else:
            # This should not happen because of the required arg group, but protects
            # in case of future additions.
            raise exceptions.OneOfArgumentsRequiredException(
                ['--csr', '--generate-key'],
                ('To create a certificate, please specify either a CSR or the '
                 '--generate-key flag to create a new key.'))

        operation = client.projects_locations_certificateAuthorities_certificates.Create(
            request)
        cert_response = operations.Await(operation, 'Creating Certificate.')
        certificate = operations.GetMessageFromResponse(
            cert_response, messages.Certificate)

        if args.IsSpecified('cert_output_file'):
            self._WritePemChain(certificate.pemCertificate,
                                certificate.pemCertificateChain,
                                args.cert_output_file)

        log.status.Print('Created Certificate [{}].'.format(certificate.name))
  def Run(self, args):
    """Runs the command."""
    self.client = privateca_base.GetClientInstance(api_version='v1')
    self.messages = privateca_base.GetMessagesModule(api_version='v1')

    template_ref = args.CONCEPTS.certificate_template.Parse()
    template = self.client.projects_locations_certificateTemplates.Get(
        self.messages.PrivatecaProjectsLocationsCertificateTemplatesGetRequest(
            name=template_ref.RelativeName()))

    # Name is output-only and will be different for each location.
    template.name = ''

    success_count = 0
    target_locations = args.target_locations
    if args.all_locations:
      target_locations = [
          location for location in locations.GetSupportedLocations('v1')
          if location != template_ref.locationsId
      ]
    for location in target_locations:
      location = location.strip()
      if location == template_ref.locationsId:
        log.warning(
            'Skipping location [{}] since it is the source location.'.format(
                location))
        continue

      try:
        operation = self._CreateOrUpdateTemplate(template_ref.projectsId,
                                                 location, template_ref.Name(),
                                                 template, args.overwrite)
        operations.Await(
            operation,
            'Replicating template to [{}]'.format(location),
            api_version='v1')
        success_count += 1
      except ReplicationError as e:
        if args.continue_on_error:
          log.warning(six.text_type(e))
          continue
        raise e

    log.status.Print(
        'Replicated template [{}] to {} out of {} locations.'.format(
            template_ref.RelativeName(), success_count, len(target_locations)))
Ejemplo n.º 23
0
  def Run(self, args):
    kms_key_version_ref, ca_ref = self.ParseResourceArgs(args)
    kms_key_ref = kms_key_version_ref.Parent()
    project_ref = ca_ref.Parent().Parent()

    common_name, subject = flags.ParseSubject(args.subject)
    subject_alt_names = flags.ParseSanFlags(args)
    issuing_options = flags.ParseIssuingOptions(args)
    issuance_policy = flags.ParseIssuancePolicy(args)
    reusable_config_wrapper = flags.ParseReusableConfig(args)
    lifetime = flags.ParseValidityFlag(args)
    labels = labels_util.ParseCreateArgs(
        args, self.messages.CertificateAuthority.LabelsValue)

    iam.CheckCreateCertificateAuthorityPermissions(project_ref, kms_key_ref)

    p4sa_email = p4sa.GetOrCreate(project_ref)
    bucket_ref = storage.CreateBucketForCertificateAuthority(ca_ref)

    p4sa.AddResourceRoleBindings(p4sa_email, kms_key_ref, bucket_ref)

    new_ca = self.messages.CertificateAuthority(
        type=self.messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED,
        lifetime=lifetime,
        config=self.messages.CertificateConfig(
            reusableConfig=reusable_config_wrapper,
            subjectConfig=self.messages.SubjectConfig(
                commonName=common_name,
                subject=subject,
                subjectAltName=subject_alt_names)),
        cloudKmsKeyVersion=kms_key_version_ref.RelativeName(),
        certificatePolicy=issuance_policy,
        issuingOptions=issuing_options,
        gcsBucket=bucket_ref.bucket,
        labels=labels)

    operation = self.client.projects_locations_certificateAuthorities.Create(
        self.messages
        .PrivatecaProjectsLocationsCertificateAuthoritiesCreateRequest(
            certificateAuthority=new_ca,
            certificateAuthorityId=ca_ref.Name(),
            parent=ca_ref.Parent().RelativeName(),
            requestId=request_utils.GenerateRequestId()))

    return operations.Await(operation, 'Creating Certificate Authority.')
Ejemplo n.º 24
0
  def Run(self, args):
    client = privateca_base.GetClientInstance()
    messages = privateca_base.GetMessagesModule()
    ca_ref = args.CONCEPTS.certificate_authority.Parse()

    pem_cert, pem_chain = self._ParsePemChainFromFile(args.pem_chain)

    operation = client.projects_locations_certificateAuthorities.Activate(
        messages
        .PrivatecaProjectsLocationsCertificateAuthoritiesActivateRequest(
            name=ca_ref.RelativeName(),
            activateCertificateAuthorityRequest=messages
            .ActivateCertificateAuthorityRequest(
                pemCaCertificate=pem_cert,
                subordinateConfig=messages.SubordinateConfig(
                    pemIssuerChain=messages.SubordinateConfigChain(
                        pemCertificates=pem_chain)))))

    operations.Await(operation, 'Activating Certificate Authority.')
Ejemplo n.º 25
0
    def Run(self, args):
        client = privateca_base.GetClientInstance()
        messages = privateca_base.GetMessagesModule()

        ca_ref = args.CONCEPTS.certificate_authority.Parse()

        if not console_io.PromptContinue(
                message=
                'You are about to schedule Certificate Authority [{}] for deletion in 30 days'
                .format(ca_ref.RelativeName()),
                default=True):
            log.status.Print('Aborted by user.')
            return

        current_ca = client.projects_locations_certificateAuthorities.Get(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest(
                name=ca_ref.RelativeName()))

        resource_args.CheckExpectedCAType(
            messages.CertificateAuthority.TypeValueValuesEnum.SUBORDINATE,
            current_ca)

        operation = client.projects_locations_certificateAuthorities.ScheduleDelete(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesScheduleDeleteRequest(
                name=ca_ref.RelativeName(),
                scheduleDeleteCertificateAuthorityRequest=messages.
                ScheduleDeleteCertificateAuthorityRequest(
                    ignoreActiveCertificates=args.ignore_active_certificates,
                    requestId=request_utils.GenerateRequestId())))

        ca_response = operations.Await(
            operation, 'Scheduling Subordinate CA for deletion')
        ca = operations.GetMessageFromResponse(ca_response,
                                               messages.CertificateAuthority)

        formatted_deletion_time = times.ParseDateTime(
            ca.deleteTime).astimezone(tz.tzutc()).strftime('%Y-%m-%dT%H:%MZ')

        log.status.Print(
            'Scheduled Subordinate CA [{}] for deletion at {}.'.format(
                ca_ref.RelativeName(), formatted_deletion_time))
Ejemplo n.º 26
0
    def _SignCsr(self, issuer_ref, csr, lifetime):
        """Issues a certificate under the given issuer with the given settings."""
        certificate_id = 'subordinate-{}'.format(
            certificate_utils.GenerateCertId())
        certificate_name = '{}/certificates/{}'.format(
            issuer_ref.RelativeName(), certificate_id)
        cert_request = self.messages.PrivatecaProjectsLocationsCertificateAuthoritiesCertificatesCreateRequest(
            certificateId=certificate_id,
            parent=issuer_ref.RelativeName(),
            requestId=request_utils.GenerateRequestId(),
            certificate=self.messages.Certificate(name=certificate_name,
                                                  lifetime=lifetime,
                                                  pemCsr=csr))

        operation = self.client.projects_locations_certificateAuthorities_certificates.Create(
            cert_request)
        cert_response = operations.Await(operation, 'Signing CA cert.')
        return operations.GetMessageFromResponse(cert_response,
                                                 self.messages.Certificate)
Ejemplo n.º 27
0
    def Run(self, args):
        cert_ref = args.CONCEPTS.certificate.Parse()
        if cert_ref:
            cert_name = cert_ref.RelativeName()
        else:
            # Check to make sure the certificate was not partially provided.
            self.CheckCompleteResourceFlag(args, [
                'certificate', 'certificate_issuer',
                'certificate_issuer_location'
            ])
            ca_ref = args.CONCEPTS.issuer.Parse()
            if not ca_ref:
                # Check to make sure the certificate authority was not partially
                # provided.
                self.CheckCompleteResourceFlag(args,
                                               ['issuer', 'issuer_location'])
                raise exceptions.Invalid.ArgumentException(
                    '--issuer', 'Expected a value for the issuer.')
            cert_name = certificate_utils.GetCertificateBySerialNum(
                ca_ref, args.serial_number).name

        reason = flags.ParseRevocationChoiceToEnum(args.reason)

        client = privateca_base.GetClientInstance()
        messages = privateca_base.GetMessagesModule()

        operation = client.projects_locations_certificateAuthorities_certificates.Revoke(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesCertificatesRevokeRequest(
                name=cert_name,
                revokeCertificateRequest=messages.RevokeCertificateRequest(
                    reason=reason)))

        response = operations.Await(operation, 'Revoking Certificate.')
        certificate = operations.GetMessageFromResponse(
            response, messages.Certificate)

        revoke_time = times.ParseDateTime(
            certificate.revocationDetails.revocationTime)
        log.Print('Revoked certificate at {}.'.format(
            times.FormatDateTime(revoke_time, tzinfo=times.LOCAL)))
Ejemplo n.º 28
0
  def Run(self, args):
    client = privateca_base.GetClientInstance('v1')
    messages = privateca_base.GetMessagesModule('v1')

    ca_pool_ref = args.CONCEPTS.ca_pool.Parse()

    current_ca_pool = client.projects_locations_caPools.Get(
        messages.PrivatecaProjectsLocationsCaPoolsGetRequest(
            name=ca_pool_ref.RelativeName()))

    pool_to_update, update_mask = update_utils_v1.UpdateCaPoolFromArgs(
        args, current_ca_pool.labels)

    operation = client.projects_locations_caPools.Patch(
        messages.PrivatecaProjectsLocationsCaPoolsPatchRequest(
            name=ca_pool_ref.RelativeName(),
            caPool=pool_to_update,
            updateMask=','.join(update_mask),
            requestId=request_utils.GenerateRequestId()))

    return operations.Await(operation, 'Updating CA pool.', api_version='v1')
    def Run(self, args):
        client = privateca_base.GetClientInstance('v1')
        messages = privateca_base.GetMessagesModule('v1')

        cert_template_ref = args.CONCEPTS.certificate_template.Parse()
        template_name = cert_template_ref.RelativeName()

        current_cert_template = client.projects_locations_certificateTemplates.Get(
            messages.PrivatecaProjectsLocationsCertificateTemplatesGetRequest(
                name=template_name))

        cert_template_to_update, update_mask = self._UpdateCertificateTemplateFromArgs(
            args, current_cert_template.labels)

        # Confirm that the result of this update is intended to be identity
        # reflection, if applicable.
        flags_v1.ValidateIdentityConstraints(
            args,
            existing_copy_subj=current_cert_template.identityConstraints.
            allowSubjectPassthrough,
            existing_copy_sans=current_cert_template.identityConstraints.
            allowSubjectAltNamesPassthrough,
            for_update=True)

        operation = client.projects_locations_certificateTemplates.Patch(
            messages.
            PrivatecaProjectsLocationsCertificateTemplatesPatchRequest(
                name=template_name,
                certificateTemplate=cert_template_to_update,
                updateMask=','.join(update_mask),
                requestId=request_utils.GenerateRequestId()))

        cert_template_response = operations.Await(
            operation, 'Updating Certificate Template.', api_version='v1')
        cert_template = operations.GetMessageFromResponse(
            cert_template_response, messages.CertificateTemplate)

        log.status.Print('Updated Certificate Template [{}].'.format(
            cert_template.name))
Ejemplo n.º 30
0
    def _RunUpdate(self, client, messages, original_cert, args):
        # Collect the list of update masks
        labels_diff = labels_util.GetAndValidateOpsFromArgs(args)
        labels_update = labels_diff.Apply(messages.Certificate.LabelsValue,
                                          original_cert.labels)

        if not labels_update.needs_update:
            raise exceptions.InvalidArgumentException(
                'labels',
                self.NO_CHANGES_MESSAGE.format(certificate=original_cert.name))

        original_cert.labels = labels_update.labels

        operation = client.projects_locations_certificateAuthorities_certificates.Patch(
            messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesCertificatesPatchRequest(
                name=original_cert.name,
                certificate=original_cert,
                updateMask='labels',
                requestId=request_utils.GenerateRequestId()))

        return operations.Await(operation, 'Updating Certificate.')