Your IP : 216.73.216.224


Current Path : /lib/python3/dist-packages/certbot/__pycache__/
Upload File :
Current File : //lib/python3/dist-packages/certbot/__pycache__/crypto_util.cpython-38.pyc

U

�]c?�@s�dZddlZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
ddlmZddl
mZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlm Z ddl!m"Z"e�#e$�Z%dEdd�Z&dd�Z'dd�Z(dd�Z)dd�Z*dd�Z+dd �Z,d!d"�Z-d#d$�Z.d%d&�Z/d'd(�Z0d)d*�Z1d+d,�Z2e
j3fd-d.�Z4e
j3fd/d0�Z5e
j3fd1d2�Z6d3d4�Z7d5d6�Z8e
j3fd7d8�Z9e
j3fd9d:�Z:d;d<�Z;d=d>�Z<d?d@�Z=dAdB�Z>dCdD�Z?dS)Fz�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)�SSL)�crypto)�x509)�InvalidSignature)�default_backend)�ECDSA)�EllipticCurvePublicKey)�PKCS1v15)�RSAPublicKey)�crypto_util)�IO)�errors)�
interfaces)�util)�os�key-certbot.pemc
Cs�zt|�}Wn4tk
r@}ztjddd�|�W5d}~XYnXtj�tj�}t	�
|d|j�t	�t
j�||�dd�\}}|�|�|�W5QRXt�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: RSA key size in bits
    :param str key_dir: Key save directory.
    :param str keyname: Filename of key

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

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

    �T��exc_infoNi�i��wbzGenerating key (%d bits): %s)�make_key�
ValueError�logger�error�zope�	component�
getUtilityr�IConfigr�make_or_verify_dir�strict_permissions�unique_filer�path�join�write�debugZKey)Zkey_sizeZkey_dirZkeynameZkey_pem�err�configZkey_f�key_path�r(�5/usr/lib/python3/dist-packages/certbot/crypto_util.py�
init_save_key%s �r*c	Cs�tj�tj�}tj|j||jd�}t	�
|d|j�t	�t
j�|d�dd�\}}|�|�|�W5QRXt�d|�t	�||d�S)a2Initialize 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: Certificate save directory.

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

    )�must_staplei�zcsr-certbot.pemi�rzCreating CSR: %s�pem)rrrrr�acme_crypto_utilZmake_csrr,r+rrrr rr!r"r#rr$�CSR)�privkey�namesr!r&Zcsr_pemZcsr_fZcsr_filenamer(r(r)�
init_save_csrIs ��r1cCsJzt�tj|�}|�|���WStjk
rDtjddd�YdSXdS)z�Validate CSR.

    Check if `csr` is a valid CSR for the given domains.

    :param str csr: CSR in PEM.

    :returns: Validity of CSR.
    :rtype: bool

    rTrFN)r�load_certificate_request�FILETYPE_PEM�verifyZ
get_pubkey�Errorrr$)�csr�reqr(r(r)�	valid_csrls�r8cCsTt�tj|�}t�tj|�}z|�|�WStjk
rNtjddd�YdSXdS)z�Does private key correspond to the subject public key in the CSR?

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

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

    rTrFN)rr2r3�load_privatekeyr4r5rr$)r6r/r7Zpkeyr(r(r)�csr_matches_pubkey�s
�r:cCs�tj}tj}z|tj|�}WnLtjk
rhz|||�}Wn&tjk
rbt�d�|���YnXYnXt|�}t�||�}|t	j
||dd�|fS)a/Import a CSR file, which can be either PEM or DER.

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

    :returns: (`crypto.FILETYPE_PEM`,
               util.CSR object representing the CSR,
               list of domains requested in the CSR)
    :rtype: tuple

    zFailed to parse CSR file: {0}r,)�file�dataZform)rr3r2�
FILETYPE_ASN1r5r
�format�"_get_names_from_loaded_cert_or_reqZdump_certificate_requestrr.)Zcsrfiler<ZPEM�loadr6ZdomainsZdata_pemr(r(r)�import_csr_file�srAcCs0|dkst�t��}|�tj|�t�tj|�S)z�Generate PEM encoded RSA key.

    :param int bits: Number of bits, at least 1024.

    :returns: new RSA key in PEM form with specified number of bits
    :rtype: str

    i)�AssertionErrorrZPKeyZgenerate_keyZTYPE_RSAZdump_privatekeyr3)�bits�keyr(r(r)r�s	rc	Cs6zt�tj|���WSttjfk
r0YdSXdS)z�Is valid RSA private key?

    :param str privkey: Private key file contents in PEM

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

    FN)rr9r3Zcheck�	TypeErrorr5)r/r(r(r)�
valid_privkey�s	�
rFcCs"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 `.storage.RenewableCert` renewable_cert: cert to verify

    :raises errors.Error: If verification fails.
    N)�verify_renewable_cert_sig�verify_fullchain�verify_cert_matches_priv_key�certr/)�renewable_certr(r(r)�verify_renewable_cert�srLc
Cs�z�t|jd��}t�|��t��}W5QRXt|jd��}t�|��t��}W5QRX|��}t�	��t
||j|j|j
�W5QRXWnJtttfk
r�}z&d�|j|�}t�|�t�|��W5d}~XYnXdS)z�Verifies the signature of a `.storage.RenewableCert` object.

    :param `.storage.RenewableCert` renewable_cert: cert to verify

    :raises errors.Error: If signature verification fails.
    �rbz[verifying the signature of the cert located at {0} has failed.                 Details: {1}N)�open�chainrZload_pem_x509_certificate�readrrJ�
public_key�warnings�catch_warnings�verify_signed_payload�	signatureZtbs_certificate_bytes�signature_hash_algorithm�IOErrorrrr>r�	exceptionr
r5)rK�
chain_filerO�	cert_filerJZpk�e�	error_strr(r(r)rG�s"
��
rGc	Cs�t���vt�d�t|t�rB|�|t�|�}|�|�|��n8t|t	�rp|�|t
|��}|�|�|��n
t�d��W5QRXdS)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 cryptography.hazmat.primitives.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
    �ignorezUnsupported public key typeN)
rRrS�simplefilter�
isinstancer
�verifierr	�updater4rrr
r5)rQrUZpayloadrVr`r(r(r)rT�s$


�


�

rTc
Cs|z,t�tj�}|�|�|�|�|��WnJttjfk
rv}z&d�|||�}t	�
|�t�|��W5d}~XYnXdS)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 cert located at {0} matches the                 private key located at {1} has failed.                 Details: {2}N)rZContextZ
SSLv23_METHODZuse_certificate_fileZuse_privatekey_fileZcheck_privatekeyrWr5r>rrXr
)�	cert_pathr'�contextr[r\r(r(r)rIs

�
rIc	
Cs�z�t|j��}|��}W5QRXt|j��}|��}W5QRXt|j��}|��}W5QRX|||kr�d}|�|j�}t�|��Wnft	k
r�}z"d�|�}t
�|�t�|��W5d}~XYn(tjk
r�}z|�W5d}~XYnXdS)z� Verifies that fullchain is indeed cert concatenated with chain.

    :param `.storage.RenewableCert` renewable_cert: cert to verify

    :raises errors.Error: If cert and chain do not combine to fullchain.
    z.fullchain does not match cert + chain for {0}!z8reading one of cert, chain, or fullchain has failed: {0}N)rNrOrPrJ�	fullchainr>Zlineagenamer
r5rWrrX)	rKrYrOrZrJZfullchain_filerdr\r[r(r(r)rH-s"

rHcCs�g}tjtjfD]J}zt�||�|fWStjk
rX}z|�|�W5d}~XYqXqt�d�d�dd�|D�����dS)z:Load PEM/DER certificate.

    :raises errors.Error:

    NzUnable to load: {0}�,css|]}t|�VqdS�N)�str)�.0rr(r(r)�	<genexpr>Usz-pyopenssl_load_certificate.<locals>.<genexpr>)	rr3r=�load_certificater5�appendr
r>r")r<Zopenssl_errorsZ	file_typerr(r(r)�pyopenssl_load_certificateGs�rlcCs8z|||�WStjk
r2tjddd��YnXdS)NrTr)rr5rr�Zcert_or_req_str�	load_func�typr(r(r)�_load_cert_or_reqYs
rpcCst�t|||��Srf)r-Z_pyopenssl_cert_or_req_sanrprmr(r(r)�_get_sans_from_cert_or_reqbs
�rqcCst|tj|�S)z�Get a list of Subject Alternative Names from a certificate.

    :param str cert: Certificate (encoded).
    :param typ: `crypto.FILETYPE_PEM` or `crypto.FILETYPE_ASN1`

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

    )rqrrj)rJror(r(r)�get_sans_from_certis

�rrcCst|||�}t|�Srf)rpr?)Zcert_or_reqrnro�loaded_cert_or_reqr(r(r)�_get_names_from_cert_or_reqwsrtcCs
t�|�Srf)r-Z _pyopenssl_cert_or_req_all_names)rsr(r(r)r?|sr?cCst|tj|�S)z�Get a list of domains from a cert, including the CN if it is set.

    :param str cert: Certificate (encoded).
    :param typ: `crypto.FILETYPE_PEM` or `crypto.FILETYPE_ASN1`

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

    )rtrrj)r6ror(r(r)�get_names_from_cert�s

�rucCst�||�S)z�Dump certificate chain into a bundle.

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

    )r-�dump_pyopenssl_chain)rOZfiletyper(r(r)rv�s	rvcCst|tjj�S)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`

    )�_notAfterBeforer�X509Z
get_notBefore�rbr(r(r)�	notBefore�s	rzcCst|tjj�S)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`

    )rwrrxZget_notAfterryr(r(r)�notAfter�s	r{c
Cs�t|��}t�tj|���}W5QRX||�}|dd�d|dd�d|dd�d|dd�d|dd	�d|d	d
�g}d�|�}tjr�|�d�}t	�
|�S)
aPInternal helper function for finding notbefore/notafter.

    :param str cert_path: path to a cert in PEM format
    :param function method: one of ``crypto.X509.get_notBefore``
        or ``crypto.X509.get_notAfter``

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

    r��-���T�
�:�N��ascii)rNrrjr3rPr"�sixZPY3�decode�	pyrfc3339�parse)rb�method�frZ	timestampZreformatted_timestampZ
timestamp_strr(r(r)rw�s$
�



�

rwc	Cs:t��}t|d��}|�|���d��W5QRX|��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-8)�hashlib�sha256rNrarP�encodeZ	hexdigest)�filenamer�Zfile_dr(r(r)�	sha256sum�sr�cCs8t�tjt�tj|����}|t|�d���}||fS)z�Split 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

    N)rZdump_certificater3rjr��len�lstrip)Z
fullchain_pemrJrOr(r(r)�cert_and_chain_from_fullchain�s
	�r�)r)@�__doc__r�ZloggingrRr�r�Zzope.componentrZOpenSSLrrZcryptographyrZcryptography.exceptionsrZcryptography.hazmat.backendsrZ,cryptography.hazmat.primitives.asymmetric.ecrrZ1cryptography.hazmat.primitives.asymmetric.paddingr	Z-cryptography.hazmat.primitives.asymmetric.rsar
Zacmerr-Zacme.magic_typingrZcertbotr
rrZcertbot.compatrZ	getLogger�__name__rr*r1r8r:rArrFrLrGrTrIrHrlr3rprqrrrtr?rurvrzr{rwr�r�r(r(r(r)�<module>sb

$#�

�