o
    shO                     @  s~  d dl mZ ddlmZ ddlmZ ddlmZmZ ddl	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ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(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ d dl0Z0d dl1Z1e12e3Z4e+ee5gdf Z6e+e7ge8f Z9d1ddZ:d2ddZ;	d3d4ddZ<d5d d!Z=d6d&d'Z>G d(d) d)Z?d7d-d.Z@G d/d0 d0e?ZAdS )8    )annotations   verify_rp_id)CoseKey)websafe_encodewebsafe_decode)CollectedClientDataAuthenticatorDataAttestationObjectAttestedCredentialDataAttestationConveyancePreferencePublicKeyCredentialRpEntityPublicKeyCredentialUserEntityAuthenticatorSelectionCriteriaPublicKeyCredentialDescriptorPublicKeyCredentialTypePublicKeyCredentialParameters"PublicKeyCredentialCreationOptions!PublicKeyCredentialRequestOptionsUserVerificationRequirementResidentKeyRequirementAuthenticatorAttachmentRegistrationResponseAuthenticationResponseCredentialCreationOptionsCredentialRequestOptions)constant_time)InvalidSignature)replace)urlparse)SequenceMappingOptionalCallableUnionTupleAnyoverloadNrp_idstrreturnVerifyOriginc                   s    fddS )Nc                   
   t  | S Nr   or)    G/var/www/html/env_mimamsha/lib/python3.10/site-packages/fido2/server.py<lambda>I      
 z'_verify_origin_for_rp.<locals>.<lambda>r2   r1   r2   r1   r3   _verify_origin_for_rpH   s   r6   	challengeOptional[bytes]bytesc                 C  s@   | d u rt d} | S t| tstdt| dk rtd| S )N    z)Custom challenge must be of type 'bytes'.   z&Custom challenge length must be >= 16.)osurandom
isinstancer9   	TypeErrorlen
ValueError)r7   r2   r2   r3   _validata_challengeL   s   

rB   
credentialr   r   c                 C  s   t tj| j|S )a  Converts an AttestedCredentialData to a PublicKeyCredentialDescriptor.

    :param credential: AttestedCredentialData containing the credential ID to use.
    :param transports: Optional list of AuthenticatorTransport strings to add to the
        descriptor.
    :return: A descriptor of the credential, for use with register_begin or
        authenticate_begin.
    :rtype: PublicKeyCredentialDescriptor
    )r   r   
PUBLIC_KEYcredential_id)rC   
transportsr2   r2   r3   to_descriptorW   s   
rG   credsPOptional[Sequence[Union[AttestedCredentialData, PublicKeyCredentialDescriptor]]]1Optional[Sequence[PublicKeyCredentialDescriptor]]c                 C  s   | d u rd S dd | D S )Nc                 S  s(   g | ]}t |trt|nt|qS r2   )r>   r   rG   r   	from_dict).0cr2   r2   r3   
<listcomp>o   s    
z%_wrap_credentials.<locals>.<listcomp>r2   )rH   r2   r2   r3   _wrap_credentialsh   s
   rO   attestation_objectr   client_data_hashNonec                 C  s   dS )zIgnore attestation.Nr2   )rP   rQ   r2   r2   r3   _ignore_attestationy   s    rS   c                   @  s   e Zd ZdZ			d8d9ddZ						d:d;ddZed<d d!Zed=d&d!Zd'd! Z				d>d?d)d*Zed@d.d/Z	edAd4d/Z	d5d/ Z	e
dBd6d7ZdS )CFido2Servera@  FIDO2 server.

    :param rp: Relying party data as `PublicKeyCredentialRpEntity` instance.
    :param attestation: (optional) Requirement on authenticator attestation.
    :param verify_origin: (optional) Alternative function to validate an origin.
    :param verify_attestation: (optional) function to validate attestation, which is
        invoked with attestation_object and client_data_hash. It should return nothing
        and raise an exception on failure. By default, attestation is ignored.
        Attestation is also ignored if `attestation` is set to `none`.
    Nrpr   attestation)Optional[AttestationConveyancePreference]verify_originOptional[VerifyOrigin]verify_attestationOptional[VerifyAttestation]c                 C  sb   t || _|pt| jj| _d | _t|| _dd t	
 D | _|p$t| _td| j  d S )Nc                 S  s   g | ]}t tj|qS r2   )r   r   rD   )rL   algr2   r2   r3   rN      s    
z(Fido2Server.__init__.<locals>.<listcomp>z Fido2Server initialized for RP: )r   rK   rU   r6   id_verifytimeoutr   rV   r   supported_algorithmsallowed_algorithmsrS   _verify_attestationloggerdebug)selfrU   rV   rX   rZ   r2   r2   r3   __init__   s   

zFido2Server.__init__userr   credentialsrI   resident_key_requirement Optional[ResidentKeyRequirement]user_verification%Optional[UserVerificationRequirement]authenticator_attachment!Optional[AuthenticatorAttachment]r7   r8   r+   %Tuple[CredentialCreationOptions, Any]c           
      C  s   | j stdt|}t|}| ||}	tdddd |p g D   tt	| j
t||| j | j|t|||frAt|||nd| j|	|	fS )av  Return a PublicKeyCredentialCreationOptions registration object and
        the internal state dictionary that needs to be passed as is to the
        corresponding `register_complete` call.

        :param user: The dict containing the user data.
        :param credentials: The list of previously registered credentials, these can be
            of type AttestedCredentialData, or PublicKeyCredentialDescriptor.
        :param resident_key_requirement: The desired RESIDENT_KEY_REQUIREMENT level.
        :param user_verification: The desired USER_VERIFICATION level.
        :param authenticator_attachment: The desired AUTHENTICATOR_ATTACHMENT
            or None to not provide a preference (and get both types).
        :param challenge: A custom challenge to sign and verify or None to use
            OS-specific random bytes.
        :return: Registration data, internal state.z!Server has no allowed algorithms.z1Starting new registration, existing credentials: , c                 s      | ]}|j  V  qd S r.   r]   hexrL   dr2   r2   r3   	<genexpr>       z-Fido2Server.register_begin.<locals>.<genexpr>N)ra   rA   rB   rO   _make_internal_staterc   rd   joinr   r   rU   r   rK   r_   anyr   rV   )
re   rg   rh   ri   rk   rm   r7   
extensionsdescriptorsstater2   r2   r3   register_begin   sH   zFido2Server.register_beginresponse.Union[RegistrationResponse, Mapping[str, Any]]r
   c                 C     d S r.   r2   )re   r}   r   r2   r2   r3   register_complete   s   zFido2Server.register_completeclient_datar	   rP   r   c                 C  r   r.   r2   )re   r}   r   rP   r2   r2   r3   r         c                 O  s  d}t |dkr|s|d }nt|dhkr|s|d }|r,t|}|jj}|jj}n1ddg}tt||}	i ||	}
t|t|	@ sMt|
t|krQt	d|
|d  }|
|d  }|j
tjjkrhtd| |jsrtd	tt|d
 |jstdt| jj|jjstd|j std|d tjkr|j std| jdtjfvrt !d|j"  | #||j$ |j}|j%dusJ t &d|j%j'(   |S )aL  Verify the correctness of the registration data received from
        the client.

        :param state: The state data returned by the corresponding
            `register_begin`.
        :param client_data: The client data.
        :param attestation_object: The attestation object.
        :return: The authenticator data
        Nr   r   r   r   rP   z1incorrect arguments passed to register_complete()&Incorrect type in CollectedClientData.&Invalid origin in CollectedClientData.r7   Wrong challenge in response.Wrong RP ID hash in response.User Present flag not set.rk   z;User verification required, but User Verified flag not set.zVerifying attestation of type zNew credential registered: ))r@   setr   rK   r   r   rP   dictzipr?   typer	   TYPECREATErA   r^   originr   bytes_eqr   r7   rU   id_hash	auth_data
rp_id_hashis_user_presentr   REQUIREDis_user_verifiedrV   r   NONErc   rd   fmtrb   hashcredential_datainforE   rs   )re   r}   argskwargsr   registrationr   rP   namesposdatar   r2   r2   r3   r      s^   



 

$Tuple[CredentialRequestOptions, Any]c                 C  sn   t |}t|}| ||}|du rtd ntdddd |D   tt|| j| j	j
||||fS )aR  Return a PublicKeyCredentialRequestOptions assertion object and the internal
        state dictionary that needs to be passed as is to the corresponding
        `authenticate_complete` call.

        :param credentials: The list of previously registered credentials, these can be
            of type AttestedCredentialData, or PublicKeyCredentialDescriptor.
        :param user_verification: The desired USER_VERIFICATION level.
        :param challenge: A custom challenge to sign and verify or None to use
            OS-specific random bytes.
        :return: Assertion data, internal state.Nz/Starting new authentication without credentialsz.Starting new authentication, for credentials: rp   c                 s  rq   r.   rr   rt   r2   r2   r3   rv   N  rw   z1Fido2Server.authenticate_begin.<locals>.<genexpr>)rB   rO   rx   rc   rd   ry   r   r   r_   rU   r]   )re   rh   rk   r7   r{   r|   r}   r2   r2   r3   authenticate_begin3  s,   
zFido2Server.authenticate_begin Sequence[AttestedCredentialData]0Union[AuthenticationResponse, Mapping[str, Any]]r   c                 C  r   r.   r2   )re   r}   rh   r   r2   r2   r3   authenticate_complete_  r   z!Fido2Server.authenticate_completerE   r9   r   	signaturec                 C  r   r.   r2   )re   r}   rh   rE   r   r   r   r2   r2   r3   r   h  s   
c              	   O  s  d}t |dkr|s|d }nt|dhkr|s|d }|r3t|}|j}|jj}|jj}	|jj}
n=g d}t	t
||}i ||}t|t|@ sTt|t|krXtd||d  }||d  }||d  }	||d  }
|jtjjkr{td	| |jstd
t|d |jkrtdt| jj|	jstd|	 std|d tjkr|	 std|D ]-}|j|krz|j |	|j! |
 W n t"y   tdw t#$d|%   |  S qtd)a  Verify the correctness of the assertion data received from
        the client.

        :param state: The state data returned by the corresponding
            `register_begin`.
        :param credentials: The list of previously registered credentials.
        :param credential_id: The credential id from the client response.
        :param client_data: The client data.
        :param auth_data: The authenticator data.
        :param signature: The signature provided by the client.Nr   r   r   )rE   r   r   r   z5incorrect arguments passed to authenticate_complete()      r   r   r7   r   r   r   rk   z;User verification required, but user verified flag not set.zInvalid signature.zCredential authenticated: zUnknown credential ID.)&r@   r   r   rK   r]   r   r   authenticator_datar   r   r   r?   r   r	   r   GETrA   r^   r   r   r7   r   r   rU   r   r   r   r   r   r   rE   
public_keyverifyr   _InvalidSignaturerc   r   rs   )re   r}   rh   r   r   r   authenticationrE   r   r   r   r   r   r   credr2   r2   r3   r   t  s^   


 
c                 C  s   t | |dS )Nr7   rk   )r   r   r2   r2   r3   rx     s   z Fido2Server._make_internal_state)NNN)rU   r   rV   rW   rX   rY   rZ   r[   )NNNNNN)rg   r   rh   rI   ri   rj   rk   rl   rm   rn   r7   r8   r+   ro   )r   r   r+   r
   )r   r	   rP   r   r+   r
   )NNNN)rh   rI   rk   rl   r7   r8   r+   r   )rh   r   r   r   r+   r   )rh   r   rE   r9   r   r	   r   r
   r   r9   r+   r   )r7   r9   rk   rl   )__name__
__module____qualname____doc__rf   r~   r(   r   r   r   staticmethodrx   r2   r2   r2   r3   rT      s<    DE,?rT   app_idr   boolc                 C  s<   t | }|j}|jdkr|j|fdkrdS |sdS t||S )a+  Checks if a FIDO U2F App ID is usable for a given origin.

    :param app_id: The App ID to validate.
    :param origin: The origin of the request.
    :return: True if the App ID is usable by the origin, False if not.

    .. deprecated:: 1.2.0
       This will be removed in python-fido2 2.0.
    https)http	localhostF)r    hostnameschemer   )r   r   urlr   r2   r2   r3   verify_app_id  s   

r   c                      sJ   e Zd ZdZ	dd fd	d
Z fddZ fddZ fddZ  ZS )U2FFido2ServeraL  Fido2Server which can be used with existing U2F credentials.

    This Fido2Server can be used with existing U2F credentials by using the
    WebAuthn appid extension, as well as with new WebAuthn credentials.
    See https://www.w3.org/TR/webauthn/#sctn-appid-extension for details.

    :param app_id: The appId which was used for U2F registration.
    :param verify_u2f_origin: (optional) Alternative function to validate an
        origin for U2F credentials.

    For other parameters, see Fido2Server.

    .. deprecated:: 1.2.0
       This will be removed in python-fido2 2.0.
    Nr   r*   rU   r   verify_u2f_originrY   c                   sh   t  j|g|R i | |r||d< n fdd|d<  | _ttt| dg|R i || _d S )NrX   c                   r-   r.   )r   r/   r   r2   r3   r4     r5   z)U2FFido2Server.__init__.<locals>.<lambda>)r]   )superrf   _app_idrT   r   r   rK   _app_id_server)re   r   rU   r   r   r   	__class__r   r3   rf     s   
zU2FFido2Server.__init__c                   0   | j |di d< t j|i |\}}||fS )Nr{   appidExclude)r   
setdefaultr   r~   re   r   r   reqr}   r   r2   r3   r~        zU2FFido2Server.register_beginc                   r   )Nr{   appid)r   r   r   r   r   r   r2   r3   r     r   z!U2FFido2Server.authenticate_beginc                   s:   z
t  j|i |W S  ty   | jj|i | Y S w r.   )r   r   rA   r   )re   r   r   r   r2   r3   r     s
   z$U2FFido2Server.authenticate_completer.   )r   r*   rU   r   r   rY   )	r   r   r   r   rf   r~   r   r   __classcell__r2   r2   r   r3   r     s    r   )r)   r*   r+   r,   )r7   r8   r+   r9   r.   )rC   r   r+   r   )rH   rI   r+   rJ   )rP   r   rQ   r9   r+   rR   )r   r*   r   r*   r+   r   )B
__future__r   rpidr   coser   utilsr   r   webauthnr	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   cryptography.hazmat.primitivesr   cryptography.exceptionsr   r   dataclassesr   urllib.parser    typingr!   r"   r#   r$   r%   r&   r'   r(   r<   logging	getLoggerr   rc   r9   VerifyAttestationr*   r   r,   r6   rB   rG   rO   rS   rT   r   r   r2   r2   r2   r3   <module>   s4   X(




  
A