HEX
Server: Apache/2.4.65 (Debian)
System: Linux kubikelcreative 5.10.0-35-amd64 #1 SMP Debian 5.10.237-1 (2025-05-19) x86_64
User: www-data (33)
PHP: 8.4.13
Disabled: NONE
Upload Files
File: //usr/lib/python3/dist-packages/certbot/__pycache__/crypto_util.cpython-39.pyc
a

�`�R�@s$dZddlZddlZddlZddlZddlmZddlmZm	Z	ddl
mZddlm
Z
ddlmZmZddlmZdd	lmZdd
lmZmZmZddlmZddlmZddlZddlZddlZdd
l m!Z"ddl#m$Z$ddl%m&Z&ddl%m'Z'ddl%m(Z(ddl)m*Z*e�+e,�Z-dOdd�Z.dd�Z/dd�Z0dd�Z1dd�Z2dPd!d"�Z3d#d$�Z4d%d&�Z5d'd(�Z6d)d*�Z7d+d,�Z8d-d.�Z9d/d0�Z:ej;fd1d2�Z<ej;fd3d4�Z=ej;fd5d6�Z>d7d8�Z?d9d:�Z@ej;fd;d<�ZAej;fd=d>�ZBd?d@�ZCdAdB�ZDdCdD�ZEdEdF�ZFe�GdGejH�ZIdHdI�ZJdJdK�ZKdQdMdN�ZLdS)Rz�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)�x509)�InvalidSignature�UnsupportedAlgorithm)�default_backend)�ec)�ECDSA�EllipticCurvePublicKey)�PKCS1v15)�RSAPublicKey)�Encoding�NoEncryption�
PrivateFormat)�crypto)�SSL)�crypto_util)�IO)�errors)�
interfaces)�util)�os�rsa�	secp256r1�key-certbot.pemc

Cs�zt||pd|d�}Wn6tyL}ztjddd�|�WYd}~n
d}~00tj�tj�}t	�
|d|j�t	�t
j�||�dd	�\}}	|�|�|�Wd�n1s�0Y|d
kr�t�d||	�nt�d||	�t	�|	|�S)
aiInitializes 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: 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

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

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

    r)�bits�elliptic_curve�key_type�T��exc_infoNi�i��wbrz Generating RSA key (%d bits): %sz"Generating ECDSA 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_dirrrZkeynameZkey_pem�err�configZkey_f�key_path�r2�5/usr/lib/python3/dist-packages/certbot/crypto_util.py�
init_save_key's$
�
�(r4cCs�tj�tj�}tj|j||jd�}t	�
|d|j�t	�t
j�|d�dd�\}}|�|�|�Wd�n1sr0Yt�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�rNzCreating CSR: %s�pem)r$r%r&rr'�acme_crypto_utilZmake_csrr6r5rr(r)r*rr+r,r-r"r.�CSR)�privkey�namesr+r0Zcsr_pemZcsr_fZcsr_filenamer2r2r3�
init_save_csrTs
��(r;cCsHzt�tj|�}|�|���WStjyBtjddd�YdS0dS)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�Errorr"r.)�csr�reqr2r2r3�	valid_csrws�rBcCsRt�tj|�}t�tj|�}z|�|�WStjyLtjddd�YdS0dS)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)rr<r=�load_privatekeyr>r?r"r.)r@r9rAZpkeyr2r2r3�csr_matches_pubkey�s
�rDcCs�tj}tj}z|tj|�}WnHtjydz|||�}Wn$tjy^t�d�|���Yn0Yn0t|�}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}r6)�file�dataZform)rr=r<�
FILETYPE_ASN1r?r�format�"_get_names_from_loaded_cert_or_reqZdump_certificate_requestrr8)ZcsrfilerF�PEM�loadr@ZdomainsZdata_pemr2r2r3�import_csr_file�srL�c
Cs&|dkr8|dkr t�d�|���t��}|�tj|�n�|dk�rzD|��}|dvrttj	t
t|��d��t�d�}nt�d�|���WnZty�t�d�|���Yn:t
y�}z"t�|t�t|����WYd}~n
d}~00|jtjtjt�d	�}t�tj|�}nt�d
�|���t�tj|�S)aDGenerate PEM encoded RSA|EC key.

    :param int bits: Number of bits if key_type=rsa. At least 1024 for RSA.

    :param str ec_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
    rrMzUnsupported RSA key length: {}Zecdsa)Z	SECP256R1Z	SECP384R1Z	SECP521R1N)ZcurveZbackendzUnsupported elliptic curve: {})�encodingrHZencryption_algorithmz0Invalid key_type specified: {}.  Use [rsa|ecdsa])rr?rHrZPKeyZgenerate_keyZTYPE_RSA�upperrZgenerate_private_key�getattrr�	TypeErrorr�sixZ
raise_from�strZ
private_bytesrrJr
ZTraditionalOpenSSLrrCr=Zdump_privatekey)rrr�key�nameZ_key�eZ_key_pemr2r2r3r �s4
�,�r c	Cs4zt�tj|���WSttjfy.YdS0dS)z�Is valid RSA private key?

    :param str privkey: Private key file contents in PEM

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

    FN)rrCr=ZcheckrQr?)r9r2r2r3�
valid_privkey�s	�
rWcCs"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_pathr1)�renewable_certr2r2r3�verify_renewable_cert�s
r]c
Csz�t|jd��"}t�|��t��}Wd�n1s60Yt|jd��"}t�|��t��}Wd�n1st0Y|��}t�	��$t
||j|j|j
�Wd�n1s�0YWnNtttf�y}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�readrr[�
public_key�warnings�catch_warnings�verify_signed_payload�	signatureZtbs_certificate_bytes�signature_hash_algorithm�IOErrorr!rrHr"�	exceptionrr?)r\�
chain_file�chain�	cert_file�certZpkrV�	error_strr2r2r3rXs 00
�&�
rXcCs�t����t�d�t|t�rB|�|t�|�}|�|�|��n8t|t	�rp|�|t
|��}|�|�|��n
t�d��Wd�n1s�0YdS)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)
rdre�simplefilter�
isinstancer
�verifierr	�updater>rrrr?)rcrgZpayloadrhrsr2r2r3rf s


�


�

rfc
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_privatekeyrir?rHr"rjr)r[r1�contextrVror2r2r3rZ?s

�
rZc	
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})r_r`rbr[Zfullchain_pathrHZlineagenamerr?rir"rj)	r\rkrlrmrnZfullchain_fileZ	fullchainrorVr2r2r3rYUs"&&&

rYcCs�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)rS)�.0r#r2r2r3�	<genexpr>~sz-pyopenssl_load_certificate.<locals>.<genexpr>)	rr=rG�load_certificater?�appendrrHr,)rFZopenssl_errorsZ	file_typer#r2r2r3�pyopenssl_load_certificateps"�r|cCs6z|||�WStjy0tjddd��Yn0dS)NrTr)rr?r"r#�Zcert_or_req_str�	load_func�typr2r2r3�_load_cert_or_req�s
r�cCst�t|||��Srw)r7Z_pyopenssl_cert_or_req_sanr�r}r2r2r3�_get_sans_from_cert_or_req�s�r�cCst|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

    )r�rrz)rnrr2r2r3�get_sans_from_cert�s
�r�cCst|||�}t|�Srw)r�rI)Zcert_or_reqr~r�loaded_cert_or_reqr2r2r3�_get_names_from_cert_or_req�sr�cCs
t�|�Srw)r7Z _pyopenssl_cert_or_req_all_names)r�r2r2r3rI�srIcCst|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

    )r�rrz)r@rr2r2r3�get_names_from_cert�s
�r�cCst�||�S)z�Dump certificate chain into a bundle.

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

    )r7�dump_pyopenssl_chain)rlZfiletyper2r2r3r��s	r�cCst|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�r[r2r2r3�	notBefore�s	r�cCst|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`

    )r�rr�Zget_notAfterr�r2r2r3�notAfter�s	r�c
Cs�t|d��"}t�tj|���}Wd�n1s20Y||�}|dd�d|dd�d|dd�d|dd	�d
|d	d�d
|dd�g}d�|�}tjr�|�d
�}n|}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^Nr��-���T�
�:���ascii)r_rrzr=rbr,rRZPY3�decode�	pyrfc3339�parse)r[�method�frZ	timestampZreformatted_timestampZtimestamp_bytesZ
timestamp_strr2r2r3r��s0�
r�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�sha256r_rtrb�encodeZ	hexdigest)�filenamer�Zfile_dr2r2r3�	sha256sum�s2r�s@-----BEGIN CERTIFICATE-----
?
.+?
?
-----END CERTIFICATE-----
?
cCsLt�|���}t|�dkr$t�d��dd�|D�}|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 chainc	Ss(g|] }t�tjt�tj|�����qSr2)rZdump_certificater=rzr�)rxrnr2r2r3�
<listcomp>*s��z1cert_and_chain_from_fullchain.<locals>.<listcomp>rr�N)�CERT_PEM_REGEX�findallr��lenrr?r,)Z
fullchain_pem�certsZcerts_normalizedr2r2r3�cert_and_chain_from_fullchains
�r�cCsDt|d��"}t�tj|���}Wd�n1s20Y|��S)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
    r^N)r_rrzr=rbZget_serial_number)r[r�rr2r2r3�get_serial_from_cert1s	0r�FcCsl|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�r�rrarZissuerZget_attributes_for_oidZNameOIDZCOMMON_NAME�valuer"�info)Z
fullchainsZ	issuer_cnZwarn_on_no_matchrlr�Ztop_certZ
top_issuer_cnr2r2r3�find_chain_with_issuer?s

�r�)rrr)rMrN)F)M�__doc__r�Zloggingrd�reZcryptographyrZcryptography.exceptionsrrZcryptography.hazmat.backendsrZ)cryptography.hazmat.primitives.asymmetricrZ,cryptography.hazmat.primitives.asymmetric.ecrrZ1cryptography.hazmat.primitives.asymmetric.paddingr	Z-cryptography.hazmat.primitives.asymmetric.rsar
Z,cryptography.hazmat.primitives.serializationrrr
ZOpenSSLrrr�rRZzope.componentr$Zacmerr7Zacme.magic_typingrZcertbotrrrZcertbot.compatrZ	getLogger�__name__r"r4r;rBrDrLr rWr]rXrfrZrYr|r=r�r�r�r�rIr�r�r�r�r�r��compile�DOTALLr�r�r�r�r2r2r2r3�<module>st
�
-#
*�

�
�