
    di/                        d 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lmZmZ ddlT ddlT ddlT ddlT ddlT ddlmZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZ  edg  e ddg d           e ddg d           e ddg d           e ddg d           e ddg d           e ddg d           e ddg d           e ddg d           e ddg d           e d d!g d           e d"d#g d           e d$d%g d           e d&d'g d           e d(d)g d           e d*d+g d           e d,d-g d           e d.d/g d           e d0d1g d           e d0d2g d           e d3d4g d           e d5d6g d           e d7d8d9g           e d:d;d9g           e d<d=d9g           e d>d?d9g           e d@dAg d           e dBdCg d           e dDdEg d           e dFdGd9g           e dHdIg d           e dJdKd9g           e dLdMg d           e dNdOdPdQg           e dRdSdPdQg           e d,d-dPdQg           e d.d/dPdQg           e dTdUdPdQg           e dVdWdPdQg           e dXdYdPdQg           e dZd[d\d]g                    Z! ee"d^d_d-d`d8a          Z# G db dce$dde          Z% G df dge$dhe          Z& G di dje$dke          Z' G dl dme$dne          Z( G do dpe$d4e          Z) G dq dre$dde          Z* G ds dte$dhe          Z+ G du dve$dke          Z, G dw dxe$dne          Z- G dy dze$d4e          Z. G d{ d|e$d}e          Z/ G d~ de$de          Z0 G d de$de          Z1 G d de$d1e          Z2 G d de$d2e          Z3 G d de$dMe          Z4 G d de$de          Z5 G d de$d;e          Z6 G d de$de          Z7 G d de$de*e+e,e-e.e/e0e1e2e4e5e6e7g          Z8 G d de$de          Z9 G d de$de          Z: G d de$de          Z; G d de$d1e          Z< G d de$de          Z= G d de$de          Z> G d de$de          Z? G d de$dne          Z@ G d de$de>e?e@g          ZA G d de$de%e&e'e(e)e8e9e:e;e<e=eAg          ZBd ZCd ZD G d de$dde          ZE G d de$dhe          ZF G d de$dke          ZG G d de$dne          ZH G d de$deEeFeGeHg          ZI G d deJ          ZK G d deJ          ZL G dÄ deJ          ZM eNd eMdh           eMdk           eMdn           eMd4           eMd}           eMd           eMd           eMd1           eMd2           eMd           eMd           eMd           eMdƦ           eMdǦ           eMdȦ          gɦ          ZOeO eK            z  ZPeO eL            z  ZQ ei d^dʓd_d˓dd͓d-dΓddГddғddԓd`dՓddדddٓddۓddݓddߓdddhddkddndddddddddddd
          ZR G d deJ          ZS G d deJ          ZT eUddd          ZV eUddd          ZW G d deJ          ZX eNddeVeW eT             eTd           eS            gɦ          ZY eXddeY          ZZ eNd deVeW eT             eTd           eS            gɦ          Z[ eXdde[          Z\ eNddeVeW eT             eTd           eS            gɦ          Z] eXdde]          Z^ eNdd	eVeW eT             eTd           eS            eZe\e^gɦ          Z_ G d
 de`          Za G d de`          Zb G d dec          Zd G d de          ZedS (  a  Utilities / Functions related to ETSI TS 102 221, the core UICC spec.

(C) 2021-2024 by Harald Welte <laforge@osmocom.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
    )bidict)SelectConstBitStructInt16ub	FlagsEnumGreedyStringValidationError)OptionalComputed)*)CardProfile)	iso7816_4)AddonSIMEF_ICCIDEF_PL)	AddonGSMR)	AddonRUIMz
TS 102 22xSELECT   )0X4X6XSTATUS   )8XCXEXzREAD BINARY   zUPDATE BINARY   zREAD RECORD   zUPDATE RECORD   zSEARCH RECORD   INCREASE2   zRETRIEVE DATA   zSET DATA   z
VERIFY PIN    z
CHANGE PIN$   zDISABLE PIN&   z
ENABLE PIN(   zUNBLOCK PIN,   zDEACTIVATE FILE   zACTIVATE FILED   AUTHENTICATE      zGET CHALLENGE   zTERMINAL CAPABILITY   zTERMINAL PROFILE   80ENVELOPE   FETCH   zTERMINAL RESPONSE   zMANAGE CHANNELp   zMANAGE SECURE CHANNELs   zTRANSACT DATAu   zSUSPEND UICCv   zGET IDENTITYx   zEXCHANGE CAPABILITIESz   zGET RESPONSE   zCREATE FILE   r   r   zDELETE FILE   zTERMINATE DF   zTERMINATE EF   zTERMINATE CARD USAGE   zRESIZE FILE   r   r            abcdec                   &    e Zd Z ed          ZdS )FileSizerJ   minlenN__name__
__module____qualname__GreedyInteger
_construct     >/home/jenkins/workspace/simtester-sanitize/pySim/ts_102_221.pyrS   rS   X            a(((JJJr]   rS      tagc                   &    e Zd Z ed          ZdS )TotalFileSizerJ   rT   NrV   r\   r]   r^   rd   rd   \   r_   r]   rd      c                   "   e Zd Zddddddddfddd	d
ddddfddddddddfddddddddfgZ G d de          Z e e ede	          de
z  d e ed ed                              z  d ed          z             e ede	          de
z  d e ed          ddd          z  d e ed          dddd          z                      Z edez   ed           d! ee          z  d" ee          z            ZdS )#FileDescriptor82027921T
working_efber_tlv)	shareable	file_type	structureN)file_descriptor_byte
record_len
num_of_rec82027821dfno_info_given82024121transparent82054221006e05linear_fixedn      c                       e Zd Zd Zd ZdS )FileDescriptor.BerTlvAdapterc                      |dk    rdS t           )N9   rj   r   selfobjcontextpaths       r^   _decodez$FileDescriptor.BerTlvAdapter._decodeh   s    d{{ y!!r]   c                      |dk    rdS t           )Nrj   r}   r~   r   s       r^   _encodez$FileDescriptor.BerTlvAdapter._encodel   s    it!!r]   NrW   rX   rY   r   r   r\   r]   r^   BerTlvAdapterr{   g   s2        	" 	" 	"	" 	" 	" 	" 	"r]   r   r   rk   rm   r}      rl      rI      )ri   internal_efrr   rJ   )rs   ru   rw   cyclicrn      !ro   rp   )rW   rX   rY   _test_de_encodeAdapterr   r   	BitStructr   r   FlagBitsIntegerr   EnumFDBr   	COptionalr   Int8ubr[   r\   r]   r^   rg   rg   `   sZ       
tR^mv0x0x  IM  ]a  c  c  	e
tRVet0v0v  GK  [_  a  a  	b
tR^mz0|0|  MQ  ae  g  g  	i
TXd  tB  7D  7D  TW  gh  j  j  	l	O" " " " " " " " &55C==+d*:KV[V[\`bmbmnobpbpVqVqHrHr<rt  AI  AI  JV  AW  AW  uW  X  X55C==+d*:K[[YZ^^hiwx}~HHH<&ttKKNN!YZijst'u'u'uuw w C .s2EE'NN$YYw%7%77iiPVFWFW9WY YJJJr]   rg      c                       e Zd ZeZdS )FileIdentifierNrW   rX   rY   GreedyBytesr[   r\   r]   r^   r   r   y           JJJr]   r      c                       e Zd ZeZdS )DfNameNr   r\   r]   r^   r   r   }   r   r]   r   c                       e Zd ZeZdS )UiccCharacteristicsNr   r\   r]   r^   r   r      r   r]   r   c                   :    e Zd Z edez  dez  dez            ZdS )ApplicationPowerConsumptionvoltage_classpower_consumption_mareference_freq_100kNrW   rX   rY   r   SupplyVoltageClassesr   r[   r\   r]   r^   r   r      s7        (<<.v5-f46 6JJJr]   r   c                       e Zd ZeZdS )MinApplicationClockFrequencyN)rW   rX   rY   r   r[   r\   r]   r^   r   r      s        JJJr]   r   c                   "    e Zd Z e            ZdS )AvailableMemoryNrV   r\   r]   r^   r   r              JJJr]   r   c                   (    e Zd Z eed          ZdS )FileDetailsrI   )der_coding_onlyNrW   rX   rY   r	   Byter[   r\   r]   r^   r   r      s"        4333JJJr]   r   c                   "    e Zd Z e            ZdS )ReservedFileSizeNrV   r\   r]   r^   r   r      r   r]   r      c                   "    e Zd Z e            ZdS )MaximumFileSizeNrV   r\   r]   r^   r   r      r   r]   r      c                   (    e Zd Z eed          ZdS )SupportedFilesystemCommandsrI   )terminal_capabilityNr   r\   r]   r^   r   r      s"        4Q777JJJr]   r      c                   z    e Zd Z ed ed          z  dez  d e ed          dddd	          z            Zd
S )!SpecificUiccEnvironmentConditionsrfur.   high_humidity_supportedtemperature_classr   r   rI   rJ   )standardclass_Aclass_Bclass_CN)	rW   rX   rY   r   BitsRFUr   r   r   r[   r\   r]   r^   r   r      s`        5+4T9.ttKKNNQXYcdno/p/p/ppr rJJJr]   r   c                       e Zd ZeZdS )Platform2PlatformCatSecuredApduNr   r\   r]   r^   r   r      r   r]   r   c                   *    e Zd Z eedd          ZdS )SpecialFileInfor`   @   )high_update_activity'readable_and_updatable_when_deactivatedNr   r\   r]   r^   r   r      s%        4ddhiiiJJJr]   r   c                       e Zd ZeZdS )FillingPatternNr   r\   r]   r^   r   r               JJJr]   r      c                       e Zd ZeZdS )RepeatPatternNr   r\   r]   r^   r   r      r   r]   r   c                   .    e Zd Z eedddd          ZdS )ToolkitAccessConditionsrI   rJ   r.   rK   )
rfm_createrfm_delete_terminateother_applet_createother_applet_delete_terminateNr   r\   r]   r^   r   r      s0        4AA[\9:< < <JJJr]   r      c                       e Zd ZdS )ProprietaryInformationNrW   rX   rY   r\   r]   r^   r   r      s         	Dr]   r      rb   nestedc                       e Zd ZeZdS )SecurityAttribCompactNr   r\   r]   r^   r   r      r   r]   r      c                       e Zd ZeZdS )SecurityAttribExpandedNr   r\   r]   r^   r   r      r   r]   r      c                   D    e Zd Z ed ed          z  dez            ZdS )SecurityAttribReferencedef_arr_file_idrJ   ef_arr_record_nrN)rW   rX   rY   r   Bytesr   r[   r\   r]   r^   r   r      s3        (q13Ef3LMMJJJr]   r      c                   d    e Zd Z G d de          Z e e ed                              ZdS )ShortFileIdentifierc                       e Zd Zd Zd ZdS )"ShortFileIdentifier.Shift3RAdapterc                 >    t                               |d          dz	  S )Nbigr   )int
from_bytesr   s       r^   r   z*ShortFileIdentifier.Shift3RAdapter._decode   s    >>#u--22r]   c                 R    t          |          dz  }|                    dd          S )Nr   rI   r   )r   to_bytes)r   r   r   r   vals        r^   r   z*ShortFileIdentifier.Shift3RAdapter._encode   s%    c((a-C<<5)))r]   Nr   r\   r]   r^   Shift3RAdapterr      s2        	3 	3 	3	* 	* 	* 	* 	*r]   r   rI   N)rW   rX   rY   r   r   r   r   r[   r\   r]   r^   r   r      s[        * * * * * * * * >>%%((3344JJJr]   r   c                   &    e Zd ZdgZdefdZd ZdS )LifeCycleStatusInteger)8a0105operational_activateddoc                     t                               |d          }|dk    rd}n8|dk    rd}n/|dk    rd}n&|dz  dk    rd	}n|dz  d
k    rd}n|dz  dk    rd}n|}|| _        | j        S )Nr   r   no_informationrI   creationr   initializationry   r   r.   operational_deactivatedrB   termination)r   r   decoded)r   r   lcsirets       r^   _from_bytesz"LifeCycleStatusInteger._from_bytes   s    ~~b%((4<<"CCT\\CCT\\"CCD[D  )CCD[D  +CCD[D  CCC|r]   c                    | j         dk    rdS | j         dk    rdS | j         dk    rdS | j         dk    rdS | j         d	k    rd
S | j         dk    rdS t          | j         t                    r| j                             dd          S t          )Nr       r     r     r      r     r     rI   r   )r  
isinstancer   r   
ValueError)r   s    r^   	_to_bytesz LifeCycleStatusInteger._to_bytes  s    <+++7<:%%7<+++7<2227<4447<=((7dlC(( 	3<((E222r]   N)rW   rX   rY   r   bytesr  r  r\   r]   r^   r   r      sH        -Oe    $    r]   r      c                       e Zd ZeZdS )PS_DONr   r\   r]   r^   r  r    r   r]   r     c                       e Zd ZeZdS )UsageQualifier_DONr   r\   r]   r^   r  r    r   r]   r     c                       e Zd ZeZdS )KeyReferenceN)rW   rX   rY   r   r[   r\   r]   r^   r  r    s        JJJr]   r  c                       e Zd ZdS )PinStatusTemplate_DONr   r\   r]   r^   r  r    s        Dr]   r     c                       e Zd ZdS )FcpTemplateNr   r\   r]   r^   r!  r!    s        
 	Dr]   r!  b   c                 N     d  fd|                                 D             S )Nc                     || v r| |         S |S Nr\   )inmapkeys     r^   newkeyztlv_key_replace.<locals>.newkey%  s    %<<:Jr]   c                 B    i | ]} |d                    |d         S r   rI   r\   ).0rP   r&  r(  s     r^   
<dictcomp>z#tlv_key_replace.<locals>.<dictcomp>*  s/    >>>!FF5!A$1>>>r]   items)r&  indatar(  s   ` @r^   tlv_key_replacer0  $  s:      
 ?>>>>v||~~>>>>r]   c                 N     d  fd|                                 D             S )Nc                 0    || v r | |         |          S |S r%  r\   )r&  r'  r   s      r^   newvalz!tlv_val_interpret.<locals>.newval.  s"    %<<5:c??"Jr]   c           	      P    i | ]"}|d           |d          |d                   #S r*  r\   )r+  rP   r&  r3  s     r^   r,  z%tlv_val_interpret.<locals>.<dictcomp>3  s5    DDDAaD&&!ad++DDDr]   r-  )r&  r/  r3  s   ` @r^   tlv_val_interpretr5  -  s;      
 EDDDDV\\^^DDDDr]   c                   :    e Zd Z edez  dez  dez            ZdS )TerminalPowerSupplyused_supply_voltage_classmaximum_available_power_supplyactual_used_freq_100kNr   r\   r]   r^   r7  r7  6  s8        34HH8?/68 8JJJr]   r7  c                       e Zd ZeZdS )ExtendedLchanTerminalSupportNr   r\   r]   r^   r<  r<  <  r   r]   r<  c                   (    e Zd Z eed          ZdS )AdditionalInterfacesSupportrI   )uicc_clfNrW   rX   rY   r	   r   r[   r\   r]   r^   r>  r>  @  s"        6D111JJJr]   r>  c                   6    e Zd Z eedddddddd		  	        Zd
S )AdditionalTermCapEuiccrI   rJ   r.   rK   r5   r)   r   r`   )lui_dlpd_dlds_d
lui_e_scwsmetadata_update_alertingenterprise_capable_device	lui_e_e4elprNr@  r\   r]   r^   rB  rB  D  s;        6TRV4859%)#	% % %JJJr]   rB  c                       e Zd ZdS )TerminalCapabilityNr   r\   r]   r^   rL  rL  L  s        Dr]   rL     c                   0     e Zd Z fdZdefdZd Z xZS )	_AM_DO_DFc                 P    t                                          ddd           d S Naccess_modezAccess Moder`   ra   super__init__r   	__class__s    r^   rU  z_AM_DO_DF.__init__R  (    4@@@@@r]   r   c                    g }t          |          dk    rt          d          |d         }|dz  dk    rh|dz  r|                    d           |dz  r|                    d           |d	z  r|                    d
           |dz  r|                    d           |dz  r|                    d           |dz  r|                    d           |dz  r|                    d           || _        d S )NrI   ,We only support single-byte AMF inside AM-DOr   r`   r   delete_filer)   terminate_dfr5   activate_filerK   deactivate_filer.   create_file_dfrJ   create_file_efdelete_file_childlenr  appendr  r   r   resamfs       r^   r   z_AM_DO_DF.from_bytesU  s   r77a<<KLLLe:??Tz *

=)))Tz +

>***Tz ,

?+++Tz .

,---: 	)JJ'(((: 	)JJ'(((: 	,JJ*+++r]   c                     d}d| j         v r|dz  }d| j         v r|dz  }d| j         v r|dz  }d| j         v r|d	z  }d
| j         v r|dz  }d| j         v r|dz  }d| j         v r|dz  }|                    dd          S )Nr   r[  r   r\  r)   r]  r5   r^  rK   r_  r.   r`  rJ   ra  rI   r   r  r   r   r   s     r^   r   z_AM_DO_DF.to_bytesl  s    DL((4KCT\))4KCdl**4KC,,4KCt|++4KCt|++4KC$,..4KC||Au%%%r]   rW   rX   rY   rU  r  r   r   __classcell__rW  s   @r^   rO  rO  Q  sg        A A A A AU    .& & & & & & &r]   rO  c                   4     e Zd ZdZ fdZdefdZd Z xZS )	_AM_DO_EFz+ISO7816-4 9.3.2 Table 18 + 9.3.3.1 Table 31c                 P    t                                          ddd           d S rQ  rS  rV  s    r^   rU  z_AM_DO_EF.__init__  rX  r]   r   c                    g }t          |          dk    rt          d          |d         }|dz  dk    rh|dz  r|                    d           |dz  r|                    d           |d	z  r|                    d
           |dz  r|                    d           |dz  r|                    d           |dz  r|                    d           |dz  r|                    d           || _        d S )NrI   rZ  r   r`   r   r[  r)   terminate_efr5   activate_file_or_recordrK   deactivate_file_or_recordr.   write_appendrJ   update_eraseread_search_comparerb  re  s       r^   r   z_AM_DO_EF.from_bytes  s   r77a<<KLLLe:??Tz *

=)))Tz +

>***Tz 6

4555Tz 8

6777: 	'JJ~&&&: 	'JJ~&&&: 	.JJ,---r]   c                     d}d| j         v r|dz  }d| j         v r|dz  }d| j         v r|dz  }d| j         v r|d	z  }d
| j         v r|dz  }d| j         v r|dz  }d| j         v r|dz  }|                    dd          S )Nr   r[  r   rr  r)   rs  r5   rt  rK   ru  r.   rv  rJ   rw  rI   r   ri  rj  s     r^   r   z_AM_DO_EF.to_bytes  s    DL((4KCT\))4KC$444KC&$,664KCT\))4KCT\))4KC DL004KC||Au%%%r]   	rW   rX   rY   __doc__rU  r  r   r   rl  rm  s   @r^   ro  ro    sm        55A A A A AU    .& & & & & & &r]   ro  c                   :     e Zd ZdZ fdZdefdZd Zd Z xZ	S )_AM_DO_CHDRz?Command Header Access Mode DO according to ISO 7816-4 Table 32.c                 P    t                                          dd|           d S )Ncommand_headerzCommand Header Descriptionra   rS  r   rb   rW  s     r^   rU  z_AM_DO_CHDR.__init__  s*    )+GSQQQQQr]   r   c                     i }d}| j         dz  r||         |d<   |dz  }| j         dz  r||         |d<   |dz  }| j         dz  r||         |d<   |dz  }| j         dz  r||         |d	<   |dz  }|| _        d S )
Nr   rK   CLArI   r.   INSrJ   P1P2)rb   r  )r   r   rf  is       r^   r   z_AM_DO_CHDR.from_bytes  s    8d? 	ACJFA8d? 	ACJFA8d? 	1CIFA8d? 	1CIFAr]   c                 z    d}d| j         v r|dz  }d| j         v r|dz  }d| j         v r|dz  }d| j         v r|d	z  }|S )
z7Override to encode the tag, as it depends on the value.r`   r  rK   r  r.   r  rJ   r  rI   r  )r   rb   s     r^   _compute_tagz_AM_DO_CHDR._compute_tag  sd    DL  4KCDL  4KC4<4KC4<4KC
r]   c                 j   t                      }d| j        v r |                    | j        d                    d| j        v r |                    | j        d                    d| j        v r |                    | j        d                    d| j        v r |                    | j        d                    |S )Nr  r  r  r  )	bytearrayr  rd  )r   rf  s     r^   r   z_AM_DO_CHDR.to_bytes  s    kkDL  JJt|E*+++DL  JJt|E*+++4<JJt|D)***4<JJt|D)***
r]   )
rW   rX   rY   rz  rU  r  r   r  r   rl  rm  s   @r^   r|  r|    s|        IIR R R R RU    "  
 
 
 
 
 
 
r]   r|  
am_do_chdr         )membersPIN1PIN2r   PIN3PIN4ry   PIN5r   PIN6r   PIN7PIN8
   ADM1   ADM2   ADM3   ADM4   ADM5   UNIVERSAL_PIN2PIN12PIN22PIN32PIN42PIN52PIN62PIN72PIN8ADM6ADM7ADM8ADM9ADM10)
r3   r   r   r   r1   r  r   r   r  r  c                   4     e Zd ZdZ fdZdefdZd Z xZS )CRT_DOz2Control Reference Template as per TS 102 221 9.5.1c                 P    t                                          ddd           d S )Ncontrol_reference_templatezControl Reference Templater   ra   rS  rV  s    r^   rU  zCRT_DO.__init__  s;    554 	 	A 	A 	A 	A 	Ar]   r   c                 B   t          |          dk    rt          d|z            |d         dk    s|d         dk    rt          d|z            |dd         d	k    rt          d
|z            |dd         | _        t          |d                  | _        |dd         S )z'Decode a Control Reference Template DO.r   zUnsupported CRT DO length: %sr   r   rI   z+Unsupported Key Ref Tag or Len in CRT DO %sr   N   z3Unsupported Usage Qualifier Tag or Len in CRT DO %srJ   )rc  r  encoded	pin_namesr  )r   r   s     r^   r   zCRT_DO.from_bytes  s    r77a<<<b@AAAa5D==BqETMMJROPPPabb6_$$RUWWXXX!A#w A'!""vr]   c                 h    t           j        | j                 }d|                    dd          z   dz   S )Ns   rI   r   r  )r  inverser  r   )r   pins     r^   r   zCRT_DO.to_bytes  s/    -S\\!U333oEEr]   ry  rm  s   @r^   r  r    st        <<A A A A A
U 
 
 
 
F F F F F F Fr]   r  c                   2     e Zd Zd fd	ZdefdZd Z xZS )SecCondByte_DO   c                 N    t                                          d|           d S )Nsecurity_condition_bytera   rS  r  s     r^   rU  zSecCondByte_DO.__init__$  s'    2<<<<<r]   binaryc                 d   t          |          dk    rt          |d         }|dk    rd}|dk    rd}g }|dz  rd}nd}|d	z  r|                    d
           |dz  r|                    d           |dz  r|                    d           d|i}t          |          dk    r||d<   || _        d S )NrI   r   always   neverr`   andorr   secure_messagingr)   external_authr5   	user_authmode
conditionsrb  )r   r  inbcondrf  rds         r^   r   zSecCondByte_DO.from_bytes'  s    v;;!Qi!88D$;;D: 	DDD: 	+JJ)***: 	(JJ''': 	$JJ{###d^s88a<<"B|r]   c                 D   | j         d         }|dk    rd}nu|dk    rd}nld}|dk    r|dz  }n|dk    rnt          d	|z            | j         d
         D ]7}|dk    r|dz  }|dk    r|dz  }|dk    r|dz  }&t          d|z            |                    dd          S )Nr  r  r   r  r  r  r`   r  zUnknown mode %sr  r  r   r  r)   r  r5   zUnknown condition %srI   r   )r  r  r   )r   r  rf  rO   s       r^   r   zSecCondByte_DO.to_bytes?  s    |F#8CCW__CCCu}}t !2T!9:::\,/ A A***4KCC/))4KCC+%%4KCC$%;a%?@@@||Au%%%r]   )r  rk  rm  s   @r^   r  r  #  sg        = = = = = =    0& & & & & & &r]   r  r  Alwaysr  Never   c                   >     e Zd ZdZ fdZdedefdZdefdZ xZ	S )	Nested_DOz*A DO that nests another DO/Choice/Sequencec                 \    t                                          ||           || _        d S )Nra   )rT  rU  children)r   namerb   choicerW  s       r^   rU  zNested_DO.__init__`  s+    3'''r]   r  returnc                     |}g | _         |r9| j                            |          \  }}| j                             |           |9| j         S r%  )r  r  decoderd  )r   r  	remainderrcs       r^   r   zNested_DO.from_bytesd  sY    	 	$ M00;;MB	L###  	$ |r]   c                 T      fd j         D             }d                    |          S )Nc                 D    g | ]}j                             |          S r\   )r  encode)r+  rP   r   s     r^   
<listcomp>z&Nested_DO.to_bytes.<locals>.<listcomp>m  s)    AAAq4=''**AAAr]   r]   )r  join)r   r  s   ` r^   r   zNested_DO.to_bytesl  s0    AAAADLAAAxx   r]   )
rW   rX   rY   rz  rU  r  listr   r   rl  rm  s   @r^   r  r  ]  s{        44     4    !% ! ! ! ! ! ! ! !r]   r  or_templatezOR-Template   r     and_templatezAND-Templater     not_templatezNOT-Templatenot   security_conditionzSecurity Conditionc                   $    e Zd Zddd ed          iddid ed          igifd	dd ed
          iddigifgZ G d ded          Z G d dedej        eej	        ej
        ej        ej        ej        ej        g          Zd fd	Z xZS )EF_DIRV61294f10a0000000871002ffffffff890709000050055553696d31730ea00c80011781025f608203454150application_templateapplication_id a0000000871002ffffffff8907090000application_labelUSim1discretionary_templatea00c80011781025f608203454150661194f10a0000000871004ffffffff890709000050054953696d31 a0000000871004ffffffff8907090000ISim1c                   $    e Zd Z ed          ZdS )EF_DIR.ApplicationLabelasciiN)rW   rX   rY   r
   r[   r\   r]   r^   ApplicationLabelr    s        !\'**


r]   r  P   ra   c                       e Zd ZdS )EF_DIR.ApplicationTemplateNr   r\   r]   r^   ApplicationTemplater    s        
 	r]   r  a   r   2f00   EF.DIRApplication Directoryc                 v    t                                          ||||d           t          j        | _        d S )N)ry   6   )sfidr  descrec_len)rT  rU  r  r  _tlvr   fidr
  r  r  rW  s        r^   rU  zEF_DIR.__init__  s4    4dwOOO.			r]   )r  r  r  r  )rW   rX   rY   h2br   
BER_TLV_IEr  r   ApplicationIdFileReferenceCommandApduDiscretionaryDataDiscretionaryTemplateURLApplicationRelatedDOSetr  rU  rl  rm  s   @r^   r  r    sP       
b"(8##>`:a:a&c(;W&F(@##FdBeBe&g%j l	

 C"(8##>`:a:a&c(;W&F%I K	

O+ + + + +:4 + + + +    jd&/&=?OQZQh&/&;Y=X&/&Ey}&/&G&I   / / / / / / / / / /r]   r  c                        e Zd Zdddgiddigdddgidd	igdd
dgidd	igdddiiddiggfdddgidd	igddgidd	igdddgiddigdddiiddiggfgZd fd	Zedefd            Zd Zd Z	 e
d           G d de                      Z xZS ) EF_ARR@800101a40683010a950108800106900080016097008401d4a40683010a950108rR  rw  r  r  ru  rv  r  Nr[  rr  r  r~  r  rH   @80010190008001029700800118a40683010a9501088401d4a40683010a950108rs  rt  2f06r   EF.ARRAccess Rule Referencec                     t                                          ||||           | xj        |                                 gz  c_        d S )N)r
  r  r  )rT  rU  shell_commandsAddlShellCommandsr  s        r^   rU  zEF_ARR.__init__  sM    4d>>> 6 6 8 899r]   inpc                    d }i }| D ]}|d         }|d         } ||          }d|v r|d         D ]}|||<   2d|v r|d         d         }d|d         v r|d         d         }	nd}	t                               ||	          }
|
r3|
j                                                            d	d
          }|||<   t
          t
          |S )zDFlatten the somewhat deep/complex/nested data returned from decoder.c                 6    d| v rdS d| v rdS d| v r| d         S | S )Nr  r  r  r\   )scs    r^   sc_abbreviatez%EF_ARR.flatten.<locals>.sc_abbreviate  s:    2~~xBw-33677	r]   r   rI   rR  r~  r  r  N _)ts_102_22x_cmdsetlookupr  lowerreplacer  )r#  r'  by_modetamr&  sc_abbrminsclacmdr  s               r^   flattenzEF_ARR.flatten  s   	 	 	  	! 	!A1B1B#mB''G""M* ) )A!(GAJJ)!R'')*51B/000-.u5CCC'..sC88 %8>>++33C==D$+GDMM$$  r]   c                 v    t          dt          t          g          }|                    |          }|d         S )Narrsequencer   )DataObjectSequenceAM_DO_EFSC_DOdecode_multi)r   raw_bin_datakwargsarr_seqdecs        r^   _decode_record_binzEF_ARR._decode_record_bin  s7    $Uh5FGGG""<00 1vr]   c                 f    t          dt          t          g          }|                    |          S )Nr8  r9  )r;  r<  r=  encode_multi)r   in_jsonr@  rA  s       r^   _encode_record_binzEF_ARR._encode_record_bin  s-    $Uh5FGGG##G,,,r]   zFile-Specific Commandsc                       e Zd Ze                    ej        j                  d             Ze                    ej        j	                  d             Z
dS )EF_ARR.AddlShellCommandsc                     | j         j                            |j                  \  }}| j         j        j                            |          }| j                             ||j                   dS )z9Read one EF.ARR record in flattened, human-friendly form.N)_cmdlchanread_record_dec	RECORD_NRselected_filer6  poutput_jsononeline)r   optsdata_sws       r^   do_read_arr_recordz+EF_ARR.AddlShellCommands.do_read_arr_record  s[     )/99$.IIKT39?088>>DI""466666r]   c                 h   | j         j                                        }g }t          dd|z             D ]]}| j         j                            |          \  }}| j         j        j                            |          }|                    |           ^| j                             ||j	                   dS )zCRead + decode all EF.ARR records in flattened, human-friendly form.rI   N)
rK  rL  selected_file_num_of_recrangerM  rO  r6  rd  rP  rQ  )r   rR  rp   	data_listrecnrrS  rT  s          r^   do_read_arr_recordsz,EF_ARR.AddlShellCommands.do_read_arr_records  s     AACCJIq!j.11 ' '"io==eDDsy4<<TBB  &&&&I""9dl;;;;;r]   N)rW   rX   rY   cmd2with_argparser
LinFixedEFShellCommandsread_rec_dec_parserrU  read_recs_dec_parserr[  r\   r]   r^   r"  rI    st        			Z5I	J	J	7 	7 
K	J	7 
		Z5J	K	K		< 		< 
L	K		< 		< 		<r]   r"  )r  r   r  r  )rW   rX   rY   r   rU  staticmethodr  r6  rC  rG  with_default_category
CommandSetr"  rl  rm  s   @r^   r  r    s       
L 579+V58@B"~?A!5#1+V58
		 M 579"02! 9;VXZ+V585#1+V58
		O,: : : : : :
 "T " " " \"H  - - -
 344< < < < <J < < 54< < < < <r]   r  c                   L     e Zd Zdddddddfdd	d
ddddfgZd fd	Z xZS )EF_UMPC3cff02<   r  FTreq_inc_idle_currentsupport_uicc_suspend)max_current_mAt_op_s	addl_info320500r&   ry   2f08rK   EF.UMPCUICC Maximum Power Consumptionc                     t                                          ||||d           t          t          dd          }t	          dt
          z  dt
          z  d|z            | _        d S )	N)ry   ry   )r
  r  r  sizerI   rJ   ri  rl  rm  rn  )rT  rU  r	   r   r   r   r[   )r   r  r
  r  r  rn  rW  s         r^   rU  zEF_UMPC.__init__
  sm    4dFKKKd346 6 6	 V#Xf_k)6KM Mr]   )rp  rK   rq  rr  )rW   rX   rY   r   rU  rl  rm  s   @r^   rf  rf    s        
c=B\`#b#be e 	g
a_d_dGg Gg i i 	kOM M M M M M M M M Mr]   rf  c                        e Zd ZdZd fd	Zededefd            Ze	de
ddfd	            Z ed
           G d de                      Z xZS )CardProfileUICCr  UICCc                    t                      t                      t                      t                      t	                      g}t
          t          t          g}ddddddiddd	d
dddddddddddddddddddddddd dd!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7	}t                      	                    |d8d9d:||| 
                                g|;           d S )<NzNormal ending of the commandzrNormal ending of the command, with extra information from the proactive UICC containing a command for the terminalz`Normal ending of the command, with extra information concerning an ongoing data transfer session)900091xx92xx9300zkSIM Application Toolkit is busy. Command cannot be executed at present, further normal commands are allowedz<No information given, state of non-volatile memory unchangedz&Part of returned data may be corruptedzIEnd of file/record reached before reading Le bytes or unsuccessful searchzDSelected file invalidated/disabled; needs to be activated before usez"Selected file in termination statezMore data availablez1More data available and proactive command pendingzResponse data availablezMore data expectedz0More data expected and proactive command pendingzKCommand successful but after using an internal update retry routine X times)6200628162826283628462f162f262f363f163f263cxz:No information given, state of non-volatile memory changedzMemory problem)640065006581zWrong lengthz;The interpretation of this status word is command dependentzWrong parameter(s) P1-P2z)Instruction code not supported or invalidzClass not supportedz'Technical problem, no precise diagnosis)670067xx6b006d006e006f006fxxzNo information givenzLogical channel not supportedzSecure messaging not supported)680068816882z(Command incompatible with file structurezSecurity status not satisfiedz!Authentication/PIN method blockedzReferenced data invalidatedzConditions of use not satisfiedz$Command not allowed (no EF selected)z=Command not allowed - secure channel - security not satisfied)69006981698269836984698569866989z&Incorrect parameters in the data fieldzFunction not supportedzFile not foundzRecord not foundzNot enough memory spacezIncorrect parameters P1 to P2zLc inconsistent with P1 to P2zReferenced data not found)6a806a816a826a836a846a866a876a88z/INCREASE cannot be performed, max value reachedz*Authentication error, application specificz'Security session or association expiredz(Minimum UICC suspension time is too long)9850986298639864)	NormalzPostponed processingWarningszExecution errorszChecking errorszFunctions in CLA not supportedzCommand not allowedzWrong parameterszApplication errorszETSI TS 102 221000004)r  r4  sel_ctrlfiles_in_mfswshell_cmdsetsaddons)r  r   r   r  rf  r   r   r   rT  rU  r"  )r   r  filesr  r  rW  s        r^   rU  zCardProfileUICC.__init__  s   HHJJGGHHII
 
 7 Mz    F% W@c^<-K1,Je  WT(! ! 'U2C-AU    /78/ / /B7;59>W	$ 	$ A0(*1773	! 	! JDAB	# #{C
 C
J 	$54"(e*.*@*@*B*B)Cf 	 	V 	V 	V 	V 	Vr]   data_hexr  c                     t                      }|                    t          |                      |                                }t	          |d                   S )z ETSI TS 102 221 Section 11.1.1.3fcp_template)r!  from_tlvr  to_dictflatten_dict_lists)r  r/  rP   s      r^   decode_select_responsez&CardProfileUICC.decode_select_responsem  sE     MM	

3x==!!!IIKK!!N"3444r]   sccNc                 8    |                      |dddg           dS )zn Try to access MF via UICC APDUs (3GPP TS 102.221), if this works, the
        card is considered a UICC card.r  r  3f00N)_mf_select_test)clsr  s     r^   _try_match_cardzCardProfileUICC._try_match_cardu  s&     	Cvx88888r]   zTS 102 221 Specific Commandsc                      e Zd Ze                                Ze                    dedd           e                    dedd           e	                    e          d             Z
e                                Ze                    d	ed
           e	                    e          d             Ze                                Ze                    d          Ze                    deg dd           e                    ded           e                    ded           e                    d          Ze                    ddd           e                    d          Ze                    ddd           e                    d          Ze                    ddd           e                    d dd!           e                    d"dd#           e                    d$dd%           e                    d&dd'           e                    d(dd)           e                    d*dd+           e                    d,dd-           e	                    e          d.             Zd/efd0Zd1S )2!CardProfileUICC.AddlShellCommandsz--min-duration-secsrh  z'Proposed minimum duration of suspension)typedefaulthelpz--max-duration-secsiQ z'Proposed maximum duration of suspensionc                     | j         j        j                            |j        |j                  \  }}}| j                             d|||fz             dS )zNPerform the SUSPEND UICC command. Only supported on some UICC (check EF.UMPC).)min_len_secsmax_len_secsz/Negotiated Duration: %u secs, Token: %s, SW: %sN)rK  card_sccsuspend_uiccmin_duration_secsmax_duration_secspoutput)r   rR  durationtokenr  s        r^   do_suspend_uiccz1CardProfileUICC.AddlShellCommands.do_suspend_uicc  st     %)IN$7$D$DRVRhRVRh %E %j %j!XubIAXuVXDYY[ [ [ [ [r]   TOKENzToken provided during SUSPEND)r  r  c                 X    | j         j        j                            |j                   dS )a  Perform the REUSME UICC operation. Only supported on some UICC. Also: A power-cycle
            of the card is required between SUSPEND and RESUME, and only very few non-RESUME
            commands are permitted between SUSPEND and RESUME.  See TS 102 221 Section 11.1.22.N)rK  r  r  resume_uiccr  )r   rR  s     r^   do_resume_uiccz0CardProfileUICC.AddlShellCommands.do_resume_uicc  s'    
 IN++DJ77777r]   zTerminal Power Supplyz--used-supply-voltage-classrL   z Actual used Supply voltage class)r  choicesr  z --maximum-available-power-supplyz.Maximum available power supply of the terminalz--actual-used-freq-100kz0Actual used clock frequency (in units of 100kHz)z*Extended logical channels terminal supportz--extended-logical-channel
store_truez"Extended Logical Channel supported)actionr  zAdditional interfaces supportz
--uicc-clfz3Local User Interface in the Device (LUId) supportedz;Additional Terminal capability indications related to eUICCz--lui-dz--lpd-dz5Local Profile Download in the Device (LPDd) supportedz--lds-dz6Local Discovery Service in the Device (LPDd) supportedz--lui-e-scwszLUIe based on SCWS supportedz--metadata-update-alertingz"Metadata update alerting supportedz--enterprise-capable-devicezEnterprise Capable Devicez--lui-e-e4ez*LUIe using E4E (ENVELOPE tag E4) supportedz--lprzLPR (LPA Proxy) supportedc                   
 i }i }i }t          |          
g d}t          
fd|D                       r5t          
fd|D                       st                              d          
                                D ]\  }}|t          j        j        	                                v r|||<   0|t          j        j        	                                v r|||<   [|d t          j        j        D             v r|dk    r|r|di}|||<   g }t          d |                                D                       r#|                    t          |	                     |j        r!|                    t!                                 t          d
 |                                D                       r#|                    t          |	                     t          d |                                D                       r#|                    t          |	                     t#          |           t%          |          }	|                     t)          |	                                                     dS )z\Perform the TERMINAL CAPABILITY function. Used to inform the UICC about terminal capability.)r8  r9  r:  c              3   (   K   | ]}|         V  d S r%  r\   r+  x	opts_dicts     r^   	<genexpr>zKCardProfileUICC.AddlShellCommands.do_terminal_capability.<locals>.<genexpr>  s'      55A9Q<555555r]   c              3   (   K   | ]}|         V  d S r%  r\   r  s     r^   r  zKCardProfileUICC.AddlShellCommands.do_terminal_capability.<locals>.<genexpr>  s'      ==A9Q<======r]   zQIf any of the Terminal Power Supply group options are used, all must be specifiedc                     g | ]	}|j         
S r\   )r  )r+  fs     r^   r  zLCardProfileUICC.AddlShellCommands.do_terminal_capability.<locals>.<listcomp>  s    RRRa16RRRr]   r8  Tc              3      K   | ]}|V  d S r%  r\   r+  r  s     r^   r  zKCardProfileUICC.AddlShellCommands.do_terminal_capability.<locals>.<genexpr>  s"      001000000r]   r  c              3      K   | ]}|V  d S r%  r\   r  s     r^   r  zKCardProfileUICC.AddlShellCommands.do_terminal_capability.<locals>.<genexpr>  s"      551555555r]   c              3      K   | ]}|V  d S r%  r\   r  s     r^   r  zKCardProfileUICC.AddlShellCommands.do_terminal_capability.<locals>.<genexpr>  s"      331333333r]   )r  N)varsanyallargparseArgumentTypeErrorr.  r>  r[   flagskeysrB  r7  subconsvaluesrd  extended_logical_channelr<  printrL  r   b2hto_tlv)r   rR  ps_flagsaddl_if_flagseuicc_flagspower_itemskv
child_listtcr  s             @r^   do_terminal_capabilityz8CardProfileUICC.AddlShellCommands.do_terminal_capability  s    HMKT

IrrrK555555555 J========= J"44  6I  J  J  J!)) $ $13>DIIKKKK'(M!$$0;AFFHHHH%&KNNRR+>+I+QRRRRR777A7I"#HQKJ00hoo//00000 I!!"5h"G"G"GHHH, B!!">"@"@AAA55m224455555 V!!"=m"T"T"TUUU33k002233333 O!!"8"M"M"MNNN*#Z888B$$S%5%566666r]   rS  c                     dt          |          dz  |fz  }| j        j        j                            |          \  }}d S )Nz80AA0000%02x%srJ   )rc  rK  rL  r  send_apdu_checksw)r   rS  cmd_hex_rsp_hexrT  s        r^   r   z5CardProfileUICC.AddlShellCommands.terminal_capability  s=    &#d))Q,)==G IO/AA'JJMHcccr]   N)rW   rX   rY   r  ArgumentParsersuspend_uicc_parseradd_argumentr   r\  r]  r  resume_uicc_parserstrr  term_cap_parseradd_argument_grouptc_power_grp
auto_uint8
tc_elc_grp
tc_aif_grptc_euicc_grpr  Hexstrr   r\   r]   r^   r"  r  {  s       &5577(()>SRT.W 	) 	Y 	Y 	Y(()>SRZ.W 	) 	Y 	Y 	Y 
		0	1	1	[ 	[ 
2	1	[ &4466''c@_'```			/	0	0	8 	8 
1	0	8 #1133&99:QRR!!"?cShShSh'I 	" 	K 	K 	K!!"D:'W 	" 	Y 	Y 	Y!!";*'Y 	" 	[ 	[ 	[ %778dee
 <\%I 	  	K 	K 	K$778WXX
\%Z 	  	\ 	\ 	\ '99:wxx!!)L'\ 	" 	^ 	^ 	^!!)L'^ 	" 	` 	` 	`!!)L'_ 	" 	a 	a 	a!!.'E 	" 	G 	G 	G!!">|'K 	" 	M 	M 	M!!"?'B 	" 	D 	D 	D!!-'S 	" 	U 	U 	U!!','B 	" 	D 	D 	D 
		_	-	-$	7 $	7 
.	-$	7L	K6 	K 	K 	K 	K 	K 	Kr]   r"  )rw  )rW   rX   rY   ORDERrU  rb  r  objectr  classmethodSimCardCommandsr  rc  rd  r"  rl  rm  s   @r^   rv  rv    s       EUV UV UV UV UV UVn 5 5 5 5 5 \5 9/ 9d 9 9 9 [9
 9::fK fK fK fK fKJ fK fK ;:fK fK fK fK fKr]   rv  N)frz  r   	constructr   r   r   r   r   r	   r
   r   r   r   r   osmocom.constructosmocom.utilsosmocom.tlvpySim.utilspySim.filesystempySim.profiler   pySimr   pySim.ts_51_011r   r   r   pySim.gsm_rr   pySim.cdma_ruimr   CardCommandSetCardCommandr*  r   r   r  rS   rd   rg   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  r!  r0  r5  r7  r<  r>  rB  rL  
DataObjectrO  ro  r|  DataObjectChoice
AM_DO_CHDRAM_DO_DFr<  r  r  r  TL0_DataObject	Always_DONever_DOr  OR_TemplateOR_DOAND_TemplateAND_DONOT_TemplateNOT_DOr=  r^  r  r  TransparentEFrf  rv  r\   r]   r^   <module>r+     s   "       c c c c c c c c c c c c c c c c c c c c 5 5 5 5 5 5 5 5                     % % % % % %       6 5 5 5 5 5 5 5 5 5 ! ! ! ! ! ! % % % % % %"N< +2KD2D2D2DEE+2 KD2D2D2DEE+2 KD2D2D2DEE	+2
 KD2D2D2DEE+2 KD2D2D2DEE+2 KD2D2D2DEE+2 KD2D2D2DEE+2 K
D2D2D2DEE+2 KD2D2D2DEE+2 K
D2D2D2DEE+2 KD2D2D2DEE+2 KD2D2D2DEE+2 KD2D2D2DEE+2 KD2D2D2DEE+2  KD2D2D2DEE!+2" K!D2D2D2DEE#+2$ KD2D2D2DEE%+2& KD2D2D2DEE'+2( KD2D2D2DEE)+2* KD2D2D2DEE++2, K%D2D2D2DEE-+2. K"D4&99/+20 K
D4&991+22 KD4&993+24 K#D4&995+26 K D2D2D2DEE7+28 K'D2D2D2DEE9+2: KD2D2D2DEE;+2< KD4&99=+2> KD2D2D2DEE?+2@ K'D4&99A+2B KD2D2D2DEEC+2F KD4,??G+2H KD4,??I+2J K!D4,??K+2L KD4,??M+2N KD4,??O+2P KD4,??Q+2R K&D4,??S+2T KD4,??U+2 + + ^ !y3#tLLL ) ) ) ) )zt ) ) ) )) ) ) ) )JD ) ) ) )Y Y Y Y YZT Y Y Y Y2    ZT        ZT        *$    6 6 6 6 6*$ 6 6 6 6    :4    ! ! ! ! !jd ! ! ! !4 4 4 4 4*$ 4 4 4 4! ! ! ! !zt ! ! ! !! ! ! ! !jd ! ! ! !8 8 8 8 8*$ 8 8 8 8r r r r r
 r r r r    jd    j j j j jjd j j j j    ZT        JD    < < < < <jd < < < <
	 	 	 	 	ZT%8:U%A?%02BO%@Bc%4nm%<%>	 	 	 	    JD        ZT    N N N N Nzt N N N N
	5 	5 	5 	5 	5*$ 	5 	5 	5 	5% % % % %ZT % % % %P    JD        
        :4    	 	 	 	 	:4@QS_8` 	 	 	 		 	 	 	 	*$-Yg068NPe0FH`0CE[0D	0F 	 	 	 	? ? ?E E E8 8 8 8 8*$ 8 8 8 8    :4    2 2 2 2 2*$ 2 2 2 2% % % % %ZT % % % %	 	 	 	 	7JLh7RTj7l 	 	 	 	
+& +& +& +& +&
 +& +& +&\-& -& -& -& -&
 -& -& -&`. . . . .* . . .b lK{{4((++d*;*;[[=N=NK{{4((++d*;*;[[=N=NK{{4((++d*;*;[[=N=NK{{4((++d*;*;	5= > > >
 		#		# F && 	& 	&	
 	& 	& 	& 	& 	& 	& 	& 	& 	& 	/  	'!" 	'#$ 	'%& 








9    	@F F F F FZ F F F03& 3& 3& 3& 3&Z 3& 3& 3&l N8Xt44	>'7D11! ! ! ! !
 ! ! !( }m(18^^=M=M~~^bOcOcekekemem'np p p	$k**)2Hnn>N>NP^P^_cPdPdflflfnfn(oq q q	5$	-	-)2Hnn>N>NP^P^_cPdPdflflfnfn(oq q q	5$	-	--/C"+X~~7G7GX\I]I]_e_e_g_g"'"9	: 	: 	:
/ / / / /Z / / />a< a< a< a< a<Z a< a< a<JM M M M Mm M M MPK PK PK PK PKk PK PK PK PK PKr]   