
    mg,                     L   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ZddlmZmZmZmZ ddlmZmZ ddlmZ ddlmZ d	ZddlmZ ddlmZmZ ddlm Z m!Z!m"Z" ddlm#Z#m$Z$ ede
e%e&e'df   f   Z(ee'e&f   Z)ee)df   Z*erejV                  eejX                  eiZ-ej\                  ej^                  ej`                  ejb                  ej^                  ejd                  ej`                  ej\                  ej^                  ejf                  ejh                  ejj                  dZ6 G d de"      Z7 G d d      Z8d"d	dddddde'dee'   de%dee'   dee   dee'   dee   dee7   fd Z9yd"d	dddddde'dee'   de%dee'   dee   dee'   dee   ded   fd!Z9y# eef$ r d
ZY ^w xY w)#zPKCS#11 smart card handler    )TracebackType)DictListOptionalSequenceTupleTypeUnioncastN)	AttributeKeyType	MechanismObjectClass)
PrivateKeyToken)encode_rsa_public_key)encode_ec_public_keyTF   )
BytesOrStr)MPIntString)SSHCertificateSSHKey
SSHKeyPair)import_certificate_chainimport_public_keyr   r   SSHPKCS11Session)s   ssh-rsas   rsa-sha2-256s   rsa-sha2-512s   ssh-rsa-sha224@ssh.coms   ssh-rsa-sha256@ssh.coms   ssh-rsa-sha384@ssh.coms   ssh-rsa-sha512@ssh.coms   rsa1024-sha1s   rsa2048-sha256s   ecdsa-sha2-nistp256s   ecdsa-sha2-nistp384s   ecdsa-sha2-nistp521c            
       Z     e Zd ZdZdZ	 ddddededee   f fdZ	dd
Z
ded	efdZ xZS )SSHPKCS11KeyPairz3Surrogate for a key accessed via a PKCS#11 providerpkcs11sessionr   privkeypubkeycertc           
          t         |   |j                  |j                  |j                  |j                  |j                  |j
                  |d       || _        || _        y )NT)use_executor)super__init__	algorithmsig_algorithmspublic_datalabel_session_privkey)selfr!   r"   r#   r$   	__class__s        /lib/python3.12/site-packages/asyncssh/pkcs11.pyr(   zSSHPKCS11KeyPair.__init__F   sZ    GV--v/?/?#22F4I4I#//*.  0
 $DM#DM    returnc                 8    | j                   j                          y N)r-   closer/   s    r1   __del__zSSHPKCS11KeyPair.__del__P   s    MM!r2   datac                    | j                   }|j                  d      r|dd }| j                  j                  |t        |         }| j                  j
                  t        j                  k(  rWt        |      dz  }t        j                  |d| d      }t        j                  ||d d      }t        |      t        |      z   }t        |      t        |      z   S )z*Sign a block of data with this private keys   x509v3-   N)	mechanism   big)sig_algorithm
startswithr.   sign
mechanismskey_typer   EClenint
from_bytesr   r   )r/   r9   r?   siglengthrss          r1   rA   zSSHPKCS11KeyPair.signS   s     !..M''
3 -ab 1--$$TZ5N$OC}}%%3SQNN3w<7NN3vw<7Ahq)-(6#;66r2   r5   r3   N)__name__
__module____qualname____doc__	_key_typer   r   r   r   r(   r8   bytesrA   __classcell__)r0   s   @r1   r   r   A   sS    A	 GK	$$6 	$ 	$#	$+3N+C	$	"	7U 	7u 	7r2   r   c            	           e Zd ZU dZi Zeed<   dedede	e
   fdZddZd	ee   d
ededdfdZedede	e
   dd fd       ZddZdede	e
   de	e   dee   fdZy)r   z>Work around PKCS#11 sessions not supporting simultaneous opens	_sessionstoken_idtokenpinc                 N    || _         |j                  |      | _        d| _        y )N)user_pinr   )	_token_idopenr-   	_refcount)r/   rV   rW   rX   s       r1   r(   zSSHPKCS11Session.__init__k   s"    %DN!JJJ4DMDNr2   r3   c                     | S )z6Allow SSHPKCS11Session to be used as a context manager r7   s    r1   	__enter__zSSHPKCS11Session.__enter__q   s	     Kr2   	_exc_type
_exc_value
_tracebackNc                 $    | j                          y)z.Drop one reference to the session when exitingN)r6   )r/   ra   rb   rc   s       r1   __exit__zSSHPKCS11Session.__exit__v   s    
 JJLr2   c                     |j                   |j                  f}	 | j                  |   }|xj                  dz  c_        |S # t        $ r  | |||      }|| j                  |<   Y ;w xY w)z1Open a new session, or return an already-open oner   )manufacturer_idserialrU   KeyErrorr]   )clsrW   rX   rV   r!   s        r1   r\   zSSHPKCS11Session.open}   sp     --u||<H2--1
 "N  2hs3*1h'2s   A   "A%$A%c                     | xj                   dz  c_         | j                   dk(  r2| j                  j                          | j                  | j                  = yy)z%Drop one reference to an open sessionr   r   N)r]   r-   r6   rU   r[   r7   s    r1   r6   zSSHPKCS11Session.close   sC     NNaN~~"##%NN4>>2 #r2   
load_certs	key_labelkey_idc           
      .   t        |t              rt        j                  |      }t        j
                  t        j                  t        j                  di}|||t        j                  <   |||t        j                  <   t        j
                  t        j                  i}|r| j                  j                  |      D cg c],  }t        t        t        |t        j                                  . }}|D ci c]2  }|r.dt        |j"                        vr|j$                  j&                  |4 }}ni }g }	| j                  j                  |      D ]  }
t        t(        |
      }t*        j-                  |j.                        }|s5t1         ||            }|j-                  |j&                        }|r|	j3                  t5        | |||             |	j3                  t5        | ||              | xj6                  t9        |	      z  c_        |	S c c}w c c}w )z+Return the private keys found on this tokenTAttest)
isinstancestrrR   fromhexr   CLASSr   PRIVATE_KEYSIGNLABEL	OBJECT_IDCERTIFICATEr-   get_objectsr   r   VALUEsubjectkeyr+   r   encodersgetrC   r   appendr   r]   rE   )r/   rl   rm   rn   	key_attrs
cert_attrsr$   certscertdictkeysr}   r"   encoderr#   s                 r1   get_keyszSSHPKCS11Session.get_keys   s   
 &#&v.$-OO[5L5L$-NND$:I $-6	)//*!17	)--.%.__k6M6M$NJ &*]]%>%>z%JL%JT 2eT)//%:;=%J  L DI K54#DLL8I(I !HH00$65 K D}}00;z3/",,w'7'78.ww/?@F#<<(:(:;D$4T75;T%C D KK 0w GH < NNc$i'NK9LKs   ?1H67H)r3   r   rL   )rM   rN   rO   rP   rU   _SessionMap__annotations___TokenIDr   r   rr   r(   r`   r	   BaseExceptionr   re   classmethodr\   r6   boolr   r   r   r   r_   r2   r1   r   r   f   s    L!#	;#	X 	e 	"3-		
	d=&9 	!.	!.	37	 
	U 	# 	;M 	 
		30	t 0	 0	%j10	)*0	r2   )rl   token_labeltoken_serialrm   rn   providerrX   rl   r   r   rm   rn   r3   c          	      @   t        j                  |       }g }t        |t              r|j	                  d      }|j                  ||      D ]C  }	t        j                  |	|      5 }
|j                  |
j                  |||             ddd       E |S # 1 sw Y   QxY w)a  Load PIV keys and X.509 certificates from a PKCS#11 token

           This function loads a list of SSH keypairs with optional X.509
           cerificates from attached PKCS#11 security tokens. The PKCS#11
           provider must be specified, along with a user PIN if the
           tokens are set to require one.

           By default, this function loads both private key handles
           and the X.509 certificates associated with them, allowing for
           X.509 certificate based auth to SSH servers that support it.
           To disable loading of these certificates and perform only
           key-based authentication, load_certs may be set to `False`.

           If token_label and/or token_serial are specified, only tokens
           matching those values will be accessed.

           If key_label and/or key_id are specified, only keys matching
           those values will be loaded. Key IDs can be specified as
           either raw bytes or a string containing hex digits.

               .. note:: If you have an active asyncio event loop at
                         the time you call this function, you may want
                         to consider running it via a call to
                         :meth:`asyncio.AbstractEventLoop.run_in_executor`.
                         While retrieving the keys generally takes only a
                         fraction of a second, calling this function
                         directly could block asyncio event processing
                         until it completes.

           :param provider:
               The path to the PKCS#11 provider's shared library.
           :param pin: (optional)
               The PIN to use when accessing tokens, if needed.
           :param load_certs: (optional)
               Whether or not to load X.509 certificates from the
               security tokens.
           :param token_label: (optional)
               A token label to match against. If set, only security
               tokens with this label will be accessed.
           :param token_serial: (optional)
               A token serial number to match against. If set, only
               security tokens with this serial number  will be accessed.
           :param key_label: (optional)
               A key label to match against. If set, only keys with this
               label will be loaded.
           :param key_id: (optional)
               A key ID to match against. If set, only keys with this ID
               will be loaded.
           :type provider: `str`
           :type pin: `str`
           :type load_certs: `bool`
           :type token_label: `str`
           :type token_serial: `bytes` or `str`
           :type key_label: `str`
           :type key_id: `bytes` or `str`

           :returns: list of class:`SSHKeyPair`

        zutf-8)r   r   N)
r    librq   rr   encode
get_tokensr   r\   extendr   )r   rX   rl   r   r   rm   rn   r   r   rW   r!   s              r1   load_pkcs11_keysr      s    F jj"')lC('..w7L^^1= $ ?E!&&uc2gG,,ZFKL 32?
  32s   %#BB	c                    t        d      d)z,Report that PKCS#11 support is not availablezPKCS#11 support not availableN)
ValueError)r   rX   rl   r   r   rm   rn   s          r1   r   r     s     89tCr2   r5   ):rP   typesr   typingr   r   r   r   r   r	   r
   r   r    r   r   r   r   r   r   pkcs11.util.rsar   pkcs11.util.ecr   pkcs11_availableImportErrorModuleNotFoundErrormiscr   packetr   r   
public_keyr   r   r   r   r   r   rR   rr   	_AttrDictr   r   RSArD   r~   SHA1_RSA_PKCSSHA256_RSA_PKCSSHA512_RSA_PKCSSHA224_RSA_PKCSSHA384_RSA_PKCSECDSA_SHA256ECDSA_SHA384ECDSA_SHA512rB   r   r   r   r_   r2   r1   <module>r      sZ  * !  K K KAA(53  ! : : C eD%m$CDDE	e8//0 2

13H .7-D-D-6-F-F-6-F-F-6-F-F-6-F-F-6-F-F-6-F-F-6-D-D-6-F-F-6-C-C-6-C-C-6-C-CEJ"7: "7J_ _DO,06:>B488<O3 OXc] O%)O&.smO (0
';O %-SM	O
 "**!5O %&Ob	D,06:>B488<	D3 	DXc] 	D%)	D&.sm	D (0
';	D %-SM		D
 "**!5	D '(	Dq 	() s   &F 	F#"F#