
    <[j5<                    F
   d dl m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
mZmZmZ  ej        e          ZdZdZdZd	Zd
ZdZdZdZdZ G d dej                  Z G d de          Z G d de          Z G d de          Z G d de          Z G d de          Z  G d de          Z! ej"        e          Z# ej"        e          Z$ ej"        e          Z% ej"        e           Z&ej'        Z( ej"        e!          Z)ej*        Z+ej*        Z,ej-        Z.ej/        Z0ej1        Z2ej3        Z4dZ5ej6        Z7ej6        Z8ej6        Z9ej6        Z:ej6        Z;e:Z<e:Z= ej"        e          Z> ej"        e          Z? ej@        dejA        e7ej*        e8ej3         ej"        ejB                  e0          ZC ej@        dejA        e7ej*                  ZDdZEdZFd ZGdZHd ZIdZJdZKd ZLejM        N                    ejO        P                    d!          pd"          ZQejM        N                    ejO        P                    d#          pd$          ZRe$S                    eRd%          ZTdeRjU        _V        e# ej"        ej*                  geRjU        _W        e$eRjX        _V        ej*        ejY        ej3        geRjX        _W        ejZ        eRj[        _V        e%ejY        e0e4geRj[        _W        e.eRj\        _V        e%geRj\        _W        e.eRj]        _V        e.eRj^        _V        ej_        eRj`        _V        e&eRja        _V        g eRja        _W        e(eRjb        _V        e$e2ejZ        geRjb        _W        e7eRjc        _V        e%geRjc        _W        e:geQjd        _W        e>eQje        _V        e)e9geQje        _W        e#eQjf        _V        e>geQjf        _W        deQjg        _V        e>e%geQjg        _W        e,eQjh        _V        eji        geQjh        _W        e7eQjj        _V        e= ej"        eji                  geQjj        _W        e?eQjk        _V        e)e<geQjk        _W        e7eQjl        _V        e?ej3        geQjl        _W        deQjm        _V        e?e&e$geQjm        _W        deQjn        _V        e?e&e$geQjn        _W        e%eQjo        _V        e?e$geQjo        _W        e7eQjp        _V        e?e8e0ej*        e0geQjp        _W        e<eQjq        _V        e;e+geQjq        _W        d& Zr eCer          Zsd' Zt eDet          Zud( Zv G d) d*e          Zwd+ Zxd, Zyd- Zzd. Z{d/ Z|d0 Z}d1 Z~d2 ZdS )3    )annotationsN)EmptyQueue   )
FIDO_USAGEFIDO_USAGE_PAGECtapHidConnectionHidDescriptors   VendorIDs	   ProductIDs   Products   SerialNumbers   PrimaryUsages   PrimaryUsagePages   MaxInputReportSizes   MaxOutputReportSizes   ReportIDc                      e Zd ZdS )_CFTypeN__name__
__module____qualname__     W/home/thesage/.hermes/hermes-agent/venv/lib/python3.11/site-packages/fido2/hid/macos.pyr   r   ,           Dr   r   c                      e Zd ZdS )	_CFStringNr   r   r   r   r   r   0   r   r   r   c                      e Zd ZdS )_CFSetNr   r   r   r   r   r   4   r   r   r   c                      e Zd ZdS )_IOHIDManagerNr   r   r   r   r   r   8   r   r   r   c                      e Zd ZdS )_IOHIDDeviceNr   r   r   r   r   r   <   r   r   r   c                      e Zd ZdS )
_CFRunLoopNr   r   r   r   r   r   @   r   r   r   c                      e Zd ZdS )_CFAllocatorNr   r   r   r   r    r    D   r   r   r    i           IOKitz0/System/Library/Frameworks/IOKit.framework/IOKitCoreFoundationzB/System/Library/Frameworks/CoreFoundation.framework/CoreFoundationkCFRunLoopDefaultModec                ^    ~~~~|                      t          j        ||                     dS )z+Handles incoming IN report from HID device.N)putctypes	string_at)
read_queueresultsenderreport_type	report_idreportreport_lengths          r   _hid_read_callbackr2      s2     	YNN6#FM::;;;;;r   c                H    ~~t                               | j                   d S N)cfCFRunLoopStoprun_loop_ref)
hid_devicer,   r-   s      r   _hid_removal_callbackr9      s$    Z,-----r   c                   t                                           | _        | j        st                              d           dS t
                              | j        | j        t                     t
          	                    | j        t          t          j        |                      d}d}||k     rt                               t          dd          }| j                                         }|t           k    r#|rnBt                              d           |dz  }nt                              d	|           n||k     t
                              | j        | j        t                     dS )
zBinds a device to the thread's run loop, then starts the run loop.

    Args:
    hid_device: The MacOsHidDevice object

    The HID manager requires a run loop to handle Report reads. This thread
    function serves that purpose.
    zFailed to get current run loopNr"   r   r#   Tz6Read queue empty after HANDLE_SOURCE, attempting retryr   z!Unexpected run loop exit code: %d)r5   CFRunLoopGetCurrentr7   loggererroriokitIOHIDDeviceScheduleWithRunLoophandleK_CF_RUNLOOP_DEFAULT_MODE"IOHIDDeviceRegisterRemovalCallbackREMOVAL_CALLBACKr)   	py_objectCFRunLoopRunInModer+   empty K_CF_RUN_LOOP_RUN_HANDLED_SOURCEdebug IOHIDDeviceUnscheduleFromRunLoop)r8   max_retriesretriesrun_loop_run_resultreceived_datas        r   _dev_read_threadrN      sq    !4466J" 5666	((:24M   
,,+V-=j-I-I   KG
K

 33%
 
 '177999"BBB  UVVV1 LL<>QRRR) K

. 
**:24M    r   c                  &    e Zd Zd Zd Zd Zd ZdS )MacCtapHidConnectionc           	        || _         t          |j                  | _        t                              | j        d          }|t          k    rt          d|           t                      | _	        d | _
        t          j        |j        z              | _        t                              | j        | j        | j         j        t           t          j        | j	                             d S )Nr   z)Failed to open device for communication: )
descriptor_handle_from_pathpathr@   r>   IOHIDDeviceOpenK_IO_RETURN_SUCCESSOSErrorr   r+   r7   r)   c_uint8report_size_inin_report_buffer&IOHIDDeviceRegisterInputReportCallbackREGISTERED_READ_CALLBACKrD   )selfrR   r,   s      r   __init__zMacCtapHidConnection.__init__  s    $'
88 &&t{A66(((NfNNOOO "' ! "(*2K!K N N44K!O*$T_--	
 	
 	
 	
 	
r   c           	         t                               | j        | j        | j        j        t          j        dt                    d            d S )Nr   )	r>   r[   r@   rZ   rR   rY   r)   castIO_HID_REPORT_CALLBACK)r]   s    r   closezMacCtapHidConnection.close8  sJ    44K!O*K122	
 	
 	
 	
 	
r   c           	         t                               | j        t          d|t	          |                    }|t
          k    rt          d|           d S )Nr   z"Failed to write report to device: )r>   IOHIDDeviceSetReportr@   K_IO_HID_REPORT_TYPE_OUTPUTlenrV   rW   )r]   datar,   s      r   write_packetz!MacCtapHidConnection.write_packetA  s[    ++K'II
 
 (((GvGGHHH )(r   c                P   	 | j                             d          S # t          $ r t          j        t
          | f          }|                                 |                                 	 | j                             d          cY S # t          $ r t          d          w xY ww xY w)NF)targetargszFailed reading a response)	r+   getr   	threadingThreadrN   startjoinrW   )r]   read_threads     r   read_packetz MacCtapHidConnection.read_packetN  s    		;?&&u--- 	; 	; 	;#*2B$QQQK;**511111 ; ; ;9:::;	;s"    AB%+BB%B!!B%N)r   r   r   r^   rb   rh   rr   r   r   r   rP   rP     sS        
 
 
2
 
 
I I I
; 
; 
; 
; 
;r   rP   c                L   t                               d|d          }t                              | |          }t                               |           |st          d| d          t                               |          t                                           k    r*t          dt                               |                     t          j
                    }t                               |t          t          j        |                    st          d| d          |j        S )z'Reads int property from the HID device.Nr   z
Property 'z' not foundzExpected number type, got zFailed to read property '')r5   CFStringCreateWithCStringr>   IOHIDDeviceGetProperty	CFRelease
ValueErrorCFGetTypeIDCFNumberGetTypeIDrW   r)   c_int32CFNumberGetValueK_CF_NUMBER_SINT32_TYPEbyrefvalue)devkeycf_keytype_refouts        r   get_int_propertyr   [  s    ))$Q77F++C88HLL 86c666777	~~h2#7#7#9#999M2>>(3K3KMMNNN
.

Cx)@&,sBSBSTT :8#8889999r   c                ^   t                               d|d          }t                              | |          }t                               |           |sdS t                               |          t                                           k    r*t          dt                               |                     t          j	        d          }t           
                    ||t          j        |          t                    }|sdS 	 |j                            d          pdS # t          $ r Y dS w xY w)z*Reads string property from the HID device.Nr   zExpected string type, got    zutf-8)r5   ru   r>   rv   rw   ry   CFStringGetTypeIDrW   r)   create_string_bufferCFStringGetCStringsizeof CF_STRING_BUILTIN_ENCODINGS_UTF8r   decodeUnicodeDecodeError)r   r   r   r   r   rets         r   get_string_propertyr   m  s   ))$Q77F++C88HLL t	~~h2#7#7#9#999M2>>(3K3KMMNNN

%c
*
*C


#v}S))+K C  ty((0D0   tts   D 
D,+D,c                    t                               |           }t          j                    }t                               |t          j        |                    }|t          k    rt          d|           |j        S )zObtains the unique IORegistry entry ID for the device.

    Args:
    handle: reference to the device

    Returns:
    A unique ID for the device, obtained from the IO Registry
    z&Failed to obtain IORegistry entry ID: )	r>   IOHIDDeviceGetServicer)   c_uint64!IORegistryEntryGetRegistryEntryIDr~   rV   rW   r   )r@   io_service_objentry_idr,   s       r   get_device_idr     su     0088N  H44X.. F $$$GvGGHHH>r   c                "   t          j        t          |                     }t                              |          }t                              t          |          }|st          d|  d          t                              t          |          S )Nz
Device ID z, does not match any HID device on the system)
r)   r   intr>   IORegistryEntryIDMatchingIOServiceGetMatchingServiceK_IO_MASTER_PORT_DEFAULTrW   IOHIDDeviceCreateK_CF_ALLOCATOR_DEFAULT)rT   r   matching_dictdevice_entrys       r   rS   rS     s    s4yy))H33H==M44 - L  WU4UUUVVV""#9<HHHr   c                     t          |           S r4   )rP   )rR   s    r   open_connectionr     s    
+++r   c           	        t          | t                    }t          | t                    }|t          k    r|t          k    rt          |           }t          | t                    }t          | t                    }t          | t                    }t          | t                    }t          | t                    }t          | t                    }	t          t          |          ||||	||          S t          d          )NzNot a CTAP device)r   &HID_DEVICE_PROPERTY_PRIMARY_USAGE_PAGE!HID_DEVICE_PROPERTY_PRIMARY_USAGEr   r   r   HID_DEVICE_PROPERTY_VENDOR_IDHID_DEVICE_PROPERTY_PRODUCT_IDr   HID_DEVICE_PROPERTY_PRODUCT!HID_DEVICE_PROPERTY_SERIAL_NUMBER)HID_DEVICE_PROPERTY_MAX_INPUT_REPORT_SIZE*HID_DEVICE_PROPERTY_MAX_OUTPUT_REPORT_SIZEr
   strrx   )
r@   
usage_pageusage	device_idvidpidproductserialsize_insize_outs
             r   _get_descriptor_from_handler     s    !&*PQQJV%FGGE_$$*)<)<!&))	v'DEEv'EFF%f.IJJ$V-NOO"6+TUU#F,VWW	NNCgx&
 
 	
 (
)
))r   c                :    t          t          |                     S r4   )r   rS   )rT   s    r   get_descriptorr     s    &'8'>'>???r   c                    t                               d d          } | st          d          	 t                               | d            t                               |           }|st          d          	 t                               |          }t          |z              }t                               ||           g }|D ]7}	 t          |          }|	                    |           (# t          $ r Y 4w xY w|t                              |           t                              |            S # t                              |           w xY w# t                              |            w xY w)Nr   z&Unable to obtain HID manager referencez)Failed to obtain devices from HID manager)r>   IOHIDManagerCreaterW   IOHIDManagerSetDeviceMatchingIOHIDManagerCopyDevicesCFSetGetCountIO_HID_DEVICE_REFCFSetGetValuesr   appendrx   r5   rw   )hid_mgrdevice_set_refnumdevicesdescriptorsr@   rR   s          r   list_descriptorsr     sr   &&tQ//G @>???++GT::: 66w?? 	GEFFF	)%%n55C(3.11G  999 K!  !<V!D!DJ&&z2222!   HLL(((
W LL((((
WsI   AE 5AD- $C'&D- '
C41D- 3C44D- 8E -E		E E()
__future__r   r)   ctypes.utilloggingrm   queuer   r   baser   r   r	   r
   	getLoggerr   r<   r   r   r   r   r   r   r   r   HID_DEVICE_PROPERTY_REPORT_ID	Structurer   r   r   r   r   r   r    POINTER
CF_SET_REFCF_STRING_REFCF_TYPE_REFCF_RUN_LOOP_REFr{   CF_RUN_LOOP_RUN_RESULTCF_ALLOCATOR_REFc_void_pCF_DICTIONARY_REFCF_MUTABLE_DICTIONARY_REFc_ulong
CF_TYPE_IDc_longCF_INDEXc_doubleCF_TIME_INTERVALc_uint32CF_STRING_ENCODINGr   c_uint	IO_RETURNIO_HID_REPORT_TYPEIO_OPTION_BITSIO_OBJECT_TMACH_PORT_TIO_SERVICE_TIO_REGISTRY_ENTRY_TIO_HID_MANAGER_REFr   	CFUNCTYPErD   rX   ra   IO_HID_CALLBACKr}   r   r   re   rV   K_CF_RUN_LOOP_RUN_STOPPEDK_CF_RUN_LOOP_RUN_TIMED_OUTrG   cdllLoadLibraryutilfind_libraryr>   r5   in_dllrA   r   restypeargtypesru   c_char_pc_boolr   ry   rz   r   c_intr|   r;   rE   rw   IOObjectReleaser   r   r   r   r   r   r   IOHIDDeviceCloser?   rI   rv   rd   r   r2   r\   r9   rC   rN   rP   r   r   r   rS   r   r   r   r   r   r   r   <module>r      s  $ # " " " " "                   O O O O O O O O O O O O		8	$	$ !, !- ( $3 !$3 !)< &,A )-C * + 	 	 	 	 	f 	 	 		 	 	 	 	 	 	 		 	 	 	 	W 	 	 		 	 	 	 	G 	 	 		 	 	 	 	7 	 	 		 	 	 	 	 	 	 		 	 	 	 	7 	 	 	 V^F##
y))fnW%% &.,, !6>,// O "O ^
=? _ #,  M	] mm! #V^M22 "FN<00 ))

O
OFN6>""	 	  #&"4)99foVV        #$   	
KW%% :9	 	 [
K-.. LK  *005LMM  !  (.&.*I*IJ  '4  $
O
O
O)  %
 !'  
O	"   $ &- )  )  $l  !0  "$   6  "/1A6=!Q    $ "-  #5   %5~$F  !(2  %*<)=  &.2 # +0BK/P # ,*C  ',2O+<  (2; ' /FN6?##4 ' 0
 #4  $4l#C   !*  #4fo"F  /3 $ ,1 $ -
 26 & .3 & /
 (3  $):M(J  %%.  "
O'  # -9 ! ).9;L-M ! *< < < 212DEE . . .
 #?#899 4 4 4n:; :; :; :; :;, :; :; :;z  $  0  *
I 
I 
I, , ,* * *"@ @ @    r   