Ejemplo n.º 1
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.º 2
0
    def Run(self, args):
        self.client = privateca_base.GetClientInstance()
        self.messages = privateca_base.GetMessagesModule()

        cert_ref = args.CONCEPTS.certificate.Parse()
        issuing_ca = self._GetIssuingCa(cert_ref.Parent().RelativeName())

        if issuing_ca.tier == self.messages.CertificateAuthority.TierValueValuesEnum.DEVOPS:
            CreateBeta._ValidateArgsForDevOpsIssuer(args)

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

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

        # TODO(b/12345): only show this for Enterprise certs.
        create_utils.PrintBetaResourceDeletionDisclaimer('certificates')

        if args.csr:
            request.certificate.pemCsr = _ReadCsr(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.'))

        certificate = self.client.projects_locations_certificateAuthorities_certificates.Create(
            request)

        status_message = 'Created Certificate'
        # DevOps certs won't have a name.
        if certificate.name:
            status_message += ' [{}]'.format(certificate.name)

        if args.IsSpecified('cert_output_file'):
            status_message += ' and saved it to [{}]'.format(
                args.cert_output_file)
            _WritePemChain(certificate.pemCertificate,
                           certificate.pemCertificateChain,
                           args.cert_output_file)

        status_message += '.'
        log.status.Print(status_message)
Ejemplo n.º 3
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))
Ejemplo n.º 4
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.º 5
0
 def testParseValidityFlag(self):
     flags.AddValidityFlag(self.parser, 'certificate')
     args = self.parser.parse_args(['--validity', 'P30D'])
     duration = flags.ParseValidityFlag(args)
     self.assertEqual(duration, '2592000s')
Ejemplo n.º 6
0
 def testParseValidityFlagDefaultValue(self):
     flags.AddValidityFlag(self.parser, 'certificate')
     args = self.parser.parse_args([])
     duration = flags.ParseValidityFlag(args)
     self.assertEqual(duration, '315569261s')
Ejemplo n.º 7
0
    def Run(self, args):
        kms_key_version_ref, ca_ref, issuer_ref = _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)
        if issuer_ref:
            iam.CheckCreateCertificatePermissions(issuer_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.
            SUBORDINATE,
            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)

        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.GetCsr(
            self.messages.
            PrivatecaProjectsLocationsCertificateAuthoritiesGetCsrRequest(
                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, lifetime)
            self._ActivateCertificateAuthority(ca_ref, ca_certificate)
            log.status.Print('Created Certificate Authority [{}].'.format(
                ca_ref.RelativeName()))
            return

        # This should not happen because of the required arg group, but it protects
        # us in case of future additions.
        raise exceptions.OneOfArgumentsRequiredException([
            '--issuer', '--create-csr'
        ], ('To create a subordinate CA, please provide either an issuer or the '
            '--create-csr flag to output a CSR to be signed by another issuer.'
            ))
Ejemplo n.º 8
0
def CreateCAFromArgs(args, is_subordinate):
  """Creates a CA object from CA create flags.

  Args:
    args: The parser that contains the flag values.
    is_subordinate: If True, a subordinate CA is returned, otherwise a root CA.

  Returns:
    A tuple for the CA to create with (CA object, CA ref, issuer).
  """

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

  ca_ref, source_ca_ref, issuer_ref = _ParseCAResourceArgs(
      args)
  source_ca = None

  if source_ca_ref:
    source_ca = client.projects_locations_certificateAuthorities.Get(
        messages.PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest(
            name=source_ca_ref.RelativeName()))
    if not source_ca:
      raise exceptions.InvalidArgumentException(
          '--from-ca', 'The provided source CA could not be retrieved.')

  tier = flags.ParseTierFlag(args)
  keyspec = flags.ParseKeySpec(args)
  if tier == messages.CertificateAuthority.TierValueValuesEnum.DEVOPS and keyspec.cloudKmsKeyVersion:
    raise exceptions.InvalidArgumentException(
        '--kms-key-version',
        'The DevOps tier does not support user-specified KMS keys.')

  subject_config = messages.SubjectConfig(
      subject=messages.Subject(), subjectAltName=messages.SubjectAltNames())
  if args.IsSpecified('subject'):
    subject_config.commonName, subject_config.subject = flags.ParseSubject(args)
  elif source_ca:
    subject_config.commonName = source_ca.config.subjectConfig.commonName
    subject_config.subject = source_ca.config.subjectConfig.subject

  if flags.SanFlagsAreSpecified(args):
    subject_config.subjectAltName = flags.ParseSanFlags(args)
  elif source_ca:
    subject_config.subjectAltName = source_ca.config.subjectConfig.subjectAltName
  flags.ValidateSubjectConfig(subject_config, is_ca=True)

  issuing_options = flags.ParseIssuingOptions(args)
  if source_ca and not args.IsSpecified('publish_ca_cert'):
    issuing_options.includeCaCertUrl = source_ca.issuingOptions.includeCaCertUrl
  if source_ca and not args.IsSpecified('publish_crl'):
    issuing_options.includeCrlAccessUrl = source_ca.issuingOptions.includeCrlAccessUrl

  issuance_policy = flags.ParseIssuancePolicy(args)
  if source_ca and not issuance_policy:
    issuance_policy = source_ca.certificatePolicy

  reusable_config_wrapper = flags.ParseReusableConfig(
      args, ca_ref.locationsId, is_ca=True)
  if source_ca and not flags.ReusableConfigFlagsAreSpecified(args):
    reusable_config_wrapper = source_ca.config.reusableConfig

  lifetime = flags.ParseValidityFlag(args)
  if source_ca and not args.IsSpecified('validity'):
    lifetime = source_ca.lifetime

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

  new_ca = messages.CertificateAuthority(
      tier=tier,
      type=messages.CertificateAuthority.TypeValueValuesEnum.SUBORDINATE
      if is_subordinate else
      messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED,
      lifetime=lifetime,
      config=messages.CertificateConfig(
          reusableConfig=reusable_config_wrapper, subjectConfig=subject_config),
      keySpec=keyspec,
      certificatePolicy=issuance_policy,
      issuingOptions=issuing_options,
      gcsBucket=None,
      labels=labels)

  return (new_ca, ca_ref, issuer_ref)