o
    g>                     @   s  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ZddlZddlZddl	m
Z
 ddlmZ ddlmZmZ ddlmZmZ ddlmZ ddlmZmZ dd	lmZmZ ed
ZdZedZdZdZdZeedZ e!e " D ]\Z#Z$e$e e# d< qoG dd dZ%G dd dej&Z'G dd de'Z(G dd de'Z)dd Z*G dd dZ+G dd de%Z,G d d! d!Z-G d"d# d#e%Z.G d$d% d%eZ/dS )&z
SSH Agent interface
    N)DEBUG)select)io_sleepbyte_chr)SSHExceptionAuthenticationException)Message)PKeyUnknownKeyType)asbytes
get_logger                  )zrsa-sha2-256zrsa-sha2-512z-cert-v01@openssh.comc                   @   s<   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd ZdS )AgentSSHc                 C   s   d | _ d| _d S N )_conn_keysselfr   r   H/var/www/html/api-tag/env/lib/python3.10/site-packages/paramiko/agent.py__init__>   s   
zAgentSSH.__init__c                 C      | j S )a  
        Return the list of keys available through the SSH agent, if any.  If
        no SSH agent was running (or it couldn't be contacted), an empty list
        will be returned.

        This method performs no IO, just returns the list of keys retrieved
        when the connection was made.

        :return:
            a tuple of `.AgentKey` objects representing keys available on the
            SSH agent
        )r   r   r   r   r   get_keysB   s   zAgentSSH.get_keysc                 C   sd   || _ | t\}}|tkrtdg }t| D ]}|t| |	 |
 d qt|| _d S )Nz!could not get keys from ssh-agent)agentblobcomment)r   _send_messagecSSH2_AGENTC_REQUEST_IDENTITIESSSH2_AGENT_IDENTITIES_ANSWERr   rangeget_intappendAgentKey
get_binaryget_texttupler   )r   connptyperesultkeysir   r   r   _connectQ   s   zAgentSSH._connectc                 C   s$   | j d ur
| j   d | _ d| _d S r   )r   closer   r   r   r   r   _closea   s   


zAgentSSH._closec                 C   sX   t |}| jtdt||  | d}t| td|d }t	|
 |fS )Nz>Ir   r   )r   r   sendstructpacklen	_read_allr   unpackordget_byte)r   msgdatar   r   r   r!   g   s
   
zAgentSSH._send_messagec                 C   sl   | j |}t||k r4t|dkrtd| j |t| }t|dkr*td||7 }t||k s|S )Nr   lost ssh-agent)r   recvr6   r   )r   wantedr-   extrar   r   r   r7   n   s   zAgentSSH._read_allN)	__name__
__module____qualname__r   r   r0   r2   r!   r7   r   r   r   r   r   =   s    r   c                   @   0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )AgentProxyThreadz@
    Class in charge of communication between two channels.
    c                 C   s"   t jj| | jd || _d| _d S )N)targetF)	threadingThreadr   run_agent_exitr   r   r   r   r   r      s   
zAgentProxyThread.__init__c                 C   sh   z/|   \}}|| _|| _| j  t| jts)| jjd u s%t| jjds)t	d| 
  W d S     )NfilenozUnable to connect to SSH agent)get_connection_AgentProxyThread__inr_AgentProxyThread__addrrJ   connect
isinstanceintr   hasattrr   _communicate)r   raddrr   r   r   rI      s   
zAgentProxyThread.runc                 C   s   dd l }| | j|j}| | j|j|tjB  | jswt| jj	| jgg g d}|d D ]A}| jj	|krM| jj	
d}t|dkrG| j| q+|    n | j|krl| j
d}t|dkrf| jj	| q+|    nq+tt | jrd S d S )Nr   g      ?i   )fcntlrO   F_GETFLF_SETFLos
O_NONBLOCKrK   r   rJ   r   r>   r6   r3   r2   timesleepr   )r   rX   oldflagseventsfdr<   r   r   r   rU      s*   

zAgentProxyThread._communicatec                 C   s    d| _ | j  | jj  d S )NT)rK   rO   r1   rJ   r   r   r   r   r   r2      s   
zAgentProxyThread._closeN)rA   rB   rC   __doc__r   rI   rU   r2   r   r   r   r   rE   z   s    rE   c                   @       e Zd ZdZdd Zdd ZdS )AgentLocalProxyz
    Class to be used when wanting to ask a local SSH Agent being
    asked from a remote fake agent (so use a unix socket for ex.)
    c                 C   s   t | | d S N)rE   r   rL   r   r   r   r      s   zAgentLocalProxy.__init__c                 C   sJ   t  t jt j}z|| j  |d | \}}||fW S     )zX
        Return a pair of socket object and string address.

        May block!
           )socketAF_UNIXSOCK_STREAMbindrJ   _get_filenamelistenaccept)r   r+   rV   rW   r   r   r   rN      s   

zAgentLocalProxy.get_connectionNrA   rB   rC   rb   r   rN   r   r   r   r   rd      s    rd   c                   @   rc   )AgentRemoteProxyzA
    Class to be used when wanting to ask a remote SSH Agent
    c                 C   s   t | | || _d S re   )rE   r   _AgentRemoteProxy__chan)r   r   chanr   r   r   r      s   
zAgentRemoteProxy.__init__c                 C   s
   | j d fS re   )rp   r   r   r   r   rN      s   
zAgentRemoteProxy.get_connectionNrn   r   r   r   r   ro      s    ro   c                  C   s   dt jv r$tjdkr$ttjtj} z| t jd  | W S    Y dS tjdkrGddlm	}m
} d} | r=| } | S | rE| } | S dS )zj
    Returns some SSH agent object, or None if none were found/supported.

    .. versionadded:: 2.10
    SSH_AUTH_SOCKwin32Nrf   )win_pageantwin_openssh)r[   environsysplatformrg   rh   ri   rQ    rt   ru   can_talk_to_agentPageantConnectionOpenSSHAgentConnection)r+   rt   ru   r   r   r   get_agent_connection   s"   
r}   c                   @   rD   )AgentClientProxya  
    Class proxying request as a client:

    #. client ask for a request_forward_agent()
    #. server creates a proxy and a fake SSH Agent
    #. server ask for establishing a connection when needed,
       calling the forward_agent_handler at client side.
    #. the forward_agent_handler launch a thread for connecting
       the remote fake agent and the local agent
    #. Communication occurs ...
    c                 C   s&   d | _ || _t| || _| j  d S re   )r   _AgentClientProxy__chanRro   threadstartr   
chanRemoter   r   r   r     s   zAgentClientProxy.__init__c                 C      |    d S re   r1   r   r   r   r   __del__
     zAgentClientProxy.__del__c                 C   s   t  }|sdS || _dS )zJ
        Method automatically called by ``AgentProxyThread.run``.
        N)r}   r   r   r+   r   r   r   rQ     s   
zAgentClientProxy.connectc                 C   s:   t | drd| j_| jd | jdur| j  dS dS )zh
        Close the current connection and terminate the agent
        Should be called manually
        r   T  N)rT   r   rK   joinr   r1   r   r   r   r   r1     s   

zAgentClientProxy.closeN)rA   rB   rC   rb   r   r   rQ   r1   r   r   r   r   r~      s    	r~   c                   @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )AgentServerProxya  
    Allows an SSH server to access a forwarded agent.

    This also creates a unix domain socket on the system to allow external
    programs to also access the agent. For this reason, you probably only want
    to create one of these.

    :meth:`connect` must be called before it is usable. This will also load the
    list of keys the agent contains. You must also call :meth:`close` in
    order to clean up the unix socket and the thread that maintains it.
    (:class:`contextlib.closing` might be helpful to you.)

    :param .Transport t: Transport used for SSH Agent communication forwarding

    :raises: `.SSHException` -- mostly if we lost the agent
    c                 C   sP   t |  || _td| _t| jtj	 | jd | _
t| | _| j  d S )Nsshproxyz/sshproxy.ssh)r   r   _AgentServerProxy__ttempfilemkdtemp_dirr[   chmodstatS_IRWXU_filerd   r   r   )r   tr   r   r   r   4  s   

zAgentServerProxy.__init__c                 C   r   re   r   r   r   r   r   r   =  r   zAgentServerProxy.__del__c                 C   s2   | j  }|d u rtd|d | | d S )Nr=   z
auth-agent)r   open_forward_agent_channelr   set_namer0   )r   	conn_sockr   r   r   rQ   @  s
   

zAgentServerProxy.connectc                 C   s8   t | j t | j d| j_| jd |   dS )zk
        Terminate the agent, clean the files, close connections
        Should be called manually
        Tr   N)	r[   remover   rmdirr   r   rK   r   r2   r   r   r   r   r1   G  s
   zAgentServerProxy.closec                 C   s   d|   iS )z
        Helper for the environment under unix

        :return:
            a dict containing the ``SSH_AUTH_SOCK`` environment variables
        rr   )rk   r   r   r   r   get_envR  s   zAgentServerProxy.get_envc                 C   r   re   )r   r   r   r   r   rk   [     zAgentServerProxy._get_filenameN)
rA   rB   rC   rb   r   r   rQ   r1   r   rk   r   r   r   r   r   "  s    		r   c                   @   rD   )AgentRequestHandlera  
    Primary/default implementation of SSH agent forwarding functionality.

    Simply instantiate this class, handing it a live command-executing session
    object, and it will handle forwarding any local SSH agent processes it
    finds.

    For example::

        # Connect
        client = SSHClient()
        client.connect(host, port, username)
        # Obtain session
        session = client.get_transport().open_session()
        # Forward local agent
        AgentRequestHandler(session)
        # Commands executed after this point will see the forwarded agent on
        # the remote end.
        session.exec_command("git clone https://my.git.repository/")
    c                 C   s"   d | _ || _|| j g | _d S re   )r   _AgentRequestHandler__chanCrequest_forward_agent_forward_agent_handler"_AgentRequestHandler__clientProxys)r   
chanClientr   r   r   r   u  s   
zAgentRequestHandler.__init__c                 C   s   | j t| d S re   )r   r&   r~   r   r   r   r   r   {  s   z*AgentRequestHandler._forward_agent_handlerc                 C   r   re   r   r   r   r   r   r   ~  r   zAgentRequestHandler.__del__c                 C   s   | j D ]}|  qd S re   )r   r1   )r   pr   r   r   r1     s   

zAgentRequestHandler.closeN)rA   rB   rC   rb   r   r   r   r1   r   r   r   r   r   _  s    r   c                   @   rc   )Agenta  
    Client interface for using private keys from an SSH agent running on the
    local machine.  If an SSH agent is running, this class can be used to
    connect to it and retrieve `.PKey` objects which can be used when
    attempting to authenticate to remote SSH servers.

    Upon initialization, a session with the local machine's SSH agent is
    opened, if one is running. If no agent is running, initialization will
    succeed, but `get_keys` will return an empty tuple.

    :raises: `.SSHException` --
        if an SSH agent is found, but speaks an incompatible protocol

    .. versionchanged:: 2.10
        Added support for native openssh agent on windows (extending previous
        putty pageant support)
    c                 C   s&   t |  t }|sd S | | d S re   )r   r   r}   r0   r   r   r   r   r     s
   
zAgent.__init__c                 C   s   |    dS )z1
        Close the SSH agent connection.
        N)r2   r   r   r   r   r1     s   zAgent.closeN)rA   rB   rC   rb   r   r1   r   r   r   r   r     s    r   c                       s`   e Zd ZdZdddZdd Zdd Zd	d
 Z fddZdd Z	e
dd ZdddZ  ZS )r'   a  
    Private key held in a local SSH agent.  This type of key can be used for
    authenticating to a remote server (signing).  Most other key operations
    work as expected.

    .. versionchanged:: 3.2
        Added the ``comment`` kwarg and attribute.

    .. versionchanged:: 3.2
        Added the ``.inner_key`` attribute holding a reference to the 'real'
        key instance this key is a proxy for, if one was obtainable, else None.
    ry   c              	   C   sz   || _ || _|| _t|}| | _tt| _d | _	zt
j| j|d| _	W d S  ty<   d}| t|| j Y d S w )N)key_type	key_bytesz5Unable to derive inner_key for agent key of type {!r})r   r   r    r   r)   namer   __file___logger	inner_keyr	   from_type_stringr
   logr   format)r   r   r   r    r;   errr   r   r   r     s   

zAgentKey.__init__c                 O   s   | j j|i |S re   )r   r   )r   argskwargsr   r   r   r     s   zAgentKey.logc                 C   s   | j r| j  S | jS re   )r   r   r   r   r   r   r   r     s   zAgentKey.asbytesc                 C   r   re   )r   r   r   r   r   get_name  r   zAgentKey.get_namec                    s   | j d ur
| j  S t  S re   )r   get_bitssuperr   	__class__r   r   r     s   


zAgentKey.get_bitsc                 C   s   | j du r	t|t| j |S )zO
        Proxy any un-implemented methods/properties to the inner_key.
        N)r   AttributeErrorgetattr)r   r   r   r   r   __getattr__  s   
zAgentKey.__getattr__c                 C   s    |   | jg}| jr| jjS |S re   )r   r   r   _fields)r   fallbackr   r   r   r     s   zAgentKey._fieldsNc                 C   sb   t  }|t ||   || |t|d | j	|\}}|t
kr-td| S )Nr   zkey cannot be used for signing)r   add_bytecSSH2_AGENTC_SIGN_REQUEST
add_stringr   add_intALGORITHM_FLAG_MAPgetr   r!   SSH2_AGENT_SIGN_RESPONSEr   r(   )r   r<   	algorithmr;   r,   r-   r   r   r   sign_ssh_data  s   

zAgentKey.sign_ssh_data)ry   re   )rA   rB   rC   rb   r   r   r   r   r   r   propertyr   r   __classcell__r   r   r   r   r'     s    

r'   )0rb   r[   rg   r4   rw   rG   r]   r   r   loggingr   r   paramiko.commonr   r   paramiko.ssh_exceptionr   r   paramiko.messager   paramiko.pkeyr	   r
   paramiko.utilr   r   r"   r#   r   r   SSH_AGENT_RSA_SHA2_256SSH_AGENT_RSA_SHA2_512r   listitemskeyvaluer   rH   rE   rd   ro   r}   r~   r   r   r   r'   r   r   r   r   <module>   sJ   =;+='"