
    8                        d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ	 ddlm
Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlZdZd Z d Z! ejD                  ejF                  jH                        ejJ                   G d dejL                                      Z'y)zCreate a certificate.    )absolute_import)division)unicode_literals)cryptokeyversions)base)certificate_utils)request_utils)
exceptions)deps)flags)key_generation)	pem_utils)resource_args)labels_util)concept_parsers)presentation_specs)log)filesNa7  The path where the generated private key file should be written (in PEM format).

Note: possession of this key file could allow anybody to act as this certificate's
subject. Please make sure that you store this key file in a secure location at all
times, and ensure that only authorized users have access to it.c                     	 t        j                  |       S # t         j                  t        t        f$ r% t        j                  dj                  |             w xY w)Nz&Could not read provided CSR file '{}'.)r   ReadFileContentsErrorOSErrorIOErrorr
   BadFileExceptionformat)csr_files    ,lib/surface/privateca/certificates/create.py_ReadCsrr   .   sS    !!(++
++w	( 

%
%077A s
    AAc                     	 | g|z   }t        j                  |t        j                  |             y # t         j                  t
        t        f$ r% t        j                  dj                  |            w xY w)Nz$Could not write certificate to '{}'.)
r   WriteFileContentsr   PemChainForOutputr   r   r   r
   r   r   )pem_certissuing_chain	cert_file	pem_chains       r   _WritePemChainr&   7   si    
]*I	Iy'B'B9'MN
++w	( 

%
%.55i@ s
   /2 AA5c                   X    e Zd ZdZed        Zed        Zd Zed        Z	d Z
d Zd Zy	)
Createab  Create a new certificate.

  ## EXAMPLES

  To create a certificate using a CSR:

      $ {command} frontend-server-tls \
        --issuer-pool=my-pool --issuer-location=us-west1 \
        --csr=./csr.pem \
        --cert-output-file=./cert.pem \
        --validity=P30D

  To create a certificate using a client-generated key:

      $ {command} frontend-server-tls \
        --issuer-pool=my-pool --issuer-location=us-west1 \
        --generate-key \
        --key-output-file=./key \
        --cert-output-file=./cert.pem \
        --dns-san=www.example.com \
        --use-preset-profile=leaf_server_tls
  c           
      (   | j                  ddd      }t        j                  ddd      j                  |       t        j                  dd	d
dd      j                  |       t	        j
                  | ddd       t        j                  |        | j                  ddd      }|j                  d      }t        j                  ddd      j                  |       t        j                  dddd
      j                  |       |j                  d      }|j                  ddd      }|j                  d      }t        j                  dddddd      j                  |       t        j                  dt        d      j                  |       t        j                  dd d      j                  |        |j                  d!d      }t	        j                  |       |j                  dd"#      }t	        j                  |dd$%       t	        j                  |       t	        j                  |        d&}	t        j                  t        j                   |	t#        j$                  |	t&        j)                         g      d'd(      t        j                   d)t#        j*                  d*      d+dd,      t        j                   d-t#        j,                         d.|/      gd0d1gi2      j                  |        | j.                  j1                  d3       y )4NTz Certificate persistence options.)mutexrequiredhelpz--cert-output-fileznThe path where the resulting PEM-encoded certificate chain file should be written (ordered from leaf to root).F)r,   r+   z--validate-onlyzIf this flag is set, the certificate resource will not be persisted and the returned certificate will not contain the pem_certificate field.
store_true)r,   actiondefaultr+   certificateP30Dz30 dayszCertificate generation method.z4To issue a certificate from a CSR use the following:)r,   --csrz4A PEM-encoded certificate signing request file path.z--rdn-sequence-subjectzyIf this value is set then the issued certificate will use the subject found in the CSR preserving the exact RDN sequence.)r,   hiddenr.   z?Alternatively, you may describe the certificate and key to use.z]To describe the key that will be used for this certificate, use one of the following options.z.To generate a new key pair, use the following:--generate-keyzTUse this flag to have a new RSA-2048 private key securely generated on your machine.store_const)r,   r.   constr/   r+   z--key-output-filez--cazThe name of an existing certificate authority to use for issuing the certificate. If omitted, a certificate authority will be will be chosen from the CA pool by the service on your behalf.z&The subject names for the certificate.z1The x509 configuration used for this certificate.)r*   r,   r   )is_ca_commanddefault_max_chain_lengthCERTIFICATEa5  The name of the certificate to issue. If the certificate ID is omitted, a random identifier will be generated according to the following format: {YYYYMMDD}-{3 random alphanumeric characters}-{3 random alphanumeric characters}. The certificate ID is not required when the issuing CA pool is in the DevOps tier.)r+   
--templatecertificate_templateaE  The name of a certificate template to use for issuing this certificate, if desired. A template may overwrite parts of the certificate request, and the use of certificate templates may be required and/or regulated by the issuing CA Pool's CA Manager. The specified template must be in the same location as the issuing CA Pool.)r+   prefixes--kms-key-versionz5An existing KMS key version backing this certificate.)groupz--template.locationzCERTIFICATE.issuer-location)command_level_fallthroughszyaml(certificateDescription))	add_groupr   ArgumentAddToParserr   AddValidityFlagr   AddCreateLabelsFlags_KEY_OUTPUT_HELPAddSubjectFlagsAddInlineX509ParametersFlagsAddUsePresetProfilesFlagAddSubjectKeyIdFlagr   ConceptParserr   ResourcePresentationSpecr   CreateCertResourceSpecr(   !_GenerateCertificateIdFallthrough%CreateCertificateTemplateResourceSpecCreateKmsKeyVersionResourceSpecdisplay_info	AddFormat)
parserpersistence_groupcert_generation_group	csr_groupnon_csr_group	key_groupkey_generation_groupsubject_groupx509_parameters_groupcert_args
             r   ArgszCreate.Args[   s?   ((T(J )  	MM>  k#$MM& 
 k#$	&-C$$V,",,T(H -  &//C 0 I 	MML k)MM J  k))33N 4 M '',	 ( I %..= /  	MM* 
 k&'MM"2Tk&'MMI  k&!++5 , M 
-()33L 4  
&&UQ 
""#89	f%H!!7744vGGIJ#  77CC**  77#==?G	9"	
H "$A#B$
I'N k& !!"@A    c                 N     d _          fd}t        j                  |ddd      S )NFc                  :    d _         t        j                         S )NT)id_fallthrough_was_usedr   GenerateCertId)clss   r   FallthroughFnz?Create._GenerateCertificateIdFallthrough.<locals>.FallthroughFn   s    $(c!--//r]   z<certificate id will default to an automatically generated id)functionhintactiveplural)r`   r   Fallthrough)rb   rc   s   ` r   rM   z(Create._GenerateCertificateIdFallthrough   s1    "'C0 K	 r]   c                     |j                  d      r)|j                  d      rt        j                  ddgd      t        j                  |d       y)z Validates the command-line args.use_preset_profiletemplatez--use-preset-profiler:   zZTo create a certificate, please specify either a preset profile or a certificate template.kms_key_versionN)IsSpecifiedr
   OneOfArgumentsRequiredExceptionr   %ValidateResourceIsCompleteIfSpecified)selfargss     r   _ValidateArgszCreate._ValidateArgs   sQ    ,-$2B2B:2N66!<
0+  77>OPr]   c                    g }| j                   s|j                  d       |j                  d      r|j                  d       |rJdj                  |      }t	        |      dk(  rdnd}t        j                  dj                  ||             y	y	)
zNPrints warnings if certain command-line args are used for an unpersisted cert.zcertificate IDlabelsz,    waswerez{names} {verb} specified but will not be used since the issuing CA pool is in the DevOps tier, which does not expose certificate lifecycle.)namesverbN)r`   appendrm   joinlenr   warningr   )rb   rq   unused_argsrx   ry   s        r    _PrintWarningsForUnpersistedCertz'Create._PrintWarningsForUnpersistedCert  s     K&&)*!"ii$e+&!+Ud	kk##)6D6#A r]   c                    |j                   j                  j                         }|j                  r:t	        j
                  d      \  }}t	        j                  |j                  |       |S |rPt        j                  |      }t        j                  rt        |j                        S t        |j                  d      S t        j                  g dd      )z]Fetches the public key associated with a non-CSR certificate request, as UTF-8 encoded bytes.i   zutf-8)r2   r4   r=   zTo create a certificate, please specify either a CSR, the --generate-key flag to create a new key, or the --kms-key-version flag to use an existing KMS key.)CONCEPTSrl   Parsegenerate_keyr   	RSAKeyGenExportPrivateKeykey_output_filer   GetPublicKeysixPY2bytespemr
   rn   )rp   rq   rl   private_key
public_keypublic_key_responses         r   _GetPublicKeyzCreate._GetPublicKey  s    mm3399;O . 8 8 >k:%%d&:&:KH	-::?K WW #''
( (,,g6 66
:D r]   c                    | j                  |      }| j                  j                         }| j                  j                         |_        ||j                  _        | j                  j                  j                  j                  |j                  _        t        j                  |      |_        t        j                  |d      |_        t        j                  || j                        |_        |S )NF)r7   )r   messagesCertificateConfig	PublicKey	publicKeykeyFormatValueValuesEnumPEMr   r   ParseSubjectFlagssubjectConfigParseX509Parameters
x509ConfigParseSubjectKeyIdsubjectKeyId)rp   requestrq   r   configs        r   _GenerateCertificateConfigz!Create._GenerateCertificateConfig5  s    ##D)J]],,.F}}..0F%F"mm55KKOOF 2248F11$eLF11$FFMr]   c                    t        j                  d      | _        t        j                  d      | _        | j                  |       |j                  j                  j                         }t        j                  || j                  j                  j                        }| j                  j                         }| j                  j                         |_        |j                         |_        t!        j"                  |      |j                  _        ||j                  _        |j)                         j+                         |_        t/        j0                         |_        |j4                  |_        |j9                  d      r|j:                  |_        |j                  j>                  j                         }|rN|j@                  |j@                  k7  rtC        jD                  dd      |j+                         |j                  _#        |jH                  rjtK        |jH                        |j                  _&        |jN                  r[| j                  j                  jP                  jR                  |j                  _*        n!| jW                  ||      |j                  _,        | j                  jZ                  j]                  |      }|j4                  r|S d}|j^                  r|dja                  |j^                        z  }nt\        jc                  |       |jd                  rI|dja                  |jf                        z  }ti        |jd                  |jj                  |jf                         |d	z  }tl        jn                  jq                  |       y )
Nv1)api_versioncar:   zMThe certificate template must be in the same location as the issuing CA Pool.zCreated Certificatez [{}]z and saved it to [{}].)9privateca_baseGetClientInstanceclientGetMessagesModuler   rr   r   r0   r   r   ParseCreateArgsCertificateLabelsValue:PrivatecaProjectsLocationsCaPoolsCertificatesCreateRequestNamecertificateIdr   ParseValidityFlaglifetimert   ParentRelativeNameparentr	   GenerateRequestId	requestIdvalidate_onlyvalidateOnlyrm   r   issuingCertificateAuthorityIdrk   locationsIdr
   InvalidArgumentExceptioncertificateTemplatecsrr   pemCsrrdn_sequence_subjectSubjectModeValueValuesEnumRDN_SEQUENCEsubjectModer   r   'projects_locations_caPools_certificatesr(   namer   r   pemCertificatecert_output_filer&   pemCertificateChainr   statusPrint)rp   rq   cert_refrt   r   template_refr0   status_messages           r   Runz
Create.RunA  s    22tDDK"44FDMt}}((..0H((dmm''33F
 	PPR  --335G$MMOG#(#:#:4#@G !'G__&335GN%779G--G.2ggg+==))//1L		!	!X%9%9	911
 	

 1=0I0I0Kg-xx#+DHH#5g 		"	"MM%%@@MM 	' $(#B#B
4$g  ++EELLK
 *N{'7'788n--d3!!/66t7L7LMMn

$
$

)
)


 cNJJ^$r]   N)__name__
__module____qualname____doc__staticmethodr\   classmethodrM   rr   r   r   r   r    r]   r   r(   r(   A   s^    . NB NB`  Q  "6
E%r]   r(   )(r   
__future__r   r   r   googlecloudsdk.api_lib.cloudkmsr    googlecloudsdk.api_lib.privatecar   r   r   r	   googlecloudsdk.callioper
    googlecloudsdk.calliope.conceptsr   $googlecloudsdk.command_lib.privatecar   r   r   r   $googlecloudsdk.command_lib.util.argsr   (googlecloudsdk.command_lib.util.conceptsr   r   googlecloudsdk.corer   googlecloudsdk.core.utilr   r   rE   r   r&   ReleaseTracksReleaseTrackGADefaultUniverseOnlyCreateCommandr(   r   r]   r   <module>r      s     &  ' = C > : ( . 1 6 ? : > < D G # * 
C  D%%(()C%T C%  *C%r]   