JFIF$        dd7 

Viewing File: /usr/lib/python3.9/site-packages/certbot/__pycache__/crypto_util.cpython-39.pyc

a

}|�g�]�	@s`dZddlZddlZddlZddlZddlZddlmZddlmZddlm	Z	ddlm
Z
ddlmZddlmZdd	l
mZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddl!m"Z"ddl#m$Z$ddl#m%Z%ddl#m&Z&ddl'Z'ddl(m)Z)ddl(m*Z*ddl+m,Z-ddl.m/Z/ddl.m0Z0ddl.m1Z1ddl2m3Z3e�r�dd l4m5Z5dd!l6m7Z7dd"l8m9Z9dd#l:m;Z;e�<e=�Z>doe?ee@e@e@e@eAe1jBd(�d)d*�ZCdpe1jBeee@e	e@fee@eAeAe1jDd,�d-d.�ZEeFeAd/�d0d1�ZGeFeFeAd2�d3d4�ZHe@eFe
e-jIe1jDee@fd5�d6d7�ZJdqe?e@ee@eFd9�d:d;�ZKee@eFfeAd<�d=d>�ZLe0jMdd?�d@dA�ZNe0jMdd?�dBdC�ZOeedDdEee"dFdGfeFeFejPddH�dIdJ�ZQe@e@ddK�dLdM�ZRe0jMdd?�dNdO�ZSeFe
e)jTe?fdP�dQdR�ZUe-jIjVfeFee-jIe?fee@dS�dTdU�ZWe-jIjVfeFee-jIe?fee@dS�dVdW�ZXe-jIjVfeFee-jIe?fee@dX�dYdZ�ZYe-jIjVfeee)jTee'jZfee-jIe?feFd[�d\d]�Z[e@ejd^�d_d`�Z\e@ejd^�dadb�Z]e@e@dc�ddde�Z^e�_dfej`�Zae@e
e@e@fdg�dhdi�Zbe@e?d^�djdk�Zcdree@e@eAe@dl�dmdn�ZddS)sz�Certbot client crypto utility functions.

.. todo:: Make the transition to use PSS rather than PKCS1_v1_5 when the server
    is capable of handling the signatures.

�N)�List)�Optional)�Set)�Tuple)�
TYPE_CHECKING)�Union)�x509)�InvalidSignature)�UnsupportedAlgorithm)�default_backend)�hashes)�
serialization)�ec)�rsa)�DSAPublicKey)�ECDSA)�EllipticCurvePublicKey)�PKCS1v15)�RSAPublicKey)�Encoding)�NoEncryption)�
PrivateFormat)�crypto)�SSL)�crypto_util)�errors)�
interfaces)�util)�os)�Ed448PublicKey)�Ed25519PublicKey)�
X448PublicKey)�X25519PublicKeyr�	secp256r1�key-certbot.pemT)�key_size�key_dir�key_type�elliptic_curve�keyname�strict_permissions�returnc

Cs�zt||pd|d�}WnFty\}z.tjddd�t�dt|��|�WYd}~n
d}~00d}|r�t�|d|�t�t	j
�||�d	d
�\}	}|	�|	�|�Wd�n1s�0Y|dkr�t�d||�nt�d
||�t�
||�S)a$Initializes and saves a privkey.

    Inits key and saves it in PEM format on the filesystem.

    .. note:: keyname is the attempted filename, it may be different if a file
        already exists at the path.

    :param int key_size: key size in bits if key size is rsa.
    :param str key_dir: Optional key save directory.
    :param str key_type: Key Type [rsa, ecdsa]
    :param str elliptic_curve: Name of the elliptic curve if key type is ecdsa.
    :param str keyname: Filename of key
    :param bool strict_permissions: If true and key_dir exists, an exception is raised if
        the directory doesn't have 0700 permissions or isn't owned by the current user.

    :returns: Key
    :rtype: :class:`certbot.util.Key`

    :raises ValueError: If unable to generate the key given key_size.

    r#)�bitsr(r'�T��exc_infoz&Encountered error while making key: %sNi�i��wbrz Generating RSA key (%d bits): %sz"Generating ECDSA key (%d bits): %s)�make_key�
ValueError�logger�debug�error�strr�make_or_verify_dir�unique_filer�path�join�write�Key)
r%r&r'r(r)r*Zkey_pem�err�key_pathZkey_f�r?�7/usr/lib/python3.9/site-packages/certbot/crypto_util.py�generate_key9s(
�
�(rAF)�privkey�namesr9�must_stapler*r+cCs�tj|j||d�}d}|r~t�|d|�t�tj�|d�dd�\}}|�|�	|�Wd�n1sh0Yt
�d|�t�||d�S)	aCInitialize a CSR with the given private key.

    :param privkey: Key to include in the CSR
    :type privkey: :class:`certbot.util.Key`
    :param set names: `str` names to include in the CSR
    :param str path: Optional certificate save directory.
    :param bool must_staple: If true, include the TLS Feature extension "OCSP Must-Staple"
    :param bool strict_permissions: If true and path exists, an exception is raised if
        the directory doesn't have 0755 permissions or isn't owned by the current user.

    :returns: CSR
    :rtype: :class:`certbot.util.CSR`

    )rDNi�zcsr-certbot.pemi�r0zCreating CSR: %s�pem)
�acme_crypto_utilZmake_csrrErr7r8rr9r:r;r3r4�CSR)rBrCr9rDr*Zcsr_pemZcsr_filenameZcsr_fr?r?r@�generate_csrjs��(rH)�csrr+c	Cs>zt�|�}|jWSttfy8tjddd�YdS0dS)z�Validate CSR.

    Check if `csr` is a valid CSR with a correct self-signed signature.

    :param bytes csr: CSR in PEM.

    :returns: Validity of CSR.
    :rtype: bool

    r-Tr.FN)r�load_pem_x509_csr�is_signature_validr2�	TypeErrorr3r4)rI�reqr?r?r@�	valid_csr�s
rN)rIrBr+cCsNt�|�}tj|dd�}|joL|���tjjtj	j
�|���tjjtj	j
�kS)z�Does private key correspond to the subject public key in the CSR?

    :param bytes csr: CSR in PEM.
    :param bytes privkey: Private key file contents (PEM)

    :returns: Correspondence of private key to CSR subject public key.
    :rtype: bool

    N��password)rrJr
�load_pem_private_keyrK�
public_key�public_bytesr�DERZPublicFormatZSubjectPublicKeyInfo)rIrBrMZpkeyr?r?r@�csr_matches_pubkey�s

���rU)�csrfile�datar+cCs�zt�|�}WnDtyRzt�|�}Wn"tyLt�d�|���Yn0Yn0t�|j	|j
�}|�tj
j�}tjjtj||dd�|fS)a9Import a CSR file, which can be either PEM or DER.

    :param str csrfile: CSR filename
    :param bytes data: contents of the CSR file

    :returns: (`acme_crypto_util.Format.PEM`,
               util.CSR object representing the CSR,
               list of domains requested in the CSR)
    :rtype: tuple

    zFailed to parse CSR file: {0}rE)�filerWZform)r�load_der_x509_csrr2rJr�Error�formatrF�%get_names_from_subject_and_extensions�subject�
extensionsrSr
r�PEM�FormatrrG)rVrWrIZdomainsZdata_pemr?r?r@�import_csr_file�s�ra�)r,r'r(r+c
Cs|dkr0|dkr t�d�|���tjd|d�}n�|dkr�|sFt�d��zZ|��}|dvr�tt|���}|szt�d	|����tj|�t�d
�}nt�d�|���WnTt	y�t�d�|���Yn4t
y�}z|t�t|���WYd}~n
d}~00nt�d
�|���|jt
jtjt�d�S)a�Generate PEM encoded RSA|EC key.

    :param int bits: Number of bits if key_type=rsa. At least 2048 for RSA.
    :param str key_type: The type of key to generate, but be rsa or ecdsa
    :param str elliptic_curve: The elliptic curve to use.

    :returns: new RSA or ECDSA key in PEM form with specified number of bits
              or of type ec_curve when key_type ecdsa is used.
    :rtype: str
    rrbzUnsupported RSA key length: {}i)Zpublic_exponentr%Zecdsaz3When key_type == ecdsa, elliptic_curve must be set.)Z	SECP256R1Z	SECP384R1Z	SECP521R1zInvalid curve type: )�curveZbackendzUnsupported elliptic curve: {}Nz0Invalid key_type specified: {}.  Use [rsa|ecdsa])�encodingr[Zencryption_algorithm)rrZr[rZgenerate_private_key�upper�getattrrrrLr
r6Z
private_bytesrr_rZTraditionalOpenSSLr)r,r'r(�key�namerc�er?r?r@r1�s8

�(�r1)rBr+cCsBt|t�r|��}ztj|dd�Wnty8YdS0dSdS)z�Is valid RSA private key?

    :param privkey: Private key file contents in PEM

    :returns: Validity of private key.
    :rtype: bool

    NrOFT)�
isinstancer6�encoder
rQr2)rBr?r?r@�
valid_privkeys	
rl)�renewable_certr+cCs"t|�t|�t|j|j�dS)a�For checking that your certs were not corrupted on disk.

    Several things are checked:
        1. Signature verification for the cert.
        2. That fullchain matches cert and chain when concatenated.
        3. Check that the private key matches the certificate.

    :param renewable_cert: cert to verify
    :type renewable_cert: certbot.interfaces.RenewableCert

    :raises errors.Error: If verification fails.
    N)�verify_renewable_cert_sig�verify_fullchain�verify_cert_matches_priv_key�	cert_pathr>)rmr?r?r@�verify_renewable_certs
rrc
Cs�z�t|jd��"}t�|��t��}Wd�n1s60Yt|jd��"}t�|��t��}Wd�n1st0Y|��}|js�J�t	||j
|j|j�WnLtt
tfy�}z.d�|j|�}t�|�t�|��WYd}~n
d}~00dS)z�Verifies the signature of a RenewableCert object.

    :param renewable_cert: cert to verify
    :type renewable_cert: certbot.interfaces.RenewableCert

    :raises errors.Error: If signature verification fails.
    �rbNzbverifying the signature of the certificate located at {0} has failed.                 Details: {1})�open�
chain_pathr�load_pem_x509_certificate�readrrqrR�signature_hash_algorithm�verify_signed_payload�	signatureZtbs_certificate_bytes�OSErrorr2r	r[r3�	exceptionrrZ)rm�
chain_file�chain�	cert_file�certZpkri�	error_strr?r?r@rn+s 00
��
rnr rr"r!)rRrz�payloadrxr+cCsJt|t�r|�||t�|�n(t|t�r<|�||t|��n
t�d��dS)a�Check the signature of a payload.

    :param RSAPublicKey/EllipticCurvePublicKey public_key: the public_key to check signature
    :param bytes signature: the signature bytes
    :param bytes payload: the payload bytes
    :param hashes.HashAlgorithm signature_hash_algorithm: algorithm used to hash the payload

    :raises InvalidSignature: If signature verification fails.
    :raises errors.Error: If public key type is not supported
    zUnsupported public key type.N)rjrZverifyrrrrrZ)rRrzr�rxr?r?r@ryCs

�

�ry)rqr>r+c
Cs~z,t�tj�}|�|�|�|�|��WnLttjfyx}z.d�|||�}t	�
|�t�|��WYd}~n
d}~00dS)z� Verifies that the private key and cert match.

    :param str cert_path: path to a cert in PEM format
    :param str key_path: path to a private key file

    :raises errors.Error: If they don't match.
    z�verifying the certificate located at {0} matches the                 private key located at {1} has failed.                 Details: {2}N)rZContextZ
SSLv23_METHODZuse_certificate_fileZuse_privatekey_fileZcheck_privatekeyr{rZr[r3r|r)rqr>�contextrir�r?r?r@rp^s

�
rpc	
Cs4z�t|j��}|��}Wd�n1s*0Yt|j��}|��}Wd�n1s\0Yt|j��}|��}Wd�n1s�0Y|||kr�d}|�|j�}t�|��Wnnt	�y}z*d�|�}t
�|�t�|��WYd}~n4d}~0tj�y.}z|�WYd}~n
d}~00dS)z� Verifies that fullchain is indeed cert concatenated with chain.

    :param renewable_cert: cert to verify
    :type renewable_cert: certbot.interfaces.RenewableCert

    :raises errors.Error: If cert and chain do not combine to fullchain.
    Nz.fullchain does not match cert + chain for {0}!z8reading one of cert, chain, or fullchain has failed: {0})rtrurwrqZfullchain_pathr[ZlineagenamerrZr{r3r|)	rmr}r~rr�Zfullchain_fileZ	fullchainr�rir?r?r@rots"&&&

ro)rWr+cCs�g}tjtjfD]L}zt�||�|fWStjyZ}z|�|�WYd}~qd}~00qt�d�d�dd�|D�����dS)z:Load PEM/DER certificate.

    :raises errors.Error:

    NzUnable to load: {0}�,css|]}t|�VqdS)N)r6)�.0r5r?r?r@�	<genexpr>�sz-pyopenssl_load_certificate.<locals>.<genexpr>)	rZFILETYPE_PEMZ
FILETYPE_ASN1Zload_certificaterZ�appendrr[r:)rWZopenssl_errorsZ	file_typer5r?r?r@�pyopenssl_load_certificate�s"�r�)r��typr+cCsvt�|�}|tjjkr"t�|�}n|tjjks2J�t�|�}z|j�tj	�}Wntj
yfgYS0|j�tj
�S)z�Get a list of Subject Alternative Names from a certificate.

    :param str cert: Certificate (encoded).
    :param Format typ: Which format the `cert` bytes are in.

    :returns: A list of Subject Alternative Names.
    :rtype: list

    )rFr`r_rrvrT�load_der_x509_certificater^Zget_extension_for_classZSubjectAlternativeNameZExtensionNotFound�valueZget_values_for_typeZDNSName)r�r��	x509_certZsan_extr?r?r@�get_sans_from_cert�s

�
r�cCsLt�|�}|tjjkr"t�|�}n|tjjks2J�t�|�}t�|j|j	�S)z�Get a list of domains from a cert, including the CN if it is set.

    :param str cert: Certificate (encoded).
    :param Format typ: Which format the `cert` bytes are in.

    :returns: A list of domain names.
    :rtype: list

    )
rFr`r_rrvrTr�r\r]r^)r�r�r�r?r?r@�get_names_from_cert�s

�r�)rIr�r+cCsLt�|�}|tjjkr"t�|�}n|tjjks2J�t�|�}t�|j|j	�S)z�Get a list of domains from a CSR, including the CN if it is set.

    :param str csr: CSR (encoded).
    :param acme_crypto_util.Format typ: Which format the `csr` bytes are in.
    :returns: A list of domain names.
    :rtype: list

    )
rFr`r_rrJrTrYr\r]r^)rIr�Zx509_reqr?r?r@�get_names_from_req�s

�r�)r~�filetyper+cCst�||�S)z�Dump certificate chain into a bundle.

    :param list chain: List of `crypto.X509` (or wrapped in
        :class:`josepy.util.ComparableX509`).

    )rF�dump_pyopenssl_chain)r~r�r?r?r@r��sr�)rqr+cCs�t|d��}t�|���}Wd�n1s.0Yt���0tjddd�|jjt	j
jd�Wd�S1sv0YdS)z�When does the cert at cert_path start being valid?

    :param str cert_path: path to a cert in PEM format

    :returns: the notBefore value from the cert at cert_path
    :rtype: :class:`datetime.datetime`

    rsN�ignore�'Properties that return.*datetime object��message�Ztzinfo)rtrrvrw�warnings�catch_warnings�filterwarningsZnot_valid_before�replace�datetime�timezone�utc�rq�fr�r?r?r@�	notBefore�s
	,
r�cCs�t|d��}t�|���}Wd�n1s.0Yt���0tjddd�|jjt	j
jd�Wd�S1sv0YdS)z�When does the cert at cert_path stop being valid?

    :param str cert_path: path to a cert in PEM format

    :returns: the notAfter value from the cert at cert_path
    :rtype: :class:`datetime.datetime`

    rsNr�r�r�r�)rtrrvrwr�r�r�Znot_valid_afterr�r�r�r�r�r?r?r@�notAfter
s
	,
r�)�filenamer+cCsNt��}t|d��$}|�|���d��Wd�n1s<0Y|��S)aNCompute a sha256sum of a file.

    NB: In given file, platform specific newlines characters will be converted
    into their equivalent unicode counterparts before calculating the hash.

    :param str filename: path to the file whose hash will be computed

    :returns: sha256 digest of the file in hexadecimal
    :rtype: str
    �rzUTF-8N)�hashlib�sha256rt�updaterwrkZ	hexdigest)r�r�Zfile_dr?r?r@�	sha256sum s2r�s@-----BEGIN CERTIFICATE-----
?
.+?
?
-----END CERTIFICATE-----
?
)�
fullchain_pemr+cCspt�|���}t|�dkr$t�d��g}|D](}t�|�}|�t	j
�}|�|���q,|dd�
|dd��fS)aSplit fullchain_pem into cert_pem and chain_pem

    :param str fullchain_pem: concatenated cert + chain

    :returns: tuple of string cert_pem and chain_pem
    :rtype: tuple

    :raises errors.Error: If there are less than 2 certificates in the chain.

    �zPfailed to parse fullchain into cert and chain: less than 2 certificates in chainrr-�N)�CERT_PEM_REGEX�findallrk�lenrrZrrvrSrr_r��decoder:)r��certsZcerts_normalizedZcert_pemr�r?r?r@�cert_and_chain_from_fullchain;s

r�cCs>t|d��}t�|���}Wd�n1s.0Y|jS)z�Retrieve the serial number of a certificate from certificate path

    :param str cert_path: path to a cert in PEM format

    :returns: serial number of the certificate
    :rtype: int
    rsN)rtrrvrwZ
serial_numberr�r?r?r@�get_serial_from_certZs,r�)�
fullchains�	issuer_cn�warn_on_no_matchr+cCsl|D]N}t�|���}t�|dt��}|j�tjj	�}|r|dj
|kr|Sq|rdt�d|�|dS)a'Chooses the first certificate chain from fullchains whose topmost
    intermediate has an Issuer Common Name matching issuer_cn (in other words
    the first chain which chains to a root whose name matches issuer_cn).

    :param fullchains: The list of fullchains in PEM chain format.
    :type fullchains: `list` of `str`
    :param `str` issuer_cn: The exact Subject Common Name to match against any
        issuer in the certificate chain.

    :returns: The best-matching fullchain, PEM-encoded, or the first if none match.
    :rtype: `str`
    ���rz�Certbot has been configured to prefer certificate chains with issuer '%s', but no chain from the CA matched this issuer. Using the default certificate chain instead.)
r�r�rkrrvrZissuerZget_attributes_for_oidZNameOIDZCOMMON_NAMEr�r3Zwarning)r�r�r�r~r�Ztop_certZ
top_issuer_cnr?r?r@�find_chain_with_issuergs
�r�)rr#r$T)FT)rbrN)F)e�__doc__r�r�Zlogging�rer��typingrrrrrrZcryptographyrZcryptography.exceptionsr	r
Zcryptography.hazmat.backendsrZcryptography.hazmat.primitivesrr
Z)cryptography.hazmat.primitives.asymmetricrrZ-cryptography.hazmat.primitives.asymmetric.dsarZ,cryptography.hazmat.primitives.asymmetric.ecrrZ1cryptography.hazmat.primitives.asymmetric.paddingrZ-cryptography.hazmat.primitives.asymmetric.rsarZ,cryptography.hazmat.primitives.serializationrrrZjosepyZOpenSSLrrZacmerrFZcertbotrrrZcertbot.compatrZ/cryptography.hazmat.primitives.asymmetric.ed448rZ1cryptography.hazmat.primitives.asymmetric.ed25519r Z.cryptography.hazmat.primitives.asymmetric.x448r!Z0cryptography.hazmat.primitives.asymmetric.x25519r"Z	getLogger�__name__r3�intr6�boolr<rArGrH�bytesrNrUr`rar1rlZ
RenewableCertrrrnZ
HashAlgorithmryrproZX509r�r_r�r�r�ZComparableX509r�r�r�r��compile�DOTALLr�r�r�r�r?r?r?r@�<module>s�
��2��%�!��.�����������	�
�
Back to Directory  nL+D550H?Mx ,D"v]qv;6*Zqn)ZP0!1 A "#a$2Qr D8 a Ri[f\mIykIw0cuFcRı?lO7к_f˓[C$殷WF<_W ԣsKcëIzyQy/_LKℂ;C",pFA:/]=H  ~,ls/9ć:[=/#f;)x{ٛEQ )~ =𘙲r*2~ a _V=' kumFD}KYYC)({ *g&f`툪ry`=^cJ.I](*`wq1dđ#̩͑0;H]u搂@:~וKL Nsh}OIR*8:2 !lDJVo(3=M(zȰ+i*NAr6KnSl)!JJӁ* %݉?|D}d5:eP0R;{$X'xF@.ÊB {,WJuQɲRI;9QE琯62fT.DUJ;*cP A\ILNj!J۱+O\͔]ޒS߼Jȧc%ANolՎprULZԛerE2=XDXgVQeӓk yP7U*omQIs,K`)6\G3t?pgjrmۛجwluGtfh9uyP0D;Uڽ"OXlif$)&|ML0Zrm1[HXPlPR0'G=i2N+0e2]]9VTPO׮7h(F*癈'=QVZDF,d߬~TX G[`le69CR(!S2!P <0x<!1AQ "Raq02Br#SCTb ?Ζ"]mH5WR7k.ۛ!}Q~+yԏz|@T20S~Kek *zFf^2X*(@8r?CIuI|֓>^ExLgNUY+{.RѪ τV׸YTD I62'8Y27'\TP.6d&˦@Vqi|8-OΕ]ʔ U=TL8=;6c| !qfF3aů&~$l}'NWUs$Uk^SV:U# 6w++s&r+nڐ{@29 gL u"TÙM=6(^"7r}=6YݾlCuhquympǦ GjhsǜNlɻ}o7#S6aw4!OSrD57%|?x>L |/nD6?/8w#[)L7+6〼T ATg!%5MmZ/c-{1_Je"|^$'O&ޱմTrb$w)R$& N1EtdU3Uȉ1pM"N*(DNyd96.(jQ)X 5cQɎMyW?Q*!R>6=7)Xj5`J]e8%t!+'!1Q5 !1 AQaqё#2"0BRb?Gt^## .llQT $v,,m㵜5ubV =sY+@d{N! dnO<.-B;_wJt6;QJd.Qc%p{ 1,sNDdFHI0ГoXшe黅XۢF:)[FGXƹ/w_cMeD,ʡcc.WDtA$j@:) -# u c1<@ۗ9F)KJ-hpP]_x[qBlbpʖw q"LFGdƶ*s+ډ_Zc"?%t[IP 6J]#=ɺVvvCGsGh1 >)6|ey?Lӣm,4GWUi`]uJVoVDG< SB6ϏQ@ TiUlyOU0kfV~~}SZ@*WUUi##; s/[=!7}"WN]'(L! ~y5g9T̅JkbM' +s:S +B)v@Mj e Cf jE 0Y\QnzG1д~Wo{T9?`Rmyhsy3!HAD]mc1~2LSu7xT;j$`}4->L#vzŏILS ֭T{rjGKC;bpU=-`BsK.SFw4Mq]ZdHS0)tLg