
    afY              	          d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	m
Z
 d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ 	 d d	lmZ d d
lmZ d dlmZ dZn# e$ r dZY nw xY wdZd Z  G d de!          Z" ej#        e"            G d de"          Z$ ej#        e$            G d de!          Z% ej#        e%            G d de!          Z& ej#        e&            G d de&          Z' ej#        e'           d Z(d Z) G d de!          Z* ej#        e*            G d de!          Z+ ej#        e+           ed2d!            Z,ed3d"            Z-ed#             Z.ed$             Z/ed4d'            Z0ed5d(            Z1d)Z2	 ed6d+            Z3ed,             Z4d7d-e5d.e5d/e	e6         d0e
fd1Z7dS )8    N)OptionalDict)public)xor)IAuthenticator)
PBKDF2HMAC)hashes)default_backendhash_secretType)saslprepTF)AuthAnonymous	AuthScramAuthCryptoSignAuthWampCra
AuthTicketcreate_authenticatorpbkdf2generate_totp_secretcompute_totp
check_totpqrcode_from_totp
derive_keygenerate_wcscompute_wcsderive_scram_credentialc                 x   	 t           j        t           t          j        t          t          j        t          t          j        t          t
          j        t
          t          j        t          t          j        t          i|          }n0# t          $ r# t          d
                    |                     w xY w |di |}|S )a  
    Accepts various keys and values to configure an authenticator. The
    valid keys depend on the kind of authenticator but all can
    understand: `authextra`, `authid` and `authrole`

    :return: an instance implementing IAuthenticator with the given
        configuration.
    zUnknown authenticator '{}' )r   namer   AuthCryptoSignProxyr   r   AuthAnonymousProxyr   KeyError
ValueErrorformat)r!   kwargsklassauthenticators       D/var/www/html/env/lib/python3.11/site-packages/autobahn/wamp/auth.pyr   r   K   s    
NI$&9k#%7OZ
   
 
 
(//55
 
 	


 EOOFOOMs   A?B -B/c                   :    e Zd ZdZd Zed             Zd Zd ZdS )r   	anonymousc                     || _         d S N)_argsselfkws     r*   __init__zAuthAnonymous.__init__k   s    


    c                 P    | j                             dt                                S N	authextrar/   getdictr1   s    r*   r7   zAuthAnonymous.authextran       z~~k466222r4   c                      t          d          )Nz/on_challenge called on anonymous authentication)RuntimeErrorr1   session	challenges      r*   on_challengezAuthAnonymous.on_challenger   s    =
 
 	
r4   c                     d S r.   r    r1   msgr7   s      r*   
on_welcomezAuthAnonymous.on_welcomew       tr4   N	__name__
__module____qualname__r!   r3   propertyr7   rB   rF   r    r4   r*   r   r   h   sa        D   3 3 X3
 
 

    r4   r   c                       e Zd ZdZdS )r#   zanonymous-proxyNrI   rJ   rK   r!   r    r4   r*   r#   r#   ~   s        DDDr4   r#   c                   :    e Zd ZdZd Zed             Zd Zd ZdS )r   ticketc                     || _         	 | j                             d          | _        d S # t          $ r t	          d          w xY w)NrP   z.ticket authentication requires 'ticket=' kwarg)r/   pop_ticketr$   r%   r0   s     r*   r3   zAuthTicket.__init__   sW    
	:>>(33DLLL 	 	 	@  	s	   * Ac                 P    | j                             dt                                S r6   r8   r;   s    r*   r7   zAuthTicket.authextra   r<   r4   c                 *    |j         dk    sJ | j        S )NrP   )methodrS   r?   s      r*   rB   zAuthTicket.on_challenge   s    8++++|r4   c                     d S r.   r    rD   s      r*   rF   zAuthTicket.on_welcome   rG   r4   NrH   r    r4   r*   r   r      sa        D   3 3 X3      r4   r   c                   :    e Zd ZdZd Zed             Zd Zd ZdS )r   
cryptosignc                 ,   |                                 D ]3}|dvr-t          d                    || j        j                            4dD ](}||vr"t          d                    |                    )ddlm} |                    t          j	        |d                             | _
        d|                    d	t                                v r;|d	         d         }|| j
                                        k    rt          d
          nG|                    d	t                                |d	<   | j
                                        |d	         d<   |                    d	t                                                    dd           | _        || _        d S )N)r7   authidauthroleprivkeyUnexpected key '{}' for {})r]   z Must provide '{}' for cryptosignr   )CryptosignKeyr]   pubkeyr7   z,Public key doesn't correspond to private keychannel_binding)keysr%   r&   	__class__rI   autobahn.wamp.cryptosignr_   
from_bytesbinasciia2b_hex_privkeyr9   r:   
public_key_channel_bindingr/   )r1   r2   keyr_   r`   s        r*   r3   zAuthCryptoSign.__init__   s   7799 	 	CHHH 077T^=TUU   I  	 	C"}} 6==cBB   
 	;:::::%00R	]++
 
 rvvk4662222_X.F113333 B   4
 !ff[$&&99B{O(,(@(@(B(BB{OH% "{DFF ; ; ? ?@QSW X X


r4   c                 P    | j                             dt                                S r6   r8   r;   s    r*   r7   zAuthCryptoSign.authextra   r<   r4   c                     |j         j        j                            | j        d           }| j                            ||| j                  S )N)
channel_idchannel_id_type)
_transporttransport_detailsrn   r9   rj   rh   sign_challenge)r1   r@   rA   rn   s       r*   rB   zAuthCryptoSign.on_challenge   sQ    '9DHHI^`dee
}++I7A<@<Q , S S 	Sr4   c                     d S r.   r    rD   s      r*   rF   zAuthCryptoSign.on_welcome   rG   r4   NrH   r    r4   r*   r   r      sd        D  > 3 3 X3S S S    r4   r   c                       e Zd ZdZdS )r"   zcryptosign-proxyNrN   r    r4   r*   r"   r"      s        DDDr4   r"   c           
          t          | t          j        |          ||ddt          j        d          }|                    d          \  }}}}}	}
|
S )z
    Internal helper. Returns the salted/hashed password using the
    argon2id-13 algorithm. The return value is base64-encoded.
              secretsalt	time_costmemory_costparallelismhash_lentypeversion   $)r   base64	b64decoder   IDsplit)passwordr{   
iterationsmemoryrawhash_tagveroptions	salt_data	hash_datas              r*   _hash_argon2id13_secretr      sc    
 d##W	 	 	G 29t1D1D.AsC)Yr4   c                 (    t          | ||d          S )z2
    Internal helper for SCRAM authentication
    rw   )keylen)r   )r   r{   r   s      r*   _hash_pbkdf2_secretr      s     (D*R8888r4   c                   >    e Zd ZdZdZd Zed             Zd Zd Z	dS )r   z
    Implements "wamp-scram" authentication for components.

    NOTE: This is a prototype of a draft spec; see
    https://github.com/wamp-proto/wamp-proto/issues/135
    scramc                 N    t           st          d          || _        d | _        d S )Nz^Cannot support WAMP-SCRAM without argon2_cffi and passlib libraries; install autobahn['scram'])	HAS_ARGONr>   r/   _client_noncer0   s     r*   r3   zAuthScram.__init__   s8     	?   
!r4   c                     | j         >t          j        t          j        d                                        d          | _         d| j         iS )N   asciinonce)r   r   	b64encodeosurandomdecoder;   s    r*   r7   zAuthScram.authextra	  sH     %!'!1"*R..!A!A!H!H!Q!QDT'
 	
r4   c                    |j         dk    sJ | j        J g d}ddg}|D ]-}||j        vr"t          d                    |                    .|j        D ]+}|||z   vr"t          d                    |                    ,|j                            dd          }|j        d         }|j        d	         }t          |j        d
                   }	t          |j                            dd                    }
| j        d                             d          }t          | j        d                   }|j        d         }| j        }d                    d                    ||          d                    |||	          d                    ||                                        d          | _
        |dk    r-|
dk    rt          d          t          |||	|
          | _        n?|dk    rt          |||	          | _        n"t          d                    |                    t          j        | j        dt"          j                                                  }t#          j        d|                                          }t          j        || j
        t"          j                                                  }t)          ||          }t+          j        |          S )Nr   )r   kdfr{   r   r   ra   z?WAMP-SCRAM challenge option '{}' is  required but not specifiedz/WAMP-SCRAM challenge has unknown attribute '{}' r   r{   r   r   utf8r[   r   z:{client_first_bare},{server_first},{client_final_no_proof}z	n={},r={}zr={},s={},i={}z	c={},r={})client_first_bareserver_firstclient_final_no_proofr   argon2id-13z>WAMP-SCRAM 'argon2id-13' challenge requires 'memory' parameterr   z%WAMP-SCRAM specified unknown KDF '{}'
   Client Keysha256)rV   r   extrar>   r&   r9   intr/   encoder   _auth_messager%   r   _salted_passwordr   hmacnewhashlibr   digest	xor_arrayr   r   )r1   r@   rA   required_argsoptional_argskra   server_noncer{   r   r   r   r[   	algorithmclient_nonce
client_key
stored_keyclient_signatureclient_proofs                      r*   rB   zAuthScram.on_challenge  s   7****!--->>>!#45 	 	A	''"228&))   (
  	 	A555"ELLQOO   6
 $/--.?DD w/v&677
Y_((26677:j)0088$*X.//OE*	) IOO"-"4"4V\"J"J-44\4TT&1&8&8,&W&W P  
 &// 	 %%|| T   %<HdJX^$_$_D!!(""$7$
$S$SD!!7>>yII   Xd3]GNSSZZ\\
[:66==??
8J0BGNSSZZ\\ -=>>---r4   c                    t          j        |d                   }t          j        | j        dt
          j                                                  }t          j        || j        t
          j                                                  }t          j	        ||          s|j
                            d           dS |j
                            d           dS )a  
        When the server is satisfied, it sends a 'WELCOME' message.

        This hook allows us an opportunity to deny the session right
        before it gets set up -- we check the server-signature thus
        authorizing the server and if it fails we drop the connection.
        scram_server_signature
   Server Keyz-Verification of server SCRAM signature failedz1Verification of server SCRAM signature successfulN)r   r   r   r   r   r   r   r   r   compare_digestlogerrorinfo)r1   r@   r7   alleged_server_sig
server_keyserver_signatures         r*   rF   zAuthScram.on_welcomeJ  s     $-i8P.QRRXd3]GNSSZZ\\
8J0BGNSSZZ\\"#35GHH 	CKMNNNBB?	
 	
 	
 tr4   N)
rI   rJ   rK   __doc__r!   r3   rL   r7   rB   rF   r    r4   r*   r   r      sn          D" " " 
 
 X
6. 6. 6.p    r4   r   c                   :    e Zd ZdZd Zed             Zd Zd ZdS )r   wampcrac                    |                                 D ]3}|dvr-t          d                    || j        j                            4dD ](}||vr"t          d                    |                    )|| _        |                    d          | _        t          | j        t                    s!| j        
                    d          | _        d S d S )N)r7   r[   r\   rz   r^   )rz   r[   zMust provide '{}' for wampcrarz   r   )rb   r%   r&   rc   rI   r/   rR   _secret
isinstancestrr   )r1   r2   rk   s      r*   r3   zAuthWampCra.__init__d  s    7799 	 	CGGG 077T^=TUU   H ( 	 	C"}} 3::3??   
 
vvh''$,,, 	7<..v66DLLL	7 	7r4   c                 P    | j                             dt                                S r6   r8   r;   s    r*   r7   zAuthWampCra.authextrav  r<   r4   c                 4   | j                             d          }d|j        v r3t          ||j        d         |j        d         |j        d                   }t	          ||j        d                             d                    }|                    d          S )Nr   r{   r   r   rA   r   )r   r   r   r   r   r   )r1   r@   rA   rk   	signatures        r*   rB   zAuthWampCra.on_challengez  s    l!!&))Y_$$'-)	 C  OK(//77
 
	 (((r4   c                     d S r.   r    rD   s      r*   rF   zAuthWampCra.on_welcome  rG   r4   NrH   r    r4   r*   r   r   a  sa        D7 7 7$ 3 3 X3) ) )     r4   r   
   c                     t          |           t          k    sJ t          j        t	          j        |                                         d          S )a  
    Generates a new Base32 encoded, random secret.

    .. seealso:: http://en.wikipedia.org/wiki/Base32

    :param length: The length of the entropy used to generate the secret.
    :type length: int

    :returns: The generated secret in Base32 (letters ``A-Z`` and digits ``2-7``).
       The length of the generated secret is ``length * 8 / 5`` octets.
    :rtype: unicode
    r   )r   r   r   	b32encoder   r   r   lengths    r*   r   r     sD     <<3BJv..//66w???r4   c                 B   t          |           t          k    sJ t          |          t          k    sJ 	 t          j        |           }n# t
          $ r t          d          w xY w|t          t          j                              dz  z   }t          j	        d|          }t          j        ||t          j                                                  }d|d         z  }t          j        d|||dz                      d         d	z  d
z  }d                    |          S )aF  
    Computes the current TOTP code.

    :param secret: Base32 encoded secret.
    :type secret: unicode
    :param offset: Time offset (in steps, use eg -1, 0, +1 for compliance with RFC6238)
        for which to compute TOTP.
    :type offset: int

    :returns: TOTP for current time (+/- offset).
    :rtype: unicode
    zinvalid secret   z>Q   rx   z>I   r   ii@B z{0:06d})r   r   r   r   	b32decode	TypeError	Exceptiontimestructpackr   r   r   sha1r   unpackr&   )rz   offsetrk   intervalrE   r   otokens           r*   r   r     s    <<3<<3*v&& * * *()))*DIKK((B..H
+dH
%
%CXc3--4466F
fRjA]4!a%11!4zAWLEE"""s   A A%c                 >    dD ]}|t          | |          k    r dS dS )a  
    Check a TOTP value received from a principal trying to authenticate against
    the expected value computed from the secret shared between the principal and
    the authenticating entity.

    The Internet can be slow, and clocks might not match exactly, so some
    leniency is allowed. RFC6238 recommends looking an extra time step in either
    direction, which essentially opens the window from 30 seconds to 90 seconds.

    :param secret: The secret shared between the principal (eg a client) that
        is authenticating, and the authenticating entity (eg a server).
    :type secret: unicode
    :param ticket: The TOTP value to be checked.
    :type ticket: unicode

    :returns: ``True`` if the TOTP value is correct, else ``False``.
    :rtype: bool
    )r   rv   r   TF)r   )rz   rP   r   s      r*   r   r     s9    (   \&&111144 25r4   c                    t          |           t          k    r/t          d                    t          |                               t          |          t          k    r/t          d                    t          |                              	 dd l}dd l}n# t          $ r t          d          w xY w|                    d                    || |          d|j        j	        j
                                                  S )Nz&secret must be of type unicode, not {}z%label must be of type unicode, not {}r   zqrcode not installedz%otpauth://totp/{}?secret={}&issuer={}   )box_sizeimage_factory)r   r   r   r&   qrcodeqrcode.image.svgImportErrormakeimagesvgSvgImage	to_string)rz   labelissuerr   s       r*   r   r     s    F||s@GGVUUVVVE{{c?FFtE{{SSTTT0 0 0 0.///0 ;;/66uffMMl&/  1 1 2;=s   B B3  rw   c                    t          |           t          k    rHt          |          t          k    r0t          |          t          k    rt          |          t          k    st          d          |d}|t          u rt          d          t                      }t           t          t          |	                                                      ||||          }|
                    |           S )a	  
    Returns a binary digest for the PBKDF2 hash algorithm of ``data``
    with the given ``salt``. It iterates ``iterations`` time and produces a
    key of ``keylen`` bytes. By default SHA-256 is used as hash function,
    a different hashlib ``hashfunc`` can be provided.

    :param data: The data for which to compute the PBKDF2 derived key.
    :type data: bytes
    :param salt: The salt to use for deriving the key.
    :type salt: bytes
    :param iterations: The number of iterations to perform in PBKDF2.
    :type iterations: int
    :param keylen: The length of the cryptographic key to derive.
    :type keylen: int
    :param hashfunc: Name of the hash algorithm to use
    :type hashfunc: str

    :returns: The derived cryptographic key.
    :rtype: bytes
    zInvalid argument typesNr   z=pbkdf2 now takes the name of a hash algorithm for 'hashfunc=')r   r   r{   r   backend)r   bytesr   r%   callabler
   r   getattrr	   upperderive)datar{   r   r   hashfuncr   r   s          r*   r   r     s    , JJ%JJ%##LLC1222
 8K
 
 	
 G 3'&(.."2"23355  C ::dr4   c                 r   t          |           t          t          fvrt          d          t          |          t          t          fvrt          d          t          |          t          k    st          d          t          |          t          k    st          d          t          |           t          k    r|                     d          } t          |          t          k    r|                    d          }t          | |||          }t          j        |          	                                S )a  
    Computes a derived cryptographic key from a password according to PBKDF2.

    .. seealso:: http://en.wikipedia.org/wiki/PBKDF2

    :param secret: The secret.
    :type secret: bytes or unicode
    :param salt: The salt to be used.
    :type salt: bytes or unicode
    :param iterations: Number of iterations of derivation algorithm to run.
    :type iterations: int
    :param keylen: Length of the key to derive in bytes.
    :type keylen: int

    :return: The derived key in Base64 encoding.
    :rtype: bytes
    z'secret' must be bytesz'salt' must be bytesz'iterations' must be an integerz'keylen' must be an integerr   )
r   r   r   r%   r   r   r   rf   
b2a_base64strip)rz   r{   r   r   rk   s        r*   r   r   !  s   & LLS%L((1222JJ3,&&/000##:;;;LLC6777F||sv&&DzzS{{6""
z6
2
2Cs##))+++r4   >ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789   c                     t          |           t          k    sJ d                    d t          |           D                                           d          S )aw  
    Generates a new random secret for use with WAMP-CRA.

    The secret generated is a random character sequence drawn from

    - upper and lower case latin letters
    - digits
    -

    :param length: The length of the secret to generate.
    :type length: int

    :return: The generated secret. The length of the generated is ``length`` octets.
    :rtype: bytes
    r   c              3   H   K   | ]}t          j        t                    V  d S r.   )randomchoiceWCS_SECRET_CHARSET).0r   s     r*   	<genexpr>zgenerate_wcs.<locals>.<genexpr>\  s-      LL6=!344LLLLLLr4   r   )r   r   joinranger   r   s    r*   r   r   J  sQ    " <<377LLeFmmLLLLLSST[\\\r4   c                    t          |           t          t          fv sJ t          |          t          t          fv sJ t          |           t          k    r|                     d          } t          |          t          k    r|                    d          }t	          j        | |t          j                                                  }t          j
        |                                          S )aY  
    Compute an WAMP-CRA authentication signature from an authentication
    challenge and a (derived) key.

    :param key: The key derived (via PBKDF2) from the secret.
    :type key: bytes
    :param challenge: The authentication challenge to sign.
    :type challenge: bytes

    :return: The authentication signature.
    :rtype: bytes
    r   )r   r   r   r   r   r   r   r   r   rf   r  r  )rk   rA   sigs      r*   r   r   _  s     99e$$$$	??sEl****CyyCjj  I#$$V,,	
(3	7>
2
2
9
9
;
;Cs##))+++r4   emailr   r{   returnc           
         t           s
J d            ddlm} ddlm} |sWt	          j                    }|                    |                     d                     |                                dd         }t          |          dk    sJ  ||                    d          |dd	d
d|j
        d          }|                    d                              d          \  }}}	}
}}|dk    sJ |	dk    sJ d d |
                    d          D             D             }
|                    d          }t          j        |dt          j                                                  }t	          j        d|                                          }t          j        |dt          j                                                  }dt          |
d                   t          |
d                   t!          j        |                              d          t!          j        |                              d          t!          j        |                              d          d}|S )a?  
    Derive WAMP-SCRAM credentials from user email and password. The SCRAM parameters used
    are the following (these are also contained in the returned credentials):

    * kdf ``argon2id-13``
    * time cost ``4096``
    * memory cost ``512``
    * parallelism ``1``

    See `draft-irtf-cfrg-argon2 <https://datatracker.ietf.org/doc/draft-irtf-cfrg-argon2/>`__ and
    `argon2-cffi <https://argon2-cffi.readthedocs.io/en/stable/>`__.

    :param email: User email.
    :param password: User password.
    :param salt: Optional salt to use (must be 16 bytes long). If none is given, compute salt
        from email as ``salt = SHA256(email)[:16]``.
    :return: WAMP-SCRAM credentials. When serialized, the returned credentials can be copy-pasted
        into the ``config.json`` node configuration for a Crossbar.io node.
    zmissing dependency argon2r   r   r   r   Nr   i   i   rv   rw   rx   ry   r   $argon2idzv=19c                     i | ]\  }}||	S r    r    )r  r   vs      r*   
<dictcomp>z+derive_scram_credential.<locals>.<dictcomp>  s.       Aq 	
1  r4   c                 8    g | ]}|                     d           S )=)r   )r  xs     r*   
<listcomp>z+derive_scram_credential.<locals>.<listcomp>  s"    111!111r4   ,r   r   r   r   mt)r   r   r   r{   z
stored-keyz
server-key)r   argon2.low_levelr   r   r   r   updater   r   lenr   r   r   r   r   r   rf   b2a_hex)r  r   r{   r   r   r!  r   r   r   r  paramssalted_passwordr   r   r   
credentials                   r*   r   r   w  s\   ( 111119,,,,,,%%%%%%  N	f%%&&&xxzz#2#t99????v&&W	 	 	I -6,<,<W,E,E,K,KC,P,P)AsAvq/*;;;;  	21v||C00111  F &,,W55O/='.IIPPRRJXz2299;;J/='.IIPPRRJ fSk""&+&& &&--g66&z2299'BB&z2299'BB J r4   )r   )r   )r   rw   N)r   rw   )r  r.   )8r   r   r   r   rf   r   r   r  typingr   r   autobahn.utilr   r   r   autobahn.wamp.interfacesr   )cryptography.hazmat.primitives.kdf.pbkdf2r   cryptography.hazmat.primitivesr	   cryptography.hazmat.backendsr
   r#  r   argon2r   passlib.utilsr   r   r   __all__r   objectr   registerr#   r   r   r"   r   r   r   r   r   r   r   r   r   r   r  r   r   r   r   r   r    r4   r*   <module>r5     s  6 
			        ! ! ! ! ! ! ! !             * * * * * * 3 3 3 3 3 3 @ @ @ @ @ @ 1 1 1 1 1 1 8 8 8 8 8 8,,,,,,&&&&&&II   III&  :    F   &   & & &         * + + +       0  
 # # #- - - - -V - - -`   ' ' '    .     + , , ,  ,9 9 9d d d d d d d dN  	 " " "* * * * *& * * *Z   $ $ $ @ @ @ @" # # # #6   2 = = =& 0 0 0 0f , , , ,D V 
 ] ] ] ]( , , ,.? ?3 ?# ?Xe_ ?X\ ? ? ? ? ? ?s   A# #A-,A-