
    Wwg`b                        d Z ddlZddlZddlZddlZddlZddlmZ ddlm	Z	m
Z
mZmZmZmZmZmZ ddlZddl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mZ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(m)Z)m*Z*m+Z+m,Z,m-Z- ddlm.Z/ ddlm0Z1 g dZ4 ejj                  e6      Z7dee   de1jp                  deee9e9f      fdZ:dee   de1jp                  de;fdZ<	 	 d4dee1jz                     dee>   dee   dee1jp                     fdZ? ed       G d d             Z@e*j                  e*j                  e*j                  e*j                  e*j                  dZFe*j                  e*j                  e*j                  e*j                  e*j                  dZLe'j                  e'j                  e'j                  e'j                  e'j                  dZRe*j                  e*j                  e*j                  e*j                  e*j                  dZXe*j                  e*j                  e*j                  e*j                  e*j                  dZ^e*j                  e*j                  e*j                  e*j                  e*j                  dZ`d ej                  d!e9d"e;de@fd#Zb	 	 	 	 d5d$e9dee>   d%ee9   dee   d&ee9ecdf   de-fd'Zd	 	 d4d(e;d)ee9   d*eee   fd+Zf	 	 d4d,e-d)ee9   d*eee   fd-Zgd!e9d.e;fd/Zh G d0 d1e&      Zi G d2 d3      Zjy# e2$ rZ3 e2de3      dZ3[3ww xY w)6z
This module provides PKCS#11 integration for pyHanko, by providing a wrapper
for `python-pkcs11 <https://github.com/danni/python-pkcs11>`_ that can be
seamlessly plugged into a :class:`~.signers.PdfSigner`.
    N)	dataclass)AnyCallableDictListOptionalSetTupleUnion)algoscorex509)RSASSAPSSParams)hashes)CertificateStore)PKCS11PinEntryModePKCS11SignatureConfigTokenCriteria)coalesce)SigningErrorget_pyca_cryptography_hash)Signer)MGFPROTECTED_AUTH	Attribute	MechanismObjectClassPKCS11ErrorSession)lib)typeszpyhanko.sign.pkcs11 requires pyHanko to be installed with the [pkcs11] option. You can install missing dependencies by running "pip install 'pyHanko[pkcs11]'".)PKCS11Signeropen_pkcs11_sessionPKCS11SigningContext
find_tokenselect_pkcs11_signing_paramscriteriatokenreturnc                 6   | g S g }| j                   6|j                   | j                   k7  r|j                  d| j                   f       | j                  D|j                  | j                  k7  r+|j                  d| j                  j                         f       |S )Nlabelserial)r+   appendr,   hex)r'   r(   	err_itemss      J/var/www/horilla/myenv/lib/python3.12/site-packages/pyhanko/sign/pkcs11.pycriteria_mismatchesr1   =   s     	I~~!ekkX^^&C'8>>23"u||x'F(HOO$7$7$9:;    c                     t        | |       S N)r1   )r'   r(   s     r0   criteria_satisfied_byr5   L   s     #8U333r2   slotsslot_notoken_criteriac                    |.|,t        |       dk(  r| d   j                         S t        d      |)| D ]#  }	 |j                         }t        ||      r|c S % y|t        |       k\  rt        d| dt        |              | |   j                         }t	        ||      }|r*dj                  d |D              }t        d	| d
| d      |S # t        $ r Y w xY w)a  
    Internal helper method to find a token.

    :param slots:
        The list of slots.
    :param slot_no:
        Slot number to use. If not specified, the first slot containing a token
        satisfying the criteria will be used
    :param token_criteria:
        Criteria the token must satisfy.
    :return:
        A PKCS#11 token object, or ``None`` if none was found.
    N   r   zJModule has more than 1 slot; slot index or token criteria must be providedzSlot index z too large; there are only , c              3   0   K   | ]  \  }}| d |  yw)z is not N ).0fieldvals      r0   	<genexpr>zfind_token.<locals>.<genexpr>~   s$       .8eS5'#) s   zToken in slot z does not satisfy criteria; .)len	get_tokenr   r5   r1   join)r6   r7   r8   slotr(   errorserr_strs          r0   r%   r%   R   s*   & '/u:?8%%''# 
  	D((? L @	,  c%j gY&A#e*N  g((*$^U;ii  <B  G  	)EgYaP  !  s   C	CCT)frozenc                   b    e Zd ZU dZeeef   ed<   	 ee	e
ge
f      ed<   	 ee	e
ge
f      ed<   y)PKCS11SignatureOperationSpeczq
    Internal helper class to describe how to invoke a signature operation on
    a key in a PKCS #11 token.
    sign_kwargspre_sign_transformpost_sign_transformN)__name__
__module____qualname____doc__r   strr   __annotations__r   r   bytesr=   r2   r0   rK   rK      sV    
 c3h !5'5.!9:: "(E7E>":;;r2   rK   )sha1sha224sha256sha384sha512signature_mechanismdigest_algorithmuse_raw_mechanismc                    ddl m} ddlm} d}d}i }	 | j                  }|dk(  r2|r"t        j                  |d<   t        |d	      }nlt        |   |d<   n^|d
k(  r3|r!t        j                  |d<   t        |d	      }nt        |   |d<   |}n&|dk(  r2|r!t        j                  |d<   t        |d	      }nt        |   |d<   |}n|dk(  rt|rt        d      | d   }	||	d   d   j                  k(  sJ t         |   |d<   t"        |   }
|	d   d   d   j                  }t$        |   }|	d   j                  }|
||f|d<   nv|dk(  r!|rt        d      t        j&                  |d<   nP|dk(  r<|rt        d      t        j&                  |d<   t)        j*                  dddd      |d<   nt        d| d      t-        |||      S # t
        $ r | d   j                  }Y w xY w)aZ  
    Internal helper function to set up a PKCS #11 signing operation.

    :param signature_mechanism:
        The signature mechanism to use (as an ASN.1 value)
    :param digest_algorithm:
        The digest algorithm to use
    :param use_raw_mechanism:
        Whether to attempt to use the raw mechanism on pre-hashed data.
    :return:
    r   )encode_dsa_signature)encode_ecdsa_signatureN	algorithmrsassa_pkcs1v15	mechanismT)wrap_digest_infodsaFecdsa
rsassa_pssz$RSASSA-PSS not available in raw mode
parametershash_algorithmmask_gen_algorithmsalt_lengthmechanism_paramed25519z!Ed25519 not available in raw modeed448zEd448 not available in raw modez@?LPzSignature algorithm 'z' is not supported.)rL   rM   rN   )pkcs11.util.dsar_   pkcs11.util.ecr`   signature_algo
ValueErrornativer   RSA_PKCS_hash_fullyRSA_MECH_MAPDSADSA_MECH_MAPECDSAECDSA_MECH_MAPNotImplementedErrorRSASSA_PSS_MECH_MAPDIGEST_MECH_MAPMGF_MECH_MAPEDDSAstructpackrK   )r[   r\   r]   r_   r`   rM   rN   kwargsrq   paramspss_digest_parammgf_valpss_mgf_parampss_salt_lens                 r0   r&   r&      sX     55FA,;; **"+"4"4F;!, 4" #//?"@F;	5	 "+--F;!, 5" #//?"@F;2	7	""+//F;!, 5"
 #11A"BF;4	<	'%&LMM"5l"C6*:#;K#H#O#OOOO 22BC{*+;<-.|<[IPP$W-m,33 %
 !
 
9	$%&IJJ'oo{	7	"%&GHH'oo{ %+KKq!$D !!#N#33FG
 	
 (-/ Y  A,[9@@As   G GGlib_locationtoken_labeluser_pinc                    t        |       }|(|&t        j                  dt               t	        |      }|j                         }t        |||      }|t        |
d|d      d      i }|||d<    |j                  di |S )	a  
    Open a PKCS#11 session

    :param lib_location:
        Path to the PKCS#11 module.
    :param slot_no:
        Slot number to use. If not specified, the first slot containing a token
        labelled ``token_label`` will be used.
    :param token_label:
        .. deprecated:: 0.14.0
            Use ``token_criteria`` instead.

        Label of the token to use. If ``None``, there is no constraint.
    :param token_criteria:
        Criteria that the token should match.
    :param user_pin:
        User PIN to use, or :attr:`.PROTECTED_AUTH`. If ``None``, authentication
        is skipped.

        .. note::
            Some PKCS#11 implementations do not require PIN when the token
            is opened, but will prompt for it out-of-band when signing.
            Whether :attr:`.PROTECTED_AUTH` or ``None`` is used in this case
            depends on the implementation.
    :return:
        An open PKCS#11 session object.
    z9'token_label' is deprecated, use 'token_criteria' instead)r+   )r7   r8   zNo token matching criteria z foundzNo token foundr   r=   )	p11_libwarningswarnDeprecationWarningr   	get_slotsr%   r   open)	r   r7   r   r8   r   r    r6   r(   r   s	            r0   r#   r#   @  s    D ,
C+"9G	
 '[9MMOEugnME}) *.);6B
 	
 "
 	
 F%z5::r2   
no_resultsr+   cert_idc                     g }||j                  d| d       |7|j                  dt        j                  |      j                  d       d       |rddj	                  |       nd}| rd| d	}|S d
| d	}|S )Nzlabel ''zID 'asciiz with r;    zCould not find certrB   zFound more than one cert)r-   binasciihexlifydecoderE   )r   r+   r   	info_strs	qualifiererrs         r0   _format_pull_err_msgr   {  s    
 I75'+,4 0 0 9 @ @ IJ!LM3<&9-./"I#I;a0 J )15Jr2   pkcs11_sessionc                    t         j                  t        j                  i}|||t         j                  <   |||t         j
                  <   | j                  |      }t        |      }t        |      dk(  r5|d   }t        j                  j                  |t         j                           S t        | ||      }t        |      )Nr:   r   )r   r+   r   )r   CLASSr   CERTIFICATELABELIDget_objectslistrC   r   CertificateloadVALUEr   r   )r   r+   r   query_paramsqresultscert_objr   s           r0   
_pull_certr     s    
 OO[%<%<=L(-Y__%%,Y\\"""<0A 1gG
7|q1:$$Xioo%>??""{%
 #r2   rd   c                J     t               dt        dt        f fd}|S )Ndatar)   c                 
   t        j                        }|j                  |        |j                         }rIt	        j
                  j                         t        j                         d|d      j                         S |S )N)ra   rh   )r\   digest)
r   Hashupdatefinalizer   
DigestInfolowerr   Nulldump)r   hr   r\   md_specrd   s      r0   _hz_hash_fully.<locals>._h  ss    KK 	## &6%;%;%=&*iik) % df Mr2   )r   rU   )r\   rd   r   r   s   `` @r0   ru   ru     s(    ()9:G 5 " Ir2   c                       e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 ddedee   deej                     dee   dee	   dee	   f fdZ
d	 Zed
efd       Zed        Zded
efdZ	 dde	ded
e	fdZd
eej                     fdZd Zd Zd Z xZS )r"   a  
    Signer implementation for PKCS11 devices.

    :param pkcs11_session:
        The PKCS11 session object to use.
    :param cert_label:
        The label of the certificate that will be used for signing, to
        be pulled from the PKCS#11 token.
    :param cert_id:
        ID of the certificate object that will be used for signing, to
        be pulled from the PKCS#11 token.
    :param signing_cert:
        The signer's certificate. If the signer's certificate is provided via
        this parameter, the ``cert_label`` and ``cert_id`` parameters will not
        be used to retrieve the signer's certificate.
    :param ca_chain:
        Set of other relevant certificates
        (as :class:`.asn1crypto.x509.Certificate` objects).
    :param key_label:
        The label of the key that will be used for signing.
        Defaults to the value of ``cert_label`` if left unspecified and
        ``key_id`` is also unspecified.

        .. note::
            At least one of ``key_id``, ``key_label`` and ``cert_label`` must
            be supplied.
    :param key_id:
        ID of the private key object (optional).
    :param other_certs_to_pull:
        List labels of other certificates to pull from the PKCS#11 device.
        Defaults to the empty tuple. If ``None``, pull *all* certificates.
    :param bulk_fetch:
        Boolean indicating the fetching strategy.
        If ``True``, fetch all certs and filter the unneeded ones.
        If ``False``, fetch the requested certs one by one.
        Default value is ``True``, unless ``other_certs_to_pull`` has one or
        fewer elements, in which case it is always treated as ``False``.
    :param use_raw_mechanism:
        Use the 'raw' equivalent of the selected signature mechanism. This is
        useful when working with tokens that do not support a hash-then-sign
        mode of operation.

        .. note::
            This functionality is only available for ECDSA at this time.
            Support for other signature schemes will be added on an as-needed
            basis.
    r   
cert_labelsigning_cert	key_labelkey_idr   c                    t        ||s|nd      | _        t        |
|s|nd      | _        t        ||s|
nd      | _        t        ||
s|nd      | _        || _        || _        d| _        |t        |      dk  rd| _	        n|	| _	        || _
        d| _        d| _        d| _        t        | =  |||       || j                   j#                  |       || j                   j%                  |       yy)z-
        Initialise a PKCS11 signer.
        NFr:   )
prefer_pssembed_rootsr   )r   r   r   r   r   r   other_certs_other_certs_loadedrC   
bulk_fetchr]   _key_handle_loaded_PKCS11Signer__loading_eventsuper__init___cert_registryregister_multipleregister)selfr   r   r   ca_chainr   r   r   other_certs_to_pullr   r   r   r]   	__class__s                r0   r   zPKCS11Signer.__init__  s    $ #	d
 viwTJztL!)vZ4P,.#( *s3F/G1/L#DO(DO!2#!#% 	 	

 11(;#((6 $r2   c                     | j                   s2| j                         }| j                  j                  |       d| _         | j                  S )NT)r   _load_other_certsr   r   )r   certss     r0   _init_cert_registryz PKCS11Signer._init_cert_registry  sC     ''**,E11%8'+D$"""r2   r)   c                 "    | j                         S r4   )r   r   s    r0   cert_registryzPKCS11Signer.cert_registry'  s     ''))r2   c                 :    | j                          | j                  S r4   )_load_objects_signing_certr   s    r0   r   zPKCS11Signer.signing_cert-  s    !!!r2   r\   c                 p    |j                         }t        | j                  |      || j                        S )N)r]   )r   r&   "get_signature_mechanism_for_digestr]   )r   r\   s     r0   _select_pkcs11_signing_paramsz*PKCS11Signer._select_pkcs11_signing_params2  s;     ,113+334DE"44
 	
r2   r   c                 8  K   |ry| j                          d {    ddlm} | j                  | j	                  |      j
                  j                        fd}t        j                         }|j                  d |       d {   S 7 y7 w)Ns   00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000r   )	SignMixinc                  |     j                   fi j                  } j                  j                  |       } | S r4   )signrL   rN   )	signaturer   khspecs    r0   _perform_signaturez7PKCS11Signer.async_sign_raw.<locals>._perform_signatureL  s@    9(8(89I''3 44Y?	r2   )	ensure_objects_loadedpkcs11r   r   r   rM   asyncioget_running_looprun_in_executor)	r   r   r\   dry_runr   r   loopr   r   s	    `     @@r0   async_sign_rawzPKCS11Signer.async_sign_raw<  s      ((***$((112BC"".**40D	 '')))$0BCCC! 	+  Ds"   BBA4BBBBc                 4    t        | j                               S r4   )set_PKCS11Signer__pullr   s    r0   r   zPKCS11Signer._load_other_certsU  s    4;;=!!r2   c              #   P  K   | j                   }|t        |      dk(  ry || j                  r| j                  j	                  t
        j                  t        j                  i      }t        j                  d       |D ]i  }|t
        j                     }|||v sd| d}t        j                  |       t        j                  j                  |t
        j                            k y |D ]5  }d| d}t        j                  |       t!        | j                  |       7 y w)Nr   z.Pulling all certificates from PKCS#11 token...zFound certificate with label 'z' on token.z Pulling certificate with label 'z' from PKCS#11 token...)r   rC   r   r   r   r   r   r   r   loggerdebugr   r   r   r   r   r   )r   other_cert_labelsr   r   r+   msgs         r0   __pullzPKCS11Signer.__pullX  s      ,,(S1B-Cq-H $##//+"9"9:A LLIJ K 1$,9J0J ;5'MCLL%**//0IJJK + 	=
 7ug >' (  S! !4!4e<<	=s   BD&BD&c                 R  K   | j                   ry| j                  dt        j                         x| _        }t        j                         }|j                  d| j                         d{    |j                          y| j                  j                          d{    y7 87 w)a  
        Async method that, when awaited, ensures that objects
        (relevant certificates, key handles, ...) are loaded.

        This coroutine is guaranteed to be called & awaited in :meth:`sign_raw`,
        but some property implementations may cause object loading to be
        triggered synchronously (for backwards compatibility reasons).
        This blocks the event loop the first time it happens.

        To avoid this behaviour, asynchronous code should ideally perform
        `await signer.ensure_objects_loaded()` after instantiating the signer.

        .. note::
            The asynchronous context manager on :class:`PKCS11SigningContext`
            takes care of that automatically.
        N)	r   r   r   Eventr   r   r   r   wait)r   eventr   s      r0   r   z"PKCS11Signer.ensure_objects_loaded{  s     $ <<'+2==?:D 5++-D&&tT-?-?@@@IIK &&++--- A
 .s$   A(B'*B#+2B'B%B'%B'c                 T   | j                   ry | j                          | j                  1t        | j                  | j
                  | j                        | _        | j                  j                  t        j                  | j                  | j                        }|| _        d| _         y )N)r+   r   )r+   idT)r   r   r   r   r   r   r   get_keyr   PRIVATE_KEYr   r   r   )r   r   s     r0   r   zPKCS11Signer._load_objects  s    <<  "%!+##4??DLL"D   ((##4>>dkk ) 
 r2   )NNNNFTr=   TNNF)F)rO   rP   rQ   rR   r   r   rS   r   r   rU   r   r   propertyr   r   r   rK   r   r   r	   r   r   r   r   __classcell__)r   s   @r0   r"   r"     s   .f %)37#'"&#'+7+7 SM+7 t//0	+7 C=+7 +7 %+7Z# */ * *
 " "
 #
	%
 ;@DD-0D	D2"3t'7'7#8 "!=F.<r2   r"   c                   T    e Zd ZdZ	 ddedee   fdZd Zde	fdZ
d	 Zd
 Zd Zd Zy)r$   z+Context manager for PKCS#11 configurations.Nconfigr   c                 .    || _         d | _        || _        y r4   )r  _session	_user_pin)r   r  r   s      r0   r   zPKCS11SigningContext.__init__  s     !r2   c                     | j                   xs | j                  j                  }|t        |      }|S | j                  j                  t
        j                  k(  rt        }|S d }|S r4   )r  r  r   rS   
prompt_pinr   DEFERr   )r   pins     r0   _handle_pinz PKCS11SigningContext._handle_pin  sb    nn4 4 4?c(C
 
	 [[##'9'?'?? C 
 C
r2   r)   c                 2   | j                   }| j                         }	 t        |j                  |j                  |j
                  |      x| _        }t        ||j                  |j                  |j                  |j                   |j"                  |j$                  |j&                  |j(                  |j*                  |j,                        S # t        j                  $ r7}t        d|j                   dt        |      j                   d|       |d }~ww xY w)N)r7   r8   r   z'PKCS#11 error while opening session to z: [z] )	r   r   r   r]   r   r   r   r   r   )r  r  r#   module_pathr7   r8   r  r   r   r   typerO   r"   r   r   r   r   raw_mechanismr   r   r   r   signing_certificate)r   r  r  sessionexs        r0   _instantiatez!PKCS11SigningContext._instantiate  s    
	&9""%44	' DMG ''&&(($22 & : :((==NN33
 	
	 !! 	9&:L:L9MSQUVXQYQbQbPccefheij	s   4C D2DDc                 "    | j                         S r4   )r  r   s    r0   	__enter__zPKCS11SigningContext.__enter__  s      ""r2   c                    K   t        j                         }|j                  d | j                         d {   }|j	                          d {    |S 7 7 wr4   )r   r   r   r  r   )r   r   signers      r0   
__aenter__zPKCS11SigningContext.__aenter__  sP     '')++D$2C2CDD**,,, E,s!   4AAAAAAc                 8    | j                   j                          y r4   r  closer   exc_typeexc_valexc_tbs       r0   __exit__zPKCS11SigningContext.__exit__  s    r2   c                 @   K   | j                   j                          y wr4   r  r  s       r0   	__aexit__zPKCS11SigningContext.__aexit__  s     s   r4   )rO   rP   rQ   rR   r   r   rS   r   r  r"   r  r  r  r"  r$  r=   r2   r0   r$   r$     sJ    5 HL"+"7?}"	
l 
:#r2   r$   )NN)NNNN)krR   r   r   loggingr   r   dataclassesr   typingr   r   r   r   r   r	   r
   r   r   
asn1cryptor   r   r   asn1crypto.algosr   cryptography.hazmat.primitivesr   pyhanko_certvalidator.registryr   pyhanko.config.pkcs11r   r   r   pyhanko.pdf_utils.miscr   pyhanko.sign.generalr   r   pyhanko.sign.signersr   r   r   r   r   r   r   r   r    r   r!   	p11_typesImportErrore__all__	getLoggerrO   r   TokenrS   r1   boolr5   Slotintr%   rK   SHA1_RSA_PKCSSHA224_RSA_PKCSSHA256_RSA_PKCSSHA384_RSA_PKCSSHA512_RSA_PKCSrv   SHA1_RSA_PKCS_PSSSHA224_RSA_PKCS_PSSSHA256_RSA_PKCS_PSSSHA384_RSA_PKCS_PSSSHA512_RSA_PKCS_PSSr|   SHA1SHA224SHA256SHA384SHA512r~   
ECDSA_SHA1ECDSA_SHA224ECDSA_SHA256ECDSA_SHA384ECDSA_SHA512rz   DSA_SHA1
DSA_SHA224
DSA_SHA256
DSA_SHA384
DSA_SHA512rx   SHA_1r}   SignedDigestAlgorithmr&   objectr#   rU   r   r   ru   r"   r$   r=   r2   r0   <module>rU     s        ! I I I  ( ( , 1 ; 
 , I '   &) 
		8	$}%.7oo	%S/4}%4.7oo4	4 ".23	3c]3 ]+3 ioo	3l $  . ##'''''''' ''++++++++  HHjjjjjjjj   $$$$$$$$ """"
 """"
 OOi44ii i "	i\ "!%.2)-8 8 c]8  #8  ]+	8 
 C%&8  8 z  #C= e_(  #C= e_2# D 4h6 hV? ?C  
	E 	
	 s   0K9 9L>	LL