a
    2`/b,                     @   sf   d dl Z d dlZd dlZzd dlZW n ey:   dZY n0 d dlZd dlmZ dZG dd dZ	dS )    N)get_template)Securityc                   @   st   e Zd ZdZdZdddZedd Zdd	 Zdd
dZ	dd Z
dd Zdd Zdd Zdd Zdd Zdd ZdS )r   a4  Security configuration for a Dask cluster.

    Default values are loaded from Dask's configuration files, and can be
    overridden in the constructor.

    Parameters
    ----------
    require_encryption : bool, optional
        Whether TLS encryption is required for all connections.
    tls_ca_file : str, optional
        Path to a CA certificate file encoded in PEM format.
    tls_ciphers : str, optional
        An OpenSSL cipher string of allowed ciphers. If not provided, the
        system defaults will be used.
    tls_min_version : ssl.TLSVersion, optional
        The minimum TLS version to support. Defaults to TLS 1.2.
    tls_max_version : ssl.TLSVersion, optional
        The maximum TLS version to support. Defaults to the maximum version
        supported.
    tls_client_cert : str, optional
        Path to a certificate file for the client, encoded in PEM format.
    tls_client_key : str, optional
        Path to a key file for the client, encoded in PEM format.
        Alternatively, the key may be appended to the cert file, and this
        parameter be omitted.
    tls_scheduler_cert : str, optional
        Path to a certificate file for the scheduler, encoded in PEM format.
    tls_scheduler_key : str, optional
        Path to a key file for the scheduler, encoded in PEM format.
        Alternatively, the key may be appended to the cert file, and this
        parameter be omitted.
    tls_worker_cert : str, optional
        Path to a certificate file for a worker, encoded in PEM format.
    tls_worker_key : str, optional
        Path to a key file for a worker, encoded in PEM format.
        Alternatively, the key may be appended to the cert file, and this
        parameter be omitted.
    extra_conn_args : mapping, optional
        Mapping with keyword arguments to pass down to connections.
    )require_encryptiontls_ca_filetls_cipherstls_min_versiontls_max_versiontls_client_keytls_client_certtls_scheduler_keytls_scheduler_certtls_worker_keytls_worker_certextra_conn_argsNc                 K   s   t || j}|r$tdt| |di | _|d u rFtj	d}|d u rVt
|}|| _| |dd | |ddtjj | |dd	 | |d
d | |dd | |dd | |dd | |dd | |dd | |dd d S )NzUnknown parameters: %rr   z#distributed.comm.require-encryptionr   zdistributed.comm.tls.ciphersr   z distributed.comm.tls.min-versionr   z distributed.comm.tls.max-versionr   zdistributed.comm.tls.ca-filer	   zdistributed.comm.tls.client.keyr
   z distributed.comm.tls.client.certr   z"distributed.comm.tls.scheduler.keyr   z#distributed.comm.tls.scheduler.certr   zdistributed.comm.tls.worker.keyr   z distributed.comm.tls.worker.cert)set
difference	__slots__	TypeErrorsortedpopr   daskconfiggetboolr   
_set_field_set_tls_version_fieldssl
TLSVersionTLSv1_2)selfr   kwargsZextra r!   3lib/python3.9/site-packages/distributed/security.py__init__I   s@    zSecurity.__init__c                 K   sP  zDddl m} ddlm} ddlm}m} ddlm} ddl	m
} W n ty^   tdY n0 |jdd	| d
}|j|jj|jj| d }	|||jdg}
||dg}tj }| |
|
j|dd|  |! "|#|tj$dd %||& | }|'|jj }| f d||	||	||	|d|S )aJ  Create a new temporary Security object.

        This creates a new self-signed key/cert pair suitable for securing
        communication for all roles in a Dask cluster. These keys/certs exist
        only in memory, and are stored in this object.

        This method requires the library ``cryptography`` be installed.
        r   )x509)default_backend)hashesserialization)rsa)NameOIDz_Using `Security.temporary` requires `cryptography`, please install it using either pip or condai  i   )Zpublic_exponentZkey_sizeZbackend)encodingformatZencryption_algorithmzdask-internalF)Zcriticalim  )ZdaysT)r   r   r	   r
   r   r   r   r   )(Zcryptographyr$   Zcryptography.hazmat.backendsr%   Zcryptography.hazmat.primitivesr&   r'   Z)cryptography.hazmat.primitives.asymmetricr(   Zcryptography.x509.oidr)   ImportErrorZgenerate_private_keyZprivate_bytesZEncodingZPEMZPrivateFormatZPKCS8ZNoEncryptiondecodeNameZNameAttributeZCOMMON_NAMEZSubjectAlternativeNameZDNSNamedatetimeZutcnowZCertificateBuilderZsubject_nameZissuer_nameadd_extensionZ
public_keyZserial_numberZrandom_serial_numberZnot_valid_beforeZnot_valid_afterZ	timedeltasignZSHA256Zpublic_bytes)clsr    r$   r%   r&   r'   r(   r)   keyZkey_contentsZdask_internalZaltnamesZnowcertZcert_contentsr!   r!   r"   	temporaryk   sl    



	zSecurity.temporaryc                 C   s.   ||v r|| }nt j|}t| || d S )N)r   r   r   setattr)r   r    fieldconfig_namevalr!   r!   r"   r      s    
zSecurity._set_fieldc                 C   s   ||v rT|| }d t jjt jjh}||vrFt| d|dt| |d u r|}nN|t jjt jjd}tj|}||v r|| }nt| d|dt| t	| || d S )N=z# is not supported, expected one of )Ng333333?g?)
r   r   r   ZTLSv1_3
ValueErrorlistr   r   r   r6   )r   r    r7   r8   defaultr9   Zvalidr!   r!   r"   r      s(    
zSecurity._set_tls_version_fieldc                 C   s   t | j}|d i }|D ]^}t| |}|d urt|trNd|v rNd||< qt|trrdtj| d||< q|||< q|S )Nr   
zTemporary (In-memory)zLocal ())	r   r   removegetattr
isinstancestrospathabspath)r   keysattrkr9   r!   r!   r"   _attr_to_dict   s    





zSecurity._attr_to_dictc                 C   s(   |   }dddd | D  d S )Nz	Security(z, c                 s   s    | ]\}}| d | V  qdS )r:   Nr!   ).0r3   valuer!   r!   r"   	<genexpr>       z$Security.__repr__.<locals>.<genexpr>r?   )rJ   joinitems)r   rH   r!   r!   r"   __repr__   s    zSecurity.__repr__c                 C   s   t dj|  dS )Nzsecurity.html.j2)Zsecurity)r   ZrenderrJ   )r   r!   r!   r"   _repr_html_   s    zSecurity._repr_html_c                 C   s<   |dvrt d|| j| jt| d| t| d| dS )zR
        Return the TLS configuration for the given role, as a flat dict.
        >   Z	schedulerZclientZworkerzunknown role ztls_%s_certz
tls_%s_key)ca_fileciphersr4   r3   )r;   r   r   rA   )r   roler!   r!   r"   get_tls_config_for_role   s    z Security.get_tls_config_for_rolec              	   C   s  | dr| dr|d }|d  }}| d }}d|v rRtj||d}ntj||d}| jd urr| j|_| jd ur| j|_d|v }	|d uod|v }
|	s|
rnt }|	rt	j
|d}t|d}|| W d    n1 s0    Y  |
r@t	j
|d	}t|d}|| W d    n1 s60    Y  ||| W d    n1 sb0    Y  n||| tj|_d
|_| dr|| d |S d S )NrS   r4   r3   r>   )purposeZcadata)rW   Zcafilezdask.crtwzdask.pemFrT   )r   r   Zcreate_default_contextr   Zminimum_versionr   Zmaximum_versiontempfileZTemporaryDirectoryrD   rE   rO   openwriteZload_cert_chainZCERT_REQUIREDZverify_modeZcheck_hostnameZset_ciphers)r   tlsrW   caZ	cert_pathr4   Zkey_pathr3   ctxZcert_in_memoryZkey_in_memoryZtempdirfr!   r!   r"   _get_tls_context   s<    



(*.zSecurity._get_tls_contextc                 C   s&   |  |}| |tjj| j| jdS )zh
        Get the *connection_args* argument for a connect() call with
        the given *role*.
        )ssl_contextr   r   )rV   r`   r   PurposeZSERVER_AUTHr   r   r   rU   r\   r!   r!   r"   get_connection_args  s
    
zSecurity.get_connection_argsc                 C   s"   |  |}| |tjj| jdS )zg
        Get the *connection_args* argument for a listen() call with
        the given *role*.
        )ra   r   )rV   r`   r   rb   ZCLIENT_AUTHr   rc   r!   r!   r"   get_listen_args+  s    
zSecurity.get_listen_args)N)N)__name__
__module____qualname____doc__r   r#   classmethodr5   r   r   rJ   rQ   rR   rV   r`   rd   re   r!   r!   r!   r"   r      s   )
"
<
,r   )
r/   rD   rY   r   r,   r   Zdask.widgetsr   __all__r   r!   r!   r!   r"   <module>   s   
