HEX
Server: nginx/1.30.4
System: Linux d-twindigital-web-1.host-ed.eu 4.18.0-553.141.2.el8_10.x86_64 #1 SMP Wed Jul 8 10:28:18 EDT 2026 x86_64
User: u_twindigital_html (1009)
PHP: 8.3.30
Disabled: NONE
Upload Files
File: //lib/python3.6/site-packages/certbot/__pycache__/crypto_util.cpython-36.pyc
3

ߦ)_�K�@sdZddlZddlZddlZddlZddlmZddlmZddl	m
Z
ddlmZddlm
Z
ddlmZdd	lmZdd
lmZddlmZddlZddlZddlZddlmZdd
lmZddlmZddlm Z ddlm!Z!ddl"m#Z#ej$e%�Z&dKdd�Z'dd�Z(dd�Z)dd�Z*dd�Z+dd�Z,dd �Z-d!d"�Z.d#d$�Z/d%d&�Z0d'd(�Z1d)d*�Z2d+d,�Z3ej4fd-d.�Z5ej4fd/d0�Z6ej4fd1d2�Z7d3d4�Z8d5d6�Z9ej4fd7d8�Z:ej4fd9d:�Z;d;d<�Z<d=d>�Z=d?d@�Z>dAdB�Z?ej@dCejA�ZBdDdE�ZCdFdG�ZDdLdIdJ�ZEdS)Mz�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)�default_backend)�ECDSA)�EllipticCurvePublicKey)�PKCS1v15)�RSAPublicKey)�crypto)�SSL)�crypto_util)�IO)�errors)�
interfaces)�util)�os�key-certbot.pemcCs�yt|�}Wn4tk
r@}ztjddd�|�WYdd}~XnXtjjtj�}t	j
|d|j�t	jt
jj||�dd�\}}|�|j|�WdQRXtjd||�t	j||�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'�!/usr/lib/python3.6/crypto_util.py�
init_save_key%sr)cCs�tjjtj�}tj|j||jd�}t	j
|d|j�t	jt
jj|d�dd�\}}|�|j|�WdQRXtjd|�t	j||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)rrrrr�acme_crypto_utilZmake_csrr+r*rrrrrr r!r"rr#�CSR)�privkey�namesr r%Zcsr_pemZcsr_fZcsr_filenamer'r'r(�
init_save_csrIsr0cCsFytjtj|�}|j|j��Stjk
r@tjddd�dSXdS)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

    rT)rFN)r	�load_certificate_request�FILETYPE_PEM�verifyZ
get_pubkey�Errorrr#)�csr�reqr'r'r(�	valid_csrls
r7cCsPtjtj|�}tjtj|�}y
|j|�Stjk
rJtjddd�dSXdS)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

    rT)rFN)r	r1r2�load_privatekeyr3r4rr#)r5r.r6Zpkeyr'r'r(�csr_matches_pubkey�s


r9cCs�tj}tj}y|tj|�}WnLtjk
rhy|||�}Wn&tjk
rbtjdj|���YnXYnXt|�}tj||�}|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)r	r2r1�
FILETYPE_ASN1r4r
�format�"_get_names_from_loaded_cert_or_reqZdump_certificate_requestrr-)Zcsrfiler;ZPEM�loadr5ZdomainsZdata_pemr'r'r(�import_csr_file�sr@cCs0|dkst�tj�}|jtj|�tjtj|�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)�AssertionErrorr	ZPKeyZgenerate_keyZTYPE_RSAZdump_privatekeyr2)�bits�keyr'r'r(r�s	rcCs2ytjtj|�j�Sttjfk
r,dSXdS)z�Is valid RSA private key?

    :param str privkey: Private key file contents in PEM

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

    FN)r	r8r2Zcheck�	TypeErrorr4)r.r'r'r(�
valid_privkey�s
	rEcCs"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&)�renewable_certr'r'r(�verify_renewable_cert�s
rKc Cs�y�t|jd��}tj|j�t��}WdQRXt|jd��}tj|j�t��}WdQRX|j�}tj	��t
||j|j|j
�WdQRXWnJtttfk
r�}z(dj|j|�}tj|�tj|��WYdd}~XnXdS)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.
    �rbNz[verifying the signature of the cert located at {0} has failed.                 Details: {1})�open�
chain_pathr�load_pem_x509_certificate�readrrI�
public_key�warnings�catch_warnings�verify_signed_payload�	signatureZtbs_certificate_bytes�signature_hash_algorithm�IOErrorrrr=r�	exceptionr
r4)rJ�
chain_file�chain�	cert_file�certZpk�e�	error_strr'r'r(rF�s

rFcCs�tj��vtjd�t|t�rB|j|t�|�}|j|�|j�n8t|t	�rp|j|t
|��}|j|�|j�n
tjd��WdQRXdS)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�updater3rrr
r4)rQrUZpayloadrVrbr'r'r(rT�s







rTcCs|y,tjtj�}|j|�|j|�|j�WnJttjfk
rv}z(dj|||�}t	j
|�tj|��WYdd}~XnXdS)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)r
ZContextZ
SSLv23_METHODZuse_certificate_fileZuse_privatekey_fileZcheck_privatekeyrWr4r=rrXr
)rIr&�contextr]r^r'r'r(rHs


rHc	Cs�y�t|j��}|j�}WdQRXt|j��}|j�}WdQRXt|j��}|j�}WdQRX|||kr�d}|j|j�}tj|��Wnft	k
r�}z$dj|�}t
j|�tj|��WYdd}~Xn(tjk
r�}z
|�WYdd}~XnXdS)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})rMrNrPrIZfullchain_pathr=Zlineagenamer
r4rWrrX)	rJrYrZr[r\Zfullchain_fileZ	fullchainr^r]r'r'r(rG/s"

rGcCs~g}xTtjtjfD]D}ytj||�|fStjk
rT}z|j|�WYdd}~XqXqWtjdjdjdd�|D�����dS)z:Load PEM/DER certificate.

    :raises errors.Error:

    NzUnable to load: {0}�,css|]}t|�VqdS)N)�str)�.0rr'r'r(�	<genexpr>Ysz-pyopenssl_load_certificate.<locals>.<genexpr>)	r	r2r<�load_certificater4�appendr
r=r!)r;Zopenssl_errorsZ	file_typerr'r'r(�pyopenssl_load_certificateJs rkcCs6y
|||�Stjk
r0tjddd��YnXdS)NrT)r)r	r4rr)�cert_or_req_str�	load_func�typr'r'r(�_load_cert_or_req\s

rocCstjt|||��S)N)r,Z_pyopenssl_cert_or_req_sanro)rlrmrnr'r'r(�_get_sans_from_cert_or_reqesrpcCst|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

    )rpr	ri)r\rnr'r'r(�get_sans_from_certls
rqcCst|||�}t|�S)N)ror>)Zcert_or_reqrmrn�loaded_cert_or_reqr'r'r(�_get_names_from_cert_or_reqzsrscCs
tj|�S)N)r,Z _pyopenssl_cert_or_req_all_names)rrr'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

    )rsr	ri)r5rnr'r'r(�get_names_from_cert�s
rtcCstj||�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)rZZfiletyper'r'r(ru�s	rucCst|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)rIr'r'r(�	notBefore�s	rxcCst|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`

    )rvr	rwZget_notAfter)rIr'r'r(�notAfter�s	rycCs�t|��}tjtj|j��}WdQRX||�}|dd�d|dd�d|dd�d|dd�d	|dd
�d	|d
d�g}dj|�}tjr�|jd�}t	j
|�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`

    Nr��-���T�
�:���ascii)rMr	rir2rPr!�sixZPY3�decode�	pyrfc3339�parse)rI�method�frZ	timestampZreformatted_timestampZ
timestamp_strr'r'r(rv�s


rvc
Cs:tj�}t|d��}|j|j�jd��WdQRX|j�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�sha256rMrcrP�encodeZ	hexdigest)�filenamer�Zfile_dr'r'r(�	sha256sum�sr�s@-----BEGIN CERTIFICATE-----
?
.+?
?
-----END CERTIFICATE-----
?
cCsLtj|j��}t|�dkr$tjd
��dd�|D�}|ddj|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.

    �z/failed to parse fullchain into cert and chain: z!less than 2 certificates in chaincSs(g|] }tjtjtjtj|��j��qSr')r	Zdump_certificater2rir�)rgr\r'r'r(�
<listcomp>sz1cert_and_chain_from_fullchain.<locals>.<listcomp>rr�NzPfailed to parse fullchain into cert and chain: less than 2 certificates in chain)�CERT_PEM_REGEX�findallr��lenr
r4r!)Z
fullchain_pem�certsZcerts_normalizedr'r'r(�cert_and_chain_from_fullchain�sr�c
Cs.t|��}tjtj|j��}WdQRX|j�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
    N)rMr	rir2rPZget_serial_number)rIr�rr'r'r(�get_serial_from_certs	
r�FcCsrxX|D]P}dd�tj|j��D�}x2|D]*}|jjtjj�}|r(|dj|kr(|Sq(WqW|rjt	j
d|�|dS)a�Chooses the first certificate chain from fullchains which contains an
    Issuer Subject Common Name matching 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`
    cSsg|]}tj|t���qSr')rrOr)rgr\r'r'r(r�$sz*find_chain_with_issuer.<locals>.<listcomp>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�ZissuerZget_attributes_for_oidrZNameOIDZCOMMON_NAME�valuer�info)Z
fullchainsZ	issuer_cnZwarn_on_no_matchrZr�r\Zcert_issuer_cnr'r'r(�find_chain_with_issuers

r�)r)F)F�__doc__r�ZloggingrR�reZcryptographyrZcryptography.exceptionsrZcryptography.hazmat.backendsrZ,cryptography.hazmat.primitives.asymmetric.ecrrZ1cryptography.hazmat.primitives.asymmetric.paddingrZ-cryptography.hazmat.primitives.asymmetric.rsarZOpenSSLr	r
r�r�Zzope.componentrZacmerr,Zacme.magic_typingrZcertbotr
rrZcertbot.compatrZ	getLogger�__name__rr)r0r7r9r@rrErKrFrTrHrGrkr2rorprqrsr>rtrurxryrvr��compile�DOTALLr�r�r�r�r'r'r'r(�<module>sj

$#