o
    shX                     @  sR  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
 ddlmZmZ ddlmZmZ d d	lmZmZ d d
lmZmZmZmZ d dlmZ d dlmZmZmZmZm Z m!Z! d dl"Z"d dl#Z#e#$e%Z&dddZ'G dd dee( Z)edddG dd de)Z*edddG dd de)Z+edddG dd de)Z,G dd dZ-dS )     )annotations   )cbor)_DataClassMapping)
CtapDevice	CtapError)CoseKey)CTAPHID
CAPABILITY)AuthenticatorDataAaguid)IntEnumunique)	dataclassfieldfieldsField)Event)MappingDictAnyListOptionalCallableNreturnDict[int, Any]c                  G  s   dd t | dD S )zConstructs a dict from a list of arguments for sending a CBOR command.
    None elements will be omitted.

    :param params: Arguments, in order, to add to the command.
    :return: The input parameters as a dict.
    c                 S  s   i | ]\}}|d ur||qS N ).0ivr   r   K/var/www/html/env_mimamsha/lib/python3.10/site-packages/fido2/ctap2/base.py
<dictcomp>6   s    zargs.<locals>.<dictcomp>   )	enumerate)paramsr   r   r!   args/   s   r&   c                   @  s   e Zd ZedddZdS )	_CborDataObjectr   r   r   intc                 C  s   t | |d S )Nr#   )r   index)clsr   r   r   r!   _get_field_key:   s   z_CborDataObject._get_field_keyN)r   r   r   r(   )__name__
__module____qualname__classmethodr+   r   r   r   r!   r'   9   s    r'   FT)eqfrozenc                   @  s$  e Zd ZU dZded< eedZded< ej	Z
ded< eedZded	< d
Zded< eedZded< dZded< dZded< eedZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded < dZded!< dZd"ed#< dZded$< dZd%ed&< dS )'Infoar  Binary CBOR encoded response data returned by the CTAP2 GET_INFO command.

    :param _: The binary content of the Info data.
    :ivar versions: The versions supported by the authenticator.
    :ivar extensions: The extensions supported by the authenticator.
    :ivar aaguid: The AAGUID of the authenticator.
    :ivar options: The options supported by the authenticator.
    :ivar max_msg_size: The max message size supported by the authenticator.
    :ivar pin_uv_protocols: The PIN/UV protocol versions supported by the authenticator.
    :ivar max_creds_in_list: Max number of credentials supported in list at a time.
    :ivar max_cred_id_length: Max length of Credential ID supported.
    :ivar transports: List of supported transports.
    :ivar algorithms: List of supported algorithms for credential creation.
    :ivar data: The Info members, in the form of a dict.
    z	List[str]versions)default_factory
extensionsr   aaguidzDict[str, bool]optionsi   r(   max_msg_sizez	List[int]pin_uv_protocolsNOptional[int]max_creds_in_listmax_cred_id_length
transportszOptional[List[Dict[str, Any]]]
algorithmsmax_large_blobFboolforce_pin_change   min_pin_lengthfirmware_versionmax_cred_blob_lengthr   max_rpids_for_min_pinpreferred_platform_uv_attemptsuv_modalityzOptional[Dict]certificationsremaining_disc_credszOptional[List[int]] vendor_prototype_config_commands)r,   r-   r.   __doc____annotations__r   listr5   r   NONEr6   dictr7   r8   r9   r;   r<   r=   r>   r?   rA   rC   rD   rE   rF   rG   rH   rI   rJ   rK   r   r   r   r!   r2   ?   s.   
 r2   c                   @  sB   e Zd ZU dZded< ded< ded< dZd	ed
< dZded< dS )AttestationResponsear  Binary CBOR encoded attestation object.

    :param _: The binary representation of the attestation object.
    :type _: bytes
    :ivar fmt: The type of attestation used.
    :type fmt: str
    :ivar auth_data: The attested authenticator data.
    :type auth_data: AuthenticatorData
    :ivar att_stmt: The attestation statement.
    :type att_stmt: Dict[str, Any]
    strfmtr   	auth_datazDict[str, Any]att_stmtNOptional[bool]ep_attOptional[bytes]large_blob_key)r,   r-   r.   rL   rM   rW   rY   r   r   r   r!   rQ   h   s   
 rQ   c                   @  sr   e Zd ZU dZded< ded< ded< dZd	ed
< dZded< dZded< dZded< dddZ	e
dddZdS )AssertionResponsea  Binary CBOR encoded assertion response.

    :param _: The binary representation of the assertion response.
    :ivar credential: The credential used for the assertion.
    :ivar auth_data: The authenticator data part of the response.
    :ivar signature: The digital signature of the assertion.
    :ivar user: The user data of the credential.
    :ivar number_of_credentials: The total number of responses available
        (only set for the first response, if > 1).
    Mapping[str, Any]
credentialr   rT   bytes	signatureNzOptional[Dict[str, Any]]userr:   number_of_credentialsrV   user_selectedrX   rY   client_param
public_keyr   c                 C  s   | | j| | j dS )a  Verify the digital signature of the response with regard to the
        client_param, using the given public key.

        :param client_param: SHA256 hash of the ClientData used for the request.
        :param public_key: The public key of the credential, to verify.
        N)verifyrT   r^   )selfrb   rc   r   r   r!   rd      s   zAssertionResponse.verify	app_paramr   'AssertionResponse'c                 C  s&   | |t ||jt jj@ |j|jdS )a^  Create an AssertionResponse from a CTAP1 SignatureData instance.

        :param app_param: SHA256 hash of the RP ID used for the CTAP1 request.
        :param credential: Credential used for the CTAP1 request (from the
            allowList).
        :param authentication: The CTAP1 signature data.
        :return: The assertion response.
        )r\   rT   r^   )r   createuser_presenceFLAGUPcounterr^   )r*   rf   r\   authenticationr   r   r!   
from_ctap1   s   zAssertionResponse.from_ctap1)rb   r]   rc   r   )rf   r]   r\   r[   r   rg   )r,   r-   r.   rL   rM   r_   r`   ra   rY   rd   r/   rn   r   r   r   r!   rZ   }   s   
 
	rZ   c                   @  sN  e Zd ZdZeG dd deZd[d\d	d
Zed]ddZ		d^dddd_ddZ
d]ddZ						d`ddddad)d*Zddddbd,d-Z						d`ddddcd<d=Z					ddddddedBdCZdfdDdEZdgdGdHZ			dhdidJdKZ						d`ddddjdOdPZddddbdQdRZ					dddkdWdXZ			dhdidYdZZdS )lCtap2zImplementation of the CTAP2 specification.

    :param device: A CtapHidDevice handle supporting CTAP2.
    :param strict_cbor: Validate that CBOR returned from the Authenticator is
        canonical, defaults to True.
    c                   @  s@   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdS )z	Ctap2.CMDr#   r   rB            	   
            @   A   N)r,   r-   r.   MAKE_CREDENTIALGET_ASSERTIONGET_INFO
CLIENT_PINRESETGET_NEXT_ASSERTIONBIO_ENROLLMENTCREDENTIAL_MGMT	SELECTIONLARGE_BLOBSCONFIGBIO_ENROLLMENT_PRECREDENTIAL_MGMT_PREr   r   r   r!   CMD   s    r   Tdevicer   strict_cborr@   c                 C  s.   |j tj@ s
td|| _|| _|  | _d S )NzDevice does not support CTAP2.)capabilitiesr
   CBOR
ValueErrorr   _strict_cborget_info_info)re   r   r   r   r   r!   __init__   s
   zCtap2.__init__r   r2   c                 C  s   | j S )zGet a cached Info object which can be used to determine capabilities.

        :rtype: Info
        :return: The response of calling GetAuthenticatorInfo.
        )r   re   r   r   r!   info   s   z
Ctap2.infoNeventon_keepalivecmdr(   dataOptional[Mapping[int, Any]]r   Optional[Event]r   Optional[Callable[[int], None]]Mapping[int, Any]c                C  s   t d|}|dur|t|7 }| jtj|||}|d }|dkr't||dd }|s1i S t	|}	| j
rPt|	}
|
|krPtd|  d|
  t|	trW|	S td)av  Sends a CBOR message to the device, and waits for a response.

        :param cmd: The command byte of the request.
        :param data: The payload to send (to be CBOR encoded).
        :param event: Optional threading.Event used to cancel the request.
        :param on_keepalive: Optional function called when keep-alive is sent by
            the authenticator.
        z>BNr   r#   z,Non-canonical CBOR from Authenticator.
Got: z
Expected: zDecoded value of wrong type)structpackr   encoder   callr	   r   r   decoder   r   hex
isinstancer   	TypeError)re   r   r   r   r   requestresponsestatusencdecodedexpectedr   r   r!   	send_cbor   s0   


zCtap2.send_cborc                 C     t | tjjS )zVCTAP2 getInfo command.

        :return: Information about the authenticator.
        )r2   	from_dictr   ro   r   r|   r   r   r   r!   r        zCtap2.get_infopin_uv_protocolsub_cmdkey_agreementpin_uv_paramrX   new_pin_encpin_hash_encpermissionsr:   permissions_rpidOptional[str]c	                C  s,   | j tjjt||||||dd||
|	|
dS )a  CTAP2 clientPin command, used for various PIN operations.

        This method is not intended to be called directly. It is intended to be used by
        an instance of the PinProtocolV1 class.

        :param pin_uv_protocol: The PIN/UV protocol version to use.
        :param sub_cmd: A clientPin sub command.
        :param key_agreement: The keyAgreement parameter.
        :param pin_uv_param: The pinAuth parameter.
        :param new_pin_enc: The newPinEnc parameter.
        :param pin_hash_enc: The pinHashEnc parameter.
        :param permissions: The permissions parameter.
        :param permissions_rpid: The permissions RPID parameter.
        :param event: Optional threading.Event used to cancel the request.
        :param on_keepalive: Optional callback function to handle keep-alive
            messages from the authenticator.
        :return: The response of the command, decoded.
        Nr   )r   ro   r   r}   r&   )re   r   r   r   r   r   r   r   r   r   r   r   r   r!   
client_pin  s"    zCtap2.client_pinNonec                C  s"   | j tjj||d td dS )a
  CTAP2 reset command, erases all credentials and PIN.

        :param event: Optional threading.Event object used to cancel the request.
        :param on_keepalive: Optional callback function to handle keep-alive
            messages from the authenticator.
        r   z!Reset completed - All data erasedN)r   ro   r   r~   loggerr   re   r   r   r   r   r!   reset:  s   zCtap2.resetclient_data_hashr]   rpr[   r_   
key_paramsList[Mapping[str, Any]]exclude_list!Optional[List[Mapping[str, Any]]]r5   Optional[Mapping[str, Any]]r7   enterprise_attestationrQ   c                C  s<   t d t| jtjjt|||||||||	|

||dS )a  CTAP2 makeCredential operation.

        :param client_data_hash: SHA256 hash of the ClientData.
        :param rp: PublicKeyCredentialRpEntity parameters.
        :param user: PublicKeyCredentialUserEntity parameters.
        :param key_params: List of acceptable credential types.
        :param exclude_list: Optional list of PublicKeyCredentialDescriptors.
        :param extensions: Optional dict of extensions.
        :param options: Optional dict of options.
        :param pin_uv_param: Optional PIN/UV auth parameter.
        :param pin_uv_protocol: The version of PIN/UV protocol used, if any.
        :param enterprise_attestation: Whether or not to request Enterprise Attestation.
        :param event: Optional threading.Event used to cancel the request.
        :param on_keepalive: Optional callback function to handle keep-alive
            messages from the authenticator.
        :return: The new credential.
        zCalling CTAP2 make_credentialr   )	r   debugrQ   r   r   ro   r   rz   r&   )re   r   r   r_   r   r   r5   r7   r   r   r   r   r   r   r   r!   make_credentialI  s(   
!zCtap2.make_credentialrp_idrR   
allow_listrZ   c          
      C  s6   t d t| jtjjt|||||||||	dS )a  CTAP2 getAssertion command.

        :param rp_id: The RP ID of the credential.
        :param client_data_hash: SHA256 hash of the ClientData used.
        :param allow_list: Optional list of PublicKeyCredentialDescriptors.
        :param extensions: Optional dict of extensions.
        :param options: Optional dict of options.
        :param pin_uv_param: Optional PIN/UV auth parameter.
        :param pin_uv_protocol: The version of PIN/UV protocol used, if any.
        :param event: Optional threading.Event used to cancel the request.
        :param on_keepalive: Optional callback function to handle keep-alive messages
            from the authenticator.
        :return: The new assertion.
        zCalling CTAP2 get_assertionr   )	r   r   rZ   r   r   ro   r   r{   r&   )
re   r   r   r   r5   r7   r   r   r   r   r   r   r!   get_assertion  s"   
	zCtap2.get_assertionc                 C  r   )zaCTAP2 getNextAssertion command.

        :return: The next available assertion response.
        )rZ   r   r   ro   r   r   r   r   r   r!   get_next_assertion  r   zCtap2.get_next_assertionList[AssertionResponse]c                   s8    j |i |} fddtd|jpdD }|g| S )zuConvenience method to get list of assertions.

        See get_assertion and get_next_assertion for details.
        c                   s   g | ]}   qS r   )r   )r   _r   r   r!   
<listcomp>  s    z(Ctap2.get_assertions.<locals>.<listcomp>r#   )r   ranger`   )re   r&   kwargsfirstrestr   r   r!   get_assertions  s
   

zCtap2.get_assertionssub_cmd_paramsc                 C  sJ   d| j jv rtjj}nd| j jv rtjj}ntd| |t||||S )ag  CTAP2 credentialManagement command, used to manage resident
        credentials.

        NOTE: This implements the current draft version of the CTAP2 specification and
        should be considered highly experimental.

        This method is not intended to be called directly. It is intended to be used by
        an instance of the CredentialManagement class.

        :param sub_cmd: A CredentialManagement sub command.
        :param sub_cmd_params: Sub command specific parameters.
        :param pin_uv_protocol: PIN/UV auth protocol version used.
        :param pin_uv_param: PIN/UV Auth parameter.
        credMgmtcredentialMgmtPreviewz9Credential Management not supported by this Authenticator)	r   r7   ro   r   r   r   r   r   r&   )re   r   r   r   r   r   r   r   r!   credential_mgmt  s   

zCtap2.credential_mgmtmodalityget_modalityrV   c          
   	   C  sT   d| j jv rtjj}	nd| j jv rtjj}	ntd| j|	t||||||||dS )a  CTAP2 bio enrollment command. Used to provision/enumerate/delete bio
        enrollments in the authenticator.

        NOTE: This implements the current draft version of the CTAP2 specification and
        should be considered highly experimental.

        This method is not intended to be called directly. It is intended to be used by
        an instance of the BioEnrollment class.

        :param modality: The user verification modality being used.
        :param sub_cmd: A BioEnrollment sub command.
        :param sub_cmd_params: Sub command specific parameters.
        :param pin_uv_protocol: PIN/UV protocol version used.
        :param pin_uv_param: PIN/UV auth param.
        :param get_modality: Get the user verification type modality.
        	bioEnrolluserVerificationMgmtPreviewz)Authenticator does not support Bio Enrollr   )	r   r7   ro   r   r   r   r   r   r&   )
re   r   r   r   r   r   r   r   r   r   r   r   r!   bio_enrollment  s$   

zCtap2.bio_enrollmentc                C  s   | j tjj||d dS )aq  CTAP2 authenticator selection command.

        This command allows the platform to let a user select a certain authenticator
        by asking for user presence.

        :param event: Optional threading.Event used to cancel the request.
        :param on_keepalive: Optional callback function to handle keep-alive messages
            from the authenticator.
        r   N)r   ro   r   r   r   r   r   r!   	selection  s   zCtap2.selectionoffsetgetsetlengthc              
   C  s   |  tjjt||||||S )aR  CTAP2 authenticator large blobs command.

        This command is used to read and write the large blob array.

        This method is not intended to be called directly. It is intended to be used by
        an instance of the LargeBlobs class.

        :param offset: The offset of where to start reading/writing data.
        :param get: Optional (max) length of data to read.
        :param set: Optional data to write.
        :param length: Length of the payload in set.
        :param pin_uv_protocol: PIN/UV protocol version used.
        :param pin_uv_param: PIN/UV auth param.
        )r   ro   r   r   r&   )re   r   r   r   r   r   r   r   r   r!   large_blobs"  s   zCtap2.large_blobsc                 C  s   |  tjjt||||S )a
  CTAP2 authenticator config command.

        This command is used to configure various authenticator features through the
        use of its subcommands.

        This method is not intended to be called directly. It is intended to be used by
        an instance of the Config class.

        :param sub_cmd: A Config sub command.
        :param sub_cmd_params: Sub command specific parameters.
        :param pin_uv_protocol: PIN/UV auth protocol version used.
        :param pin_uv_param: PIN/UV Auth parameter.
        )r   ro   r   r   r&   )re   r   r   r   r   r   r   r!   config>  s   zCtap2.config)T)r   r   r   r@   )r   r2   r   )
r   r(   r   r   r   r   r   r   r   r   )NNNNNN)r   r(   r   r(   r   r   r   rX   r   rX   r   rX   r   r:   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   )r   r]   r   r[   r_   r[   r   r   r   r   r5   r   r7   r   r   rX   r   r:   r   r:   r   r   r   r   r   rQ   )NNNNN)r   rR   r   r]   r   r   r5   r   r7   r   r   rX   r   r:   r   r   r   r   r   rZ   )r   rZ   )r   r   )NNN)
r   r(   r   r   r   r:   r   rX   r   r   )r   r:   r   r:   r   r   r   r:   r   rX   r   rV   r   r   r   r   r   r   )r   r(   r   r:   r   rX   r   r:   r   rX   r   r:   r   r   )r,   r-   r.   rL   r   r   r   r   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r!   ro      s    
&5:

-
$	3ro   )r   r   ).
__future__r    r   utilsr   ctapr   r   coser   hidr	   r
   webauthnr   r   enumr   r   dataclassesr   r   r   r   	threadingr   typingr   r   r   r   r   r   r   logging	getLoggerr,   r   r&   r(   r'   r2   rQ   rZ   ro   r   r   r   r!   <module>   s.    




(
4