
    Ef?                         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      ZddgZy)z*Base implementation of 0MQ authentication.    N)AnyDictListOptionalSetTupleUnion)_check_version)z85   )load_certificates*s   1.0c                   4   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-ded   dedefdZd.dZd.dZdeddfdZdeddfdZ	 d/dedeeef   ddfdZ	 d0dedeeej(                  f   ddfdZ	 d/dededdfdZde
defdZ	 d/dedee   ddfdZdee
   fd Zded!ed"edeee
f   fd#Zded$e
deee
f   fd%Zded&e
deee
f   fd'Z	 d1d(e
d)e
d*e
d+eddf
d,Zy)2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logNc                 6   t        dd       |xs t        j                  j                         | _        || _        d| _        i | _        d | _        t               | _
        t               | _        i | _        i | _        |xs t        j                  d      | _        y )N)   r   securityFzzmq.auth)r
   zmqContextinstancer   r   r   r   r   setr   r   r   r   logging	getLoggerr   )selfr   r   r   s       //usr/lib/python3/dist-packages/zmq/auth/base.py__init__zAuthenticator.__init__:   s     	vz*8#++"6"6"8 %'"  
7'++J7    returnc                     | j                   j                  t        j                        | _        d| j                  _        | j                  j                  d       | j                  j                  d       y)zCreate and bind the ZAP socketr   zinproc://zeromq.zap.01StartingN)	r   socketr   REPr   lingerbindr   debugr$   s    r%   startzAuthenticator.startP   sK    ,,--cgg6!"56z"r'   c                 ^    | j                   r| j                   j                          d| _         y)zClose the ZAP socketN)r   closer0   s    r%   stopzAuthenticator.stopW   s     ??OO!!#r'   	addressesc                     | j                   rt        d      | j                  j                  ddj	                  |             | j
                  j                  |       y)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.
        -Only use a whitelist or a blacklist, not bothzAllowing %s,N)r   
ValueErrorr   r/   joinr   updater$   r5   s     r%   allowzAuthenticator.allow]   sD     >>LMM}chhy&9:i(r'   c                     | j                   rt        d      | j                  j                  ddj	                  |             | j
                  j                  |       y)zDeny (blacklist) IP address(es).

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

        Blacklist is mutually exclusive with whitelist.
        r7   z
Denying %sr8   N)r   r9   r   r/   r:   r   r;   r<   s     r%   denyzAuthenticator.denyl   sD     >>LMM|SXXi%89i(r'   domainc                 ^    |r|| j                   |<   | j                  j                  d|       y)zConfigure 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   s      r%   configure_plainzAuthenticator.configure_plainx   s(     %.DNN6",f5r'   locationc                    | j                   j                  d||       |t        k(  rd| _        yd| _        	 t	        |      | j
                  |<   y# t        $ r'}| j                   j                  d||       Y d}~yd}~ww xY w)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@   rD   es       r%   configure_curvezAuthenticator.configure_curve   ss    " 	0&(C&!DN"DNV%6x%@

6" VGSTUUVs   A 	B A;;B credentials_providerc                 n    d| _         ||| j                  |<   y| j                  j                  d|       y)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   rH   )r$   r@   rK   s      r%   configure_curve_callbackz&Authenticator.configure_curve_callback   s4    : +1ED&&v.HHNNMvVr'   client_public_keyc                 J    t        j                  |      j                  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$   rN   s     r%   curve_user_idzAuthenticator.curve_user_id   s    & zz+,33G<<r'   c                      y)z~Configure GSSAPI authentication

        Currently this is a no-op because there is nothing to configure with GSSAPI.
        N )r$   r@   rD   s      r%   configure_gssapizAuthenticator.configure_gssapi   s    r'   msgc           	          t        |      dk  r] j                  j                  d|       t        |      dk  r j                  j                  d       y j                  |d   dd       y|dd \  }}}}}}|dd }|j	                   j
                  d	      }|j	                   j
                  d	      }|t        k7  r0 j                  j                  d
|        j                  |dd       y j                  j                  d||||||       d}	d}
d} j                  rN| j                  v rd}	 j                  j                  d|       nzd}
d} j                  j                  d|       nY j                  rM| j                  v r!d}
d} j                  j                  d|       nd}	 j                  j                  d|       d}|
sm|dk(  r!|	s j                  j                  d       d}	nG|dk(  rct        |      dk7  r0 j                  j                  d|        j                  |dd       y fd|D        \  }} j                  |||      \  }	}n|dk(  rlt        |      dk7  r0 j                  j                  d|        j                  |dd       y|d   } j                  ||      \  }	}|	r j                  |      }nn|d k(  rit        |      dk7  r0 j                  j                  d!|        j                  |dd       y|d   }|j	                  d"      } j                  ||      \  }	}|	r j                  |d#d$|       y j                  |d|       y)%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   V   K   | ]   }|j                  j                  d        " yw)r[   N)rR   r   ).0cr$   s     r%   	<genexpr>z3Authenticator.handle_zap_message.<locals>.<genexpr>'  s%      &;<AHHT]]I6&s   &)s   CURVEzInvalid CURVE credentials: %rr   s   GSSAPIzInvalid GSSAPI credentials: %rutf8   200   OK)lenr   rH   _send_zap_replyrR   r   VERSIONr/   r   r   _authenticate_plain_authenticate_curverS   _authenticate_gssapi)r$   rW   version
request_idr@   addressidentity	mechanismcredentialsalloweddeniedreasonusernamepasswordkey	principals   `               r%   handle_zap_messagez Authenticator.handle_zap_message   s>   s8a<HHNNGM3x!|@A  $$SVV5IJDGGAVWh	!"gt}}i8..	:gHHNN4c:  V5GH8		
 >>$..(>H4EwO^^$..(2>HEwO G#G/0h&{#q(HHNN#BKP((V=ST&@K&"( #'":":68X"Vh&{#q(HHNN#BKP((V=ST!!n"&":":63"G#11#6Hi'{#q(HHNN#C[Q((V=ST'N	$++F3"&";";FI"N  VUHE  VV<r'   rs   rt   c                 t   d}d}| j                   r|sd}|| j                   v r/|| j                   |   v r|| j                   |   |   k(  rd}nd}nd}nd}|r"| j                  j                  d|||       ||fS | j                  j                  d	|       ||fS d
}| j                  j                  d|       ||fS )zPLAIN ZAP authenticationFr'   r   Ts   Invalid passwords   Invalid usernames   Invalid domainz1ALLOWED (PLAIN) domain=%s username=%s password=%sz	DENIED %ss   No passwords definedzDENIED (PLAIN) %srB   )r$   r@   rs   rt   rp   rr   s         r%   rg   z!Authenticator._authenticate_plainF  s     >>'t~~f554>>&#9(#CC"&!40F*G	  {F3  -FHHNN.7r'   
client_keyc                 p   d}d}| j                   r#d}d}| j                  j                  d       ||fS | j                  i k7  r{|sd}|| j                  v rct	        j
                  |      }| j                  |   j                  ||      rd}d}nd}|rdnd	}| j                  j                  d
|||       ||fS d}||fS |sd}|| j                  v rbt	        j
                  |      }| j                  |   j                  |      rd}d}nd}|rdnd	}| j                  j                  d|||       ||fS d}||fS )zCURVE ZAP authenticationFr'   Trc   z ALLOWED (CURVE allow any client)r   s   Unknown keyALLOWEDDENIEDz0%s (CURVE auth_callback) domain=%s client_key=%ss   Unknown domainz"%s (CURVE) domain=%s client_key=%s)	r   r   r/   r   r   rQ   callbackr   get)r$   r@   ry   rp   rr   z85_client_keystatuss          r%   rh   z!Authenticator._authenticate_curvel  sk   >>GFHHNN=>` _ ''2-333!$J!7--f5>>v~V"G"F+F&-8F"	@ 3 +2 - #!$J!7::f%)).9"G"F+F&-88"	  +r'   rv   c                 >    | j                   j                  d||       y)zPNothing to do for GSSAPI, which has already been handled by an external service.z'ALLOWED (GSSAPI) domain=%s principal=%s)Trc   )r   r/   )r$   r@   rv   s      r%   ri   z"Authenticator._authenticate_gssapi  s    @&)Tr'   rk   status_codestatus_textuser_idc                     |dk(  r|nd}t        |t              r|j                  | j                  d      }d}| j                  j                  d||       t        |||||g}| j                  j                  |       y)z.Send a ZAP reply to finish the authentication.rb   r'   r[   zZAP reply code=%s text=%sN)	
isinstancestrrQ   r   r   r/   rf   r   send_multipart)r$   rk   r   r   r   metadatareplys          r%   re   zAuthenticator._send_zap_reply  sn     )F2'gs#nnT]]I>G2KM*k;R&&u-r'   )Nzutf-8N)r(   N)r   N)r   .)r\   ) __name__
__module____qualname____doc____annotations__r   boolr   r   r   bytesr   r&   r1   r4   r=   r?   rC   r	   osPathLikerJ   rM   rS   rV   r   rw   r   rg   rh   ri   re   rU   r'   r%   r   r      s`   4 MOS>)3x3xCc3h'((T%*%%&&	H ,0	8-(8 8 	8,#) ) )
)s 
)t 
) >B66,0cN6	6 FIVV+0bkk1A+BV	V8 >B"W"W7:"W	"WH=u = =, <@+3C=	c=d5k c=J$$%($47$	tU{	$L7# 75 7U4QV;EW 7r3 5 U4QV;EW  #.. . 	.
 . 
.r'   r   rF   )r   r"   r   typingr   r   r   r   r   r   r	   r   	zmq.errorr
   	zmq.utilsr   r   r   rF   rf   r   __all__rU   r'   r%   <module>r      sI    0
  	 ? ? ? 
 $  $
d. d.N -
.r'   