CasperSecurity

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

o

6��aT_�@s�dZddlZddlZddlZddlmZddlmZddlZddlm	Z	ddl
mZddl
mZddl
mZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlZddl Z!ddl"m#Z$ddl%m&Z&ddl%m'Z'ddl%m(Z(ddl)m*Z*e�+e,�Z-			dhde.de/de/de/d e/d!e0d"e(j1fd#d$�Z2		did%d&�Z3	djd(e(j1d)ee/d*e/d+e0d!e0d"e(j4fd,d-�Z5d.d/�Z6d0d1�Z7d2d3�Z8d4d5�Z9dkd7d8�Z:d9d:�Z;d;d<�Z<d=d>�Z=d?d@�Z>dAdB�Z?dCdD�Z@dEdF�ZAejBfdGdH�ZCejBfdIdJ�ZDejBfdKdL�ZEdMdN�ZFdOdP�ZGejBfdQdR�ZHejBfdSe/dTe.d"ee/fdUdV�ZIejBfdWdX�ZJdYdZ�ZKd[d\�ZLd]d^�ZMd_d`�ZNe�OdaejP�ZQdbdc�ZRddde�ZSdldfdg�ZTdS)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)�List)�Set)�x509)�InvalidSignature)�UnsupportedAlgorithm)�default_backend)�ec)�ECDSA)�EllipticCurvePublicKey)�PKCS1v15)�RSAPublicKey)�Encoding)�NoEncryption)�
PrivateFormat)�crypto)�SSL)�crypto_util)�errors)�
interfaces)�util)�os�rsa�	secp256r1�key-certbot.pemT�key_size�key_dir�key_type�elliptic_curve�keyname�strict_permissions�returnc

Cs�zt||pd|d�}Wnty(}ztjddd�t�dt|��|�d}~wwt�|d|�t�t	j
�||�d	d
�\}}	|�
|�|�Wd�n1sPwY|dkrat�d||	�nt�d
||	�t�
|	|�S)aInitializes 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
    :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)�bitsrr�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)
rrrrrr�key_pem�err�key_f�key_path�r6�5/usr/lib/python3/dist-packages/certbot/crypto_util.py�generate_key*s*

�����r8cCs0t�dt�tj�tj�}t||||||j	d�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.

    .. deprecated:: 1.16.0
       Use :func:`generate_key` instead.

    :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.

    zecertbot.crypto_util.init_save_key is deprecated, please use certbot.crypto_util.generate_key instead.)rrrr)
�warnings�warn�DeprecationWarning�zope�	component�
getUtilityr�IConfigr8r)rrrrr�configr6r6r7�
init_save_keyZs�
�rAF�privkey�namesr.�must_staplecCs�tj|j||d�}t�|d|�t�tj�|d�dd�\}}|�
|�	|�Wd�n1s0wYt
�d|�t�||d�S)	a:Initialize 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.
    :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`

    )rDi�zcsr-certbot.pemi�r%NzCreating CSR: %s�pem)
�acme_crypto_util�make_csrrErr,r-rr.r/r0r(r)�CSR)rBrCr.rDr�csr_pem�csr_f�csr_filenamer6r6r7�generate_csr{s���rLcCs0t�dt�tj�tj�}t||||j	|j
d�S)awInitialize a CSR with the given private key.

    .. deprecated:: 1.16.0
       Use :func:`generate_csr` instead.

    :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`

    zecertbot.crypto_util.init_save_csr is deprecated, please use certbot.crypto_util.generate_csr instead.)rDr)r9r:r;r<r=r>rr?rLrDr)rBrCr.r@r6r6r7�
init_save_csr�s��rMcCsDzt�tj|�}|�|���WStjy!tjddd�YdSw)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

    r"Tr#F)r�load_certificate_request�FILETYPE_PEM�verify�
get_pubkey�Errorr(r))�csr�reqr6r6r7�	valid_csr�s��rUcCsNt�tj|�}t�tj|�}z|�|�WStjy&tjddd�YdSw)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

    r"Tr#F)rrNrO�load_privatekeyrPrRr(r))rSrBrT�pkeyr6r6r7�csr_matches_pubkey�s
��rXcCs�tj}tj}z|tj|�}Wn"tjy0z|||�}Wntjy-t�d�|���wYnwt|�}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}rE)�file�data�form)rrOrN�
FILETYPE_ASN1rRr�format�"_get_names_from_loaded_cert_or_req�dump_certificate_requestrrH)�csrfilerZ�PEM�loadrS�domains�data_pemr6r6r7�import_csr_file�s���re�c
Cs|dkr|dkrt�d�|���t��}|�tj|�nd|dkrxz"|��}|dvr9tj	t
t|��d��t�d�}nt�d�|���Wn"tyQt�d�|���t
yd}z|t�t|���d}~ww|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
    rrfzUnsupported RSA key length: {}�ecdsa)�	SECP256R1�	SECP384R1�	SECP521R1N)�curve�backendzUnsupported elliptic curve: {})�encodingr]�encryption_algorithmz0Invalid key_type specified: {}.  Use [rsa|ecdsa])rrRr]r�PKeyr8�TYPE_RSA�upperr�generate_private_key�getattrr�	TypeErrorrr+�
private_bytesr
rar�TraditionalOpenSSLrrVrO�dump_privatekey)r!rr�key�name�_key�e�_key_pemr6r6r7r&�s:�����r&c	Cs0z
t�tj|���WSttjfyYdSw)z�Is valid RSA private key?

    :param str privkey: Private key file contents in PEM

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

    F)rrVrO�checkrtrR)rBr6r6r7�
valid_privkey,s	���r~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_pathr5)�renewable_certr6r6r7�verify_renewable_cert<s
r�c
Cszet|jd��}t�|��t��}Wd�n1swYt|jd��}t�|��t��}Wd�n1s:wY|��}t�	��t
||j|j|j
�Wd�WdS1s^wYWdStttfy�}zd�|j|�}t�|�t�|��d}~ww)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_keyr9�catch_warnings�verify_signed_payload�	signature�tbs_certificate_bytes�signature_hash_algorithm�IOErrorr'rr]r(�	exceptionrrR)r��
chain_file�chain�	cert_file�cert�pkr{�	error_strr6r6r7rNs*��
�&�
�

��rcCs�t���It�d�t|t�r!|�|t�|�}|�|�|��nt|t	�r8|�|t
|��}|�|�|��n
t�d��Wd�dSWd�dS1sPwYdS)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)
r9r��simplefilter�
isinstancer�verifierr�updaterPr
r	rrR)r�r��payloadr�r�r6r6r7r�fs&


�


�


��
"�r�c
Cspzt�tj�}|�|�|�|�|��WdSttjfy7}zd�|||�}t	�
|�t�|��d}~ww)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)r�Context�
SSLv23_METHOD�use_certificate_file�use_privatekey_file�check_privatekeyr�rRr]r(r�r)r�r5�contextr{r�r6r6r7r��s

��

��r�c	
Cszat|j��}|��}Wd�n1swYt|j��}|��}Wd�n1s.wYt|j��}|��}Wd�n1sGwY|||kr_d}|�|j�}t�|��WdSt	y|}zd�|�}t
�|�t�|��d}~wtjy�}z|�d}~ww)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�r�r��fullchain_pathr]�lineagenamerrRr�r(r�)	r�r�r�r�r��fullchain_file�	fullchainr�r{r6r6r7r��s0
�
�
�
�


���r�cCs|g}tjtjfD]%}zt�||�|fWStjy-}z|�|�WYd}~qd}~wwt�d�d�dd�|D�����)z:Load PEM/DER certificate.

    :raises errors.Error:

    NzUnable to load: {0}�,css�|]}t|�VqdS�N)r+)�.0r*r6r6r7�	<genexpr>�s�
�z-pyopenssl_load_certificate.<locals>.<genexpr>)	rrOr\�load_certificaterR�appendrr]r/)rZ�openssl_errors�	file_typer*r6r6r7�pyopenssl_load_certificate�s���r�c
CsHz|||�WStjy#}ztjddd�t�dt|���d}~ww)Nr"Tr#z6Encountered error while loading certificate or csr: %s)rrRr(r)r*r+)�cert_or_req_str�	load_func�typr3r6r6r7�_load_cert_or_req�s��r�cCst�t|||��Sr�)rF�_pyopenssl_cert_or_req_sanr�)r�r�r�r6r6r7�_get_sans_from_cert_or_req�s�r�cC�t|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�rr�)r�r�r6r6r7�get_sans_from_cert��
�r�cCst|||�}t|�Sr�)r�r^)�cert_or_reqr�r��loaded_cert_or_reqr6r6r7�_get_names_from_cert_or_req�sr�cCs
t�|�Sr�)rF� _pyopenssl_cert_or_req_all_names)r�r6r6r7r^�s
r^cCr�)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�rr��rSr�r6r6r7�get_names_from_cert�r�r�rSr�cCr�)z�Get a list of domains from a CSR, including the CN if it is set.

    :param str cert: CSR (encoded).
    :param typ: `crypto.FILETYPE_PEM` or `crypto.FILETYPE_ASN1`
    :returns: A list of domain names.
    :rtype: list

    )r�rrNr�r6r6r7�get_names_from_req��	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`).

    )rF�dump_pyopenssl_chain)r��filetyper6r6r7r�
s	r�cC�t|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�X509�
get_notBefore�r�r6r6r7�	notBeforer�r�cCr�)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��get_notAfterr�r6r6r7�notAfter"r�r�c
Cs�t|d��}t�tj|���}Wd�n1swY||�}|dd�d|dd�d|dd�d|dd	�d
|d	d�d
|dd�g}d�|�}|�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�Nr��-���T�
�:���ascii)	r�rr�rOr�r/�decode�	pyrfc3339�parse)r��method�fr�	timestamp�reformatted_timestamp�timestamp_bytes�
timestamp_strr6r6r7r�.s��


r�cCsTt��}t|d��}|�|���d��Wd�|��S1s!wY|��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�r�r��encode�	hexdigest)�filenamer��file_dr6r6r7�	sha256sumGs
��r�s@-----BEGIN CERTIFICATE-----
?
.+?
?
-----END CERTIFICATE-----
?
cCsLt�|���}t|�dkrt�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|�����qSr6)r�dump_certificaterOr�r�)r�r�r6r6r7�
<listcomp>ws���z1cert_and_chain_from_fullchain.<locals>.<listcomp>rr"�N)�CERT_PEM_REGEX�findallr��lenrrRr/)�
fullchain_pem�certs�certs_normalizedr6r6r7�cert_and_chain_from_fullchainbs
�r�cCsJt|d��}t�tj|���}Wd�|��S1swY|��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�rr�rOr��get_serial_number)r�r�rr6r6r7�get_serial_from_cert~s	
��r�cCsl|D]'}t�|���}t�|dt��}|j�tjj	�}|r)|dj
|kr)|Sq|r2t�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�rr�r�issuer�get_attributes_for_oid�NameOID�COMMON_NAME�valuer(�warning)�
fullchains�	issuer_cn�warn_on_no_matchr�r��top_cert�
top_issuer_cnr6r6r7�find_chain_with_issuer�s
��r)rrrT)rrr)FT)rfrN)F)U�__doc__r��logging�re�typingrrr9�cryptographyr�cryptography.exceptionsrr�cryptography.hazmat.backendsr�)cryptography.hazmat.primitives.asymmetricr�,cryptography.hazmat.primitives.asymmetric.ecr	r
�1cryptography.hazmat.primitives.asymmetric.paddingr�-cryptography.hazmat.primitives.asymmetric.rsar�,cryptography.hazmat.primitives.serializationr
rr�OpenSSLrrr��zope.componentr<�acmerrF�certbotrrr�certbot.compatr�	getLogger�__name__r(�intr+�boolr1r8rArHrLrMrUrXrer&r~r�rr�r�r�r�rOr�r�r�r�r^r�r�r�r�r�r�r��compile�DOTALLr�r�r�rr6r6r6r7�<module>s�
����
�0
�"���
�
.
�
� �	
Hacker Blog, Shell İndir, Sql İnjection, XSS Attacks, LFI Attacks, Social Hacking, Exploit Bot, Proxy Tools, Web Shell, PHP Shell, Alfa Shell İndir, Hacking Training Set, DDoS Script, Denial Of Service, Botnet, RFI Attacks, Encryption
Telegram @BIBIL_0DAY