B
    b
,cö?  ã               @   s†   d Z ddlZddlZddlmZmZmZmZmZm	Z	m
Z
 ddlZddlmZ ddlmZ ddlmZ dZd	ZG d
d„ dƒZddgZdS )z*Base implementation of 0MQ authentication.é    N)ÚAnyÚDictÚListÚOptionalÚSetÚTupleÚUnion)Ú_check_version)Úz85é   )Úload_certificatesÚ*s   1.0c               @   sÖ  e Zd ZU dZded< eed< eed< eeef ed< ded< e	e ed	< e	e ed
< eeeeef f ed< eeee
ef f ed< eed< d=ed eedœdd„Zddœdd„Zddœdd„Zeddœdd„Zeddœdd„Zd>eeeef ddœdd „Zd?eeeejf dd"œd#d$„Zd@eedd%œd&d'„Ze
ed(œd)d*„ZdAeee dd"œd+d,„Zee
 d-œd.d/„Zeeeeee
f d0œd1d2„Zee
eee
f d3œd4d5„Zee
eee
f d6œd7d8„ZdBe
e
e
edd:œd;d<„ZdS )CÚAuthenticatoraö  Implementation of ZAP authentication for zmq connections.

    This authenticator class does not register with an event loop. As a result,
    you will need to manually call `handle_zap_message`::

        auth = zmq.Authenticator()
        auth.allow("127.0.0.1")
        auth.start()
        while True:
            auth.handle_zap_msg(auth.zap_socket.recv_multipart())

    Alternatively, you can register `auth.zap_socket` with a poller.

    Since many users will want to run ZAP in a way that does not block the
    main thread, other authentication classes (such as :mod:`zmq.auth.thread`)
    are provided.

    Note:

    - libzmq provides four levels of security: default NULL (which the Authenticator does
      not see), and authenticated NULL, PLAIN, CURVE, and GSSAPI, which the Authenticator can see.
    - until you add policies, all incoming NULL connections are allowed.
      (classic ZeroMQ behavior), and all PLAIN and CURVE connections are denied.
    - GSSAPI requires no configuration.
    zzmq.ContextÚcontextÚencodingÚ	allow_anyÚcredentials_providersz
zmq.SocketÚ
zap_socketÚ	whitelistÚ	blacklistÚ	passwordsÚcertsÚlogNúutf-8)r   r   r   c             C   sb   t ddƒ |ptj ¡ | _|| _d| _i | _d | _t	ƒ | _
t	ƒ | _i | _i | _|pZt d¡| _d S )N)é   r   ZsecurityFzzmq.auth)r	   ÚzmqZContextÚinstancer   r   r   r   r   Úsetr   r   r   r   ÚloggingZ	getLoggerr   )Úselfr   r   r   © r    ú,lib/python3.7/site-packages/zmq/auth/base.pyÚ__init__:   s    
zAuthenticator.__init__)Úreturnc             C   s4   | j  tj¡| _d| j_| j d¡ | j d¡ dS )zCreate and bind the ZAP socketr   zinproc://zeromq.zap.01ZStartingN)	r   Zsocketr   ZREPr   ZlingerZbindr   Údebug)r   r    r    r!   ÚstartP   s    zAuthenticator.startc             C   s   | j r| j  ¡  d| _ dS )zClose the ZAP socketN)r   Úclose)r   r    r    r!   ÚstopW   s    
zAuthenticator.stop)Ú	addressesr#   c             G   s2   | j rtdƒ‚| j dd |¡¡ | j |¡ dS )aI  Allow (whitelist) IP address(es).

        Connections from addresses not in the whitelist will be rejected.

        - For NULL, all clients from this address will be accepted.
        - For real auth setups, they will be allowed to continue with authentication.

        whitelist is mutually exclusive with blacklist.
        z-Only use a whitelist or a blacklist, not bothzAllowing %sú,N)r   Ú
ValueErrorr   r$   Újoinr   Úupdate)r   r(   r    r    r!   Úallow]   s    
zAuthenticator.allowc             G   s2   | j rtdƒ‚| j dd |¡¡ | j |¡ dS )z»Deny (blacklist) IP address(es).

        Addresses not in the blacklist will be allowed to continue with authentication.

        Blacklist is mutually exclusive with whitelist.
        z-Only use a whitelist or a blacklist, not bothz
Denying %sr)   N)r   r*   r   r$   r+   r   r,   )r   r(   r    r    r!   Údenyl   s    zAuthenticator.denyr   )Údomainr   r#   c             C   s    |r|| j |< | j d|¡ dS )zõConfigure PLAIN authentication for a given domain.

        PLAIN authentication uses a plain-text password file.
        To cover all domains, use "*".
        You can modify the password file at any time; it is reloaded automatically.
        zConfigure plain: %sN)r   r   r$   )r   r/   r   r    r    r!   Úconfigure_plainx   s    	
zAuthenticator.configure_plainÚ.)r/   Úlocationr#   c          
   C   sp   | j  d||¡ |tkr d| _nLd| _yt|ƒ| j|< W n2 tk
rj } z| j  d||¡ W dd}~X Y nX dS )a	  Configure CURVE authentication for a given domain.

        CURVE authentication uses a directory that holds all public client certificates,
        i.e. their public keys.

        To cover all domains, use "*".

        You can add and remove certificates in that directory at any time. configure_curve must be called
        every time certificates are added or removed, in order to update the Authenticator's state

        To allow all client keys without checking, specify CURVE_ALLOW_ANY for the location.
        zConfigure curve: %s[%s]TFz&Failed to load CURVE certs from %s: %sN)r   r$   ÚCURVE_ALLOW_ANYr   r   r   Ú	ExceptionÚerror)r   r/   r2   Úer    r    r!   Úconfigure_curve…   s    zAuthenticator.configure_curve)r/   Úcredentials_providerr#   c             C   s,   d| _ |dk	r|| j|< n| j d|¡ dS )a  Configure CURVE authentication for a given domain.

        CURVE authentication using a callback function validating
        the client public key according to a custom mechanism, e.g. checking the
        key against records in a db. credentials_provider is an object of a class which
        implements a callback method accepting two parameters (domain and key), e.g.::

            class CredentialsProvider(object):

                def __init__(self):
                    ...e.g. db connection

                def callback(self, domain, key):
                    valid = ...lookup key and/or domain in db
                    if valid:
                        logging.info('Authorizing: {0}, {1}'.format(domain, key))
                        return True
                    else:
                        logging.warning('NOT Authorizing: {0}, {1}'.format(domain, key))
                        return False

        To cover all domains, use "*".

        To allow all client keys without checking, specify CURVE_ALLOW_ANY for the location.
        FNz0None credentials_provider provided for domain:%s)r   r   r   r5   )r   r/   r8   r    r    r!   Úconfigure_curve_callback    s    z&Authenticator.configure_curve_callback)Úclient_public_keyr#   c             C   s   t  |¡ d¡S )að  Return the User-Id corresponding to a CURVE client's public key

        Default implementation uses the z85-encoding of the public key.

        Override to define a custom mapping of public key : user-id

        This is only called on successful authentication.

        Parameters
        ----------
        client_public_key: bytes
            The client public key used for the given message

        Returns
        -------
        user_id: unicode
            The user ID as text
        Úascii)r
   ÚencodeÚdecode)r   r:   r    r    r!   Úcurve_user_idÄ   s    zAuthenticator.curve_user_idc             C   s   dS )z~Configure GSSAPI authentication

        Currently this is a no-op because there is nothing to configure with GSSAPI.
        Nr    )r   r/   r2   r    r    r!   Úconfigure_gssapiÙ   s    zAuthenticator.configure_gssapi)Úmsgc          	      sÈ  t |ƒdk rJˆ j d|¡ t |ƒdk r4ˆ j d¡ nˆ  |d dd¡ dS |dd… \}}}}}}|dd… }| ˆ jd	¡}| ˆ jd	¡}|tkr²ˆ j d
|¡ ˆ  |dd¡ dS ˆ j d||||||¡ d}	d}
d}ˆ jr|ˆ jkrüd}	ˆ j d|¡ nd}
d}ˆ j d|¡ n>ˆ j	rR|ˆ j	kr@d}
d}ˆ j d|¡ nd}	ˆ j d|¡ d}|
sž|dkr€|	s€ˆ j d¡ d}	n|dkrât |ƒdkr¸ˆ j d|¡ ˆ  |dd¡ dS ‡ fdd„|D ƒ\}}ˆ  
|||¡\}	}n¼|dkrDt |ƒdkrˆ j d|¡ ˆ  |dd¡ dS |d  }ˆ  ||¡\}	}|	ržˆ  |¡}nZ|d!kržt |ƒdkr|ˆ j d"|¡ ˆ  |dd¡ dS |d  }| d#¡}ˆ  ||¡\}	}|	r¶ˆ  |d$d%|¡ nˆ  |d|¡ dS )&zPerform ZAP authenticationé   z*Invalid ZAP message, not enough frames: %ré   zNot enough information to replyr   s   400s   Not enough framesNÚreplacezInvalid ZAP version: %rs   Invalid versionzQversion: %r, request_id: %r, domain: %r, address: %r, identity: %r, mechanism: %rFs	   NO ACCESSTzPASSED (whitelist) address=%ss   Address not in whitelistz$DENIED (not in whitelist) address=%ss   Address is blacklistedzDENIED (blacklist) address=%sz$PASSED (not in blacklist) address=%sÚ	anonymouss   NULLzALLOWED (NULL)s   PLAINzInvalid PLAIN credentials: %rs   Invalid credentialsc             3   s   | ]}|  ˆ jd ¡V  qdS )rC   N)r=   r   )Ú.0Úc)r   r    r!   ú	<genexpr>(  s    z3Authenticator.handle_zap_message.<locals>.<genexpr>s   CURVEzInvalid CURVE credentials: %rr   s   GSSAPIzInvalid GSSAPI credentials: %rÚutf8s   200s   OK)Úlenr   r5   Ú_send_zap_replyr=   r   ÚVERSIONr$   r   r   Ú_authenticate_plainÚ_authenticate_curver>   Ú_authenticate_gssapi)r   r@   ÚversionÚ
request_idr/   ZaddressZidentityZ	mechanismZcredentialsÚallowedZdeniedÚreasonÚusernameÚpasswordÚkeyÚ	principalr    )r   r!   Úhandle_zap_messageá   sŽ    




z Authenticator.handle_zap_message)r/   rS   rT   r#   c             C   s˜   d}d}| j r~|sd}|| j krR|| j | krL|| j | | krFd}qPd}qVd}nd}|rn| j d|||¡ q| j d	|¡ nd
}| j d|¡ ||fS )zPLAIN ZAP authenticationFó    r   Ts   Invalid passwords   Invalid usernames   Invalid domainz1ALLOWED (PLAIN) domain=%s username=%s password=%sz	DENIED %ss   No passwords definedzDENIED (PLAIN) %s)r   r   r$   )r   r/   rS   rT   rQ   rR   r    r    r!   rL   F  s,    
z!Authenticator._authenticate_plain)r/   Ú
client_keyr#   c             C   sö   d}d}| j r$d}d}| j d¡ nÊ| ji kr|s6d}|| jkrŠt |¡}| j|  ||¡rfd}d}nd}|rrdnd	}| j d
|||¡ qîd}n^|s˜d}|| jkrêt |¡}| j|  |¡rÆd}d}nd}|rÒdnd	}| j d|||¡ nd}||fS )zCURVE ZAP authenticationFrX   Ts   OKz ALLOWED (CURVE allow any client)r   s   Unknown keyZALLOWEDZDENIEDz0%s (CURVE auth_callback) domain=%s client_key=%ss   Unknown domainz"%s (CURVE) domain=%s client_key=%s)	r   r   r$   r   r
   r<   Úcallbackr   Úget)r   r/   rY   rQ   rR   Zz85_client_keyZstatusr    r    r!   rM   l  sL    




z!Authenticator._authenticate_curve)r/   rV   r#   c             C   s   | j  d||¡ dS )zPNothing to do for GSSAPI, which has already been handled by an external service.z'ALLOWED (GSSAPI) domain=%s principal=%s)Ts   OK)r   r$   )r   r/   rV   r    r    r!   rN   ¥  s    z"Authenticator._authenticate_gssapirD   )rP   Ústatus_codeÚstatus_textÚuser_idr#   c             C   s\   |dkr|nd}t |tƒr(| | jd¡}d}| j d||¡ t|||||g}| j |¡ dS )z.Send a ZAP reply to finish the authentication.s   200rX   rC   zZAP reply code=%s text=%sN)	Ú
isinstanceÚstrr<   r   r   r$   rK   r   Zsend_multipart)r   rP   r\   r]   r^   ZmetadataZreplyr    r    r!   rJ   ª  s    
zAuthenticator._send_zap_reply)Nr   N)r   N)r   r1   )r   N)r   N)rD   ) Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r`   Úboolr   r   r   Úbytesr   r"   r%   r'   r-   r.   r0   r   ÚosÚPathLiker7   r9   r>   r?   r   rW   r   rL   rM   rN   rJ   r    r    r    r!   r      sD   
  "
f$9

r   r3   )rd   r   rh   Útypingr   r   r   r   r   r   r   r   Z	zmq.errorr	   Z	zmq.utilsr
   r   r   r3   rK   r   Ú__all__r    r    r    r!   Ú<module>   s   $   *