o
    g                     @   sP  d Z ddlZddlmZmZ ddlmZ ddlZddlmZ ddl	m
Z
m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 dd	lmZmZmZ dd
l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" ddl#m$Z$ zddl%m&Z& W n e'y   ddl(m&Z& Y nw dZ)dd Z*G dd de+Z,G dd dZ-G dd dZ.dS )z!
Common API for all public keys.
    N)encodebytesdecodebytes)	unhexlify)Path)md5sha256)default_backend)paddingserialization)
algorithmsmodesCipher)
asymmetric)util)ub)o600)SSHExceptionPasswordRequiredException)Message)	TripleDESs   openssh-key-v1 c                 C   sh   | d }d|  krdk r| S  |dkrt dt|D ]}| ||  |d kr,t dq| d |  S )N          zInvalid key   )r   range)datapadding_lengthi r    G/var/www/html/api-tag/env/lib/python3.10/site-packages/paramiko/pkey.py_unpad_openssh?   s   r"   c                   @   s"   e Zd ZdZdddZdd ZdS )UnknownKeyTypezK
    An unknown public/private key algorithm was attempted to be read.
    Nc                 C   s   || _ || _d S Nkey_type	key_bytes)selfr&   r'   r    r    r!   __init__S   s   
zUnknownKeyType.__init__c                 C   s   d| j dt| j dS )NzUnknownKeyType(type=z	, bytes=<z>))r&   lenr'   r(   r    r    r!   __str__W   s   zUnknownKeyType.__str__NN)__name__
__module____qualname____doc__r)   r,   r    r    r    r!   r#   N   s    
r#   c                   @   s  e Zd ZdZejddejdejddejdeddejddZ	dZ
d	Zed
ZedZedOddZedd Zedd ZdPddZdd Zdd Zdd Zdd Zdd Zedd  Zd!d" Zed#d$ Zd%d& Zd'd( Z d)d* Z!ed+d, Z"d-d. Z#dOd/d0Z$d1d2 Z%edOd3d4Z&edOd5d6Z'dOd7d8Z(dOd9d:Z)dOd;d<Z*dOd=d>Z+d?d@ Z,dAdB Z-dCdD Z.dEdF Z/dOdGdHZ0dOdIdJZ1dKdL Z2dMdN Z3dS )QPKeyz
    Base class for public keys.

    Also includes some "meta" level convenience constructors such as
    `.from_type_string`.
       )cipherkeysize	blocksizemoder         )zAES-128-CBCzAES-256-CBCzDES-EDE3-CBCr      z3^-{5}BEGIN (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$z1^-{5}END (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$Nc                 C   s\  ddl m}m}m}m} t| } d}t| |r%| dt|  }| }n| }| | }t|	 }t|	 }|
 }	z	tj|	|d}
W n tyT   tj|	|d}
Y nw d}t|
tjjra|}n%t|
tjjrk|}nt|
tjjru|}nt|
tjjr|}nt|	|
jd| }|j||d}W d   n1 sw   Y  | r|t| |S )aV  
        Attempt to instantiate appropriate key subclass from given file path.

        :param Path path: The path to load (may also be a `str`).

        :returns:
            A `PKey` subclass instance.

        :raises:
            `UnknownKeyType`, if our crypto backend doesn't know this key type.

        .. versionadded:: 3.2
        r   )DSSKeyRSAKey
Ed25519KeyECDSAKeyz	-cert.pubN)r   password)r'   r&   r?   )paramikor;   r<   r=   r>   strendswithr*   r   
expanduser
read_bytesr
   load_ssh_private_key
ValueErrorload_pem_private_key
isinstancer   dsaDSAPrivateKeyrsaRSAPrivateKeyed25519Ed25519PrivateKeyecEllipticCurvePrivateKeyr#   	__class__openfrom_private_keyexistsload_certificate)path
passphraser;   r<   r=   r>   cert_suffixkey_path	cert_pathr   loaded	key_classfdkeyr    r    r!   	from_path   sH   


zPKey.from_pathc                 C   s<   ddl m} |D ]}| | v r||d  S qt| |d)av  
        Given type `str` & raw `bytes`, return a `PKey` subclass instance.

        For example, ``PKey.from_type_string("ssh-ed25519", <public bytes>)``
        will (if successful) return a new `.Ed25519Key`.

        :param str key_type:
            The key type, eg ``"ssh-ed25519"``.
        :param bytes key_bytes:
            The raw byte data forming the key material, as expected by
            subclasses' ``data`` parameter.

        :returns:
            A `PKey` subclass instance.

        :raises:
            `UnknownKeyType`, if no registered classes knew about this type.

        .. versionadded:: 3.2
        r   )key_classes)r   r%   )rA   ra   identifiersr#   )r&   r'   ra   r]   r    r    r!   from_type_string   s   zPKey.from_type_stringc                 C   s   | j gS )z
        returns an iterable of key format/name strings this class can handle.

        Most classes only have a single identifier, and thus this default
        implementation suffices; see `.ECDSAKey` for one example of an
        override.
        )name)clsr    r    r!   rb      s   	zPKey.identifiersc                 C      dS )aV  
        Create a new instance of this public key type.  If ``msg`` is given,
        the key's public part(s) will be filled in from the message.  If
        ``data`` is given, the key's public part(s) will be filled in from
        the string.

        :param .Message msg:
            an optional SSH `.Message` containing a public key of this type.
        :param bytes data:
            optional, the bytes of a public key of this type

        :raises: `.SSHException` --
            if a key cannot be created from the ``data`` or ``msg`` given, or
            no key was passed in.
        Nr    )r(   msgr   r    r    r!   r)      s   zPKey.__init__c                 C   sD   d}t | dr| jrd| j}d| j d|   d| j | dS )N commentz
, comment=z	PKey(alg=z, bits=z, fp=))hasattrri   algorithm_nameget_bitsfingerprint)r(   ri   r    r    r!   __repr__  s   $zPKey.__repr__c                 C      t  S )z
        Return a string of an SSH `.Message` made up of the public part(s) of
        this key.  This string is suitable for passing to `__init__` to
        re-create the key object later.
        bytesr+   r    r    r!   asbytes  s   zPKey.asbytesc                 C   s   |   S r$   )rs   r+   r    r    r!   	__bytes__   s   zPKey.__bytes__c                 C   s   t |to
| j|jkS r$   )rI   r2   _fieldsr(   otherr    r    r!   __eq__#  s   zPKey.__eq__c                 C   s
   t | jS r$   )hashru   r+   r    r    r!   __hash__&     
zPKey.__hash__c                 C   s   t r$   )NotImplementedErrorr+   r    r    r!   ru   )  s   zPKey._fieldsc                 C   rf   )z
        Return the name of this private key implementation.

        :return:
            name of this private key type, in SSH terminology, as a `str` (for
            example, ``"ssh-rsa"``).
        rh   r    r+   r    r    r!   get_name-  s   zPKey.get_namec                 C   sF   |   dd}d}||v r||d}| S |dd }| S )z
        Return the key algorithm identifier for this key.

        Similar to `get_name`, but aimed at pure algorithm name instead of SSH
        protocol field value.
        zssh-rh   z-cert-v01@openssh.comz-cert-r   )r}   replacesplitupper)r(   rd   	cert_tailr    r    r!   rl   7  s   
zPKey.algorithm_namec                 C   rf   )z
        Return the number of significant bits in this key.  This is useful
        for judging the relative security of a key.

        :return: bits in the key (as an `int`)
        r   r    r+   r    r    r!   rm   K  s   	zPKey.get_bitsc                 C   rf   )zf
        Return ``True`` if this key has the private part necessary for signing
        data.
        Fr    r+   r    r    r!   can_signV  s   zPKey.can_signc                 C   s   t |   S )z
        Return an MD5 fingerprint of the public part of this key.  Nothing
        secret is revealed.

        :return:
            a 16-byte `string <str>` (binary) of the MD5 fingerprint, in SSH
            format.
        )r   rs   digestr+   r    r    r!   get_fingerprint]  s   	zPKey.get_fingerprintc                 C   sB   t t| }|j }t| }t| d}| d| S )z
        Modern fingerprint property designed to be comparable to OpenSSH.

        Currently only does SHA256 (the OpenSSH default).

        .. versionadded:: 3.2
        =:)	r   rr   rd   r   r   r   r   striprstrip)r(   hashy	hash_nameb64edcleanedr    r    r!   rn   h  s
   	
zPKey.fingerprintc                 C   s   t t|  ddS )a+  
        Return a base64 string containing the public part of this key.  Nothing
        secret is revealed.  This format is compatible with that used to store
        public key files or recognized host keys.

        :return: a base64 `string <str>` containing the public part of the key.
        
rh   )r   r   rs   r   r+   r    r    r!   
get_base64w  s   zPKey.get_base64c                 C   rp   )a  
        Sign a blob of data with this private key, and return a `.Message`
        representing an SSH signature message.

        :param bytes data:
            the data to sign.
        :param str algorithm:
            the signature algorithm to use, if different from the key's
            internal name. Default: ``None``.
        :return: an SSH signature `message <.Message>`.

        .. versionchanged:: 2.9
            Added the ``algorithm`` kwarg.
        rq   )r(   r   	algorithmr    r    r!   sign_ssh_data  s   zPKey.sign_ssh_datac                 C   rf   )a^  
        Given a blob of data, and an SSH message representing a signature of
        that data, verify that it was signed with this key.

        :param bytes data: the data that was signed.
        :param .Message msg: an SSH signature message
        :return:
            ``True`` if the signature verifies correctly; ``False`` otherwise.
        Fr    )r(   r   rg   r    r    r!   verify_ssh_sig  s   
zPKey.verify_ssh_sigc                 C      | ||d}|S )a  
        Create a key object by reading a private key file.  If the private
        key is encrypted and ``password`` is not ``None``, the given password
        will be used to decrypt the key (otherwise `.PasswordRequiredException`
        is thrown).  Through the magic of Python, this factory method will
        exist in all subclasses of PKey (such as `.RSAKey` or `.DSSKey`), but
        is useless on the abstract PKey class.

        :param str filename: name of the file to read
        :param str password:
            an optional password to use to decrypt the key file, if it's
            encrypted
        :return: a new `.PKey` based on the given private key

        :raises: ``IOError`` -- if there was an error reading the file
        :raises: `.PasswordRequiredException` -- if the private key file is
            encrypted, and ``password`` is ``None``
        :raises: `.SSHException` -- if the key file is invalid
        )filenamer?   r    )re   r   r?   r_   r    r    r!   from_private_key_file  s   zPKey.from_private_key_filec                 C   r   )a  
        Create a key object by reading a private key from a file (or file-like)
        object.  If the private key is encrypted and ``password`` is not
        ``None``, the given password will be used to decrypt the key (otherwise
        `.PasswordRequiredException` is thrown).

        :param file_obj: the file-like object to read from
        :param str password:
            an optional password to use to decrypt the key, if it's encrypted
        :return: a new `.PKey` based on the given private key

        :raises: ``IOError`` -- if there was an error reading the key
        :raises: `.PasswordRequiredException` --
            if the private key file is encrypted, and ``password`` is ``None``
        :raises: `.SSHException` -- if the key file is invalid
        )file_objr?   r    )re   r   r?   r_   r    r    r!   rT     s   zPKey.from_private_keyc                 C      t d)a  
        Write private key contents into a file.  If the password is not
        ``None``, the key is encrypted before writing.

        :param str filename: name of the file to write
        :param str password:
            an optional password to use to encrypt the key file

        :raises: ``IOError`` -- if there was an error writing the file
        :raises: `.SSHException` -- if the key is invalid
        Not implemented in PKey	Exception)r(   r   r?   r    r    r!   write_private_key_file     zPKey.write_private_key_filec                 C   r   )a  
        Write private key contents into a file (or file-like) object.  If the
        password is not ``None``, the key is encrypted before writing.

        :param file_obj: the file-like object to write into
        :param str password: an optional password to use to encrypt the key

        :raises: ``IOError`` -- if there was an error writing to the file
        :raises: `.SSHException` -- if the key is invalid
        r   r   )r(   r   r?   r    r    r!   write_private_key  r   zPKey.write_private_keyc                 C   s>   t |d}| |||}W d   |S 1 sw   Y  |S )a  
        Read an SSH2-format private key file, looking for a string of the type
        ``"BEGIN xxx PRIVATE KEY"`` for some ``xxx``, base64-decode the text we
        find, and return it as a string.  If the private key is encrypted and
        ``password`` is not ``None``, the given password will be used to
        decrypt the key (otherwise `.PasswordRequiredException` is thrown).

        :param str tag: ``"RSA"`` or ``"DSA"``, the tag used to mark the
            data block.
        :param str filename: name of the file to read.
        :param str password:
            an optional password to use to decrypt the key file, if it's
            encrypted.
        :return: the `bytes` that make up the private key.

        :raises: ``IOError`` -- if there was an error reading the file.
        :raises: `.PasswordRequiredException` -- if the private key file is
            encrypted, and ``password`` is ``None``.
        :raises: `.SSHException` -- if the key file is invalid.
        rN)rS   _read_private_key)r(   tagr   r?   fr   r    r    r!   _read_private_key_file  s   
zPKey._read_private_key_filec                 C   sH  |  }|std|d}| j|| }t|d }||k r5|s5|d7 }| j|| }||k r5|r#|d7 }|r@|dnd }|t|ksL|d u rStd||}	| j||	 }|	|k ru|su|	d7 }	| j||	 }|	|k ru|rc||kr| ||	|}
| j	}||
fS |dkr| 
|||	 |}
| j}||
fS td||)Nzno lines in {} private key filer   r   znot a valid {} private key fileOPENSSHz#encountered {} key, expected {} key)	readlinesr   format	BEGIN_TAGmatchr*   groupEND_TAG_read_private_key_pem_PRIVATE_KEY_FORMAT_ORIGINAL_read_private_key_openssh_PRIVATE_KEY_FORMAT_OPENSSH)r(   r   r   r?   linesstartm
line_rangekeytypeendr   pkformatr    r    r!   r      s>   	
zPKey._read_private_keyc                 C   s   d}t || jj|)Nz={}._read_private_key() spat out an unknown key format id '{}')r   r   rR   r.   )r(   id_errr    r    r!   _got_bad_key_format_id%  s   zPKey._got_bad_key_format_idc              
   C   s  d}i }|d7 }|t |k r2|| d}t |dkrn|d  ||d  < |d7 }|t |k szttd||| }W n tjj	yV } zt
d|d }~ww d|vr]|S |d }	|	dkrlt
d|	z|d	 d
\}
}W n   t
d|
| jvrt
d|
|d u rtd| j|
 d }| j|
 d }| j|
 d }tt|}tt|||}t||||t d }|||  }t|j }z
|||  W S  ty   t
dw )Nr   r   z: rh   base64 decoding error: {}z	proc-typez4,ENCRYPTEDz"Unknown private key structure "{}"zdek-info,z(Can't parse DEK-info in private key filezUnknown private key cipher "{}"zPrivate key file is encryptedr4   r5   r7   )backendz(Bad password or corrupt private key file)r*   r   r   lowerr   r   joinbase64binasciiErrorr   r   _CIPHER_TABLEr   r   r   generate_key_bytesr   r   r   	decryptorupdatefinalizer	   PKCS7
block_sizeunpadderrG   )r(   r   r   r?   r   headersliner   e	proc_typeencryption_typesaltstrr4   r5   r7   saltr_   r   decrypted_datar   r    r    r!   r   )  sd   
zPKey._read_private_key_pemc              
   C   s  zt td|}W n tjjy  } ztd|d}~ww |dd }|tkr/td| 	|dd d}|\}}}	}
}|
dkrHtd| 	|d	\}}|td
kr|tdkr`t
j}n|tdkrjt
j}n
td|d|du r|td| 	|	d\}}tjt|t|d|dd}|dd }|dd }tt|||t  }||}|| 7 }n|tdkr|tdkr|}ntd| 	|d}|\}}}}||krtdt|S )z
        Read the new OpenSSH SSH2 private key format available
        since OpenSSH version 6.5
        Reference:
        https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
        rh   r   Nr   z)unexpected OpenSSH key header encounteredsssurr   z.unsupported: private keyfile has multiple keysssbcryptz
aes256-cbcz
aes256-ctrz,unknown cipher `{}` used in private key filezutf-8zprivate key file is encryptedsu0   T)ignore_few_roundsr   nonez.unknown cipher or kdf used in private key fileuusrz/OpenSSH private key file checkints do not match)r   r   r   r   r   r   r   r   OPENSSH_AUTH_MAGIC_uint32_cstruct_unpackr   CBCCTRdecoder   r   kdfr   r   AESr   r   r   r   r"   )r(   r   r?   r   r   
auth_magiccstructr4   kdfnamekdf_optionsnum_pubkeys	remainderpubkeyprivkey_blobr7   r   roundskey_ivr_   ivr   decrypted_privkey	checkint1	checkint2r   keydatar    r    r!   r   ]  sv   	
zPKey._read_private_key_opensshc              
   C   sP  g }d}z|D ]}|dkr0t d|||d  d }|d7 }||||  }||7 }|| |dkr^t d|||d  d }|d7 }||||  }||7 }t|d}|| q|dkrzt d|||d  d }	|d7 }||	 q|dkr||d	 }||  nqW t|S W t|S  ty }
 ztt|
d	}
~
ww )
a  
        Used to read new OpenSSH private key format.
        Unpacks a c data structure containing a mix of 32-bit uints and
        variable length strings prefixed by 32-bit uint size field,
        according to the specified format. Returns the unpacked vars
        in a tuple.
        Format strings:
          s - denotes a string
          i - denotes a long integer, encoded as a byte string
          u - denotes a 32-bit unsigned integer
          r - the remainder of the input string, returned as a string
        r   sz>L   r   Tr   r   N)	structunpackappendr   inflate_longr   r   rB   tuple)r(   r   	strformatarridxr   s_sizer   r   r   r   r    r    r!   r     sD   

zPKey._uint32_cstruct_unpackc                 C   s^   t t j|t jt jB t jB tdd}| j||||d W d   dS 1 s(w   Y  dS )a  
        Write an SSH2-format private key file in a form that can be read by
        paramiko or openssh.  If no password is given, the key is written in
        a trivially-encoded format (base64) which is completely insecure.  If
        a password is given, DES-EDE3-CBC is used.

        :param str tag:
            ``"RSA"`` or ``"DSA"``, the tag used to mark the data block.
        :param filename: name of the file to write.
        :param bytes data: data blob that makes up the private key.
        :param str password: an optional password to use to encrypt the file.

        :raises: ``IOError`` -- if there was an error writing the file.
        )flagsr7   wr@   N)osfdopenrS   O_WRONLYO_TRUNCO_CREATr   _write_private_key)r(   r   r_   r   r?   r   r    r    r!   _write_private_key_file  s   "zPKey._write_private_key_filec                 C   s@   |d u r	t  }nt t|}||t jj||  d S r$   )	r
   NoEncryptionBestAvailableEncryptionr   writeprivate_bytesEncodingPEMr   )r(   r   r_   r   r?   
encryptionr    r    r!   r     s   

zPKey._write_private_keyc                 C   s   |}|}t |tr|g}t |tr|g}|du rtd|  | }||v r*dS ||v r=| t|  |  dS d}t|	| j
j|)a  
        Perform message type-checking & optional certificate loading.

        This includes fast-forwarding cert ``msg`` objects past the nonce, so
        that the subsequent fields are the key numbers; thus the caller may
        expect to treat the message as key material afterwards either way.

        The obtained key type is returned for classes which need to know what
        it was (e.g. ECDSA.)
        NzKey object may not be emptyz%Invalid key (class: {}, data type: {})rI   rB   r   rewindget_textrV   r   rs   
get_stringr   rR   r.   )r(   rg   r&   	cert_type	key_types
cert_typestype_r   r    r    r!   _check_type_and_load_cert  s"   

zPKey._check_type_and_load_certc                 C   sh   t |trd}ntj|rd}nd}tt||}|j| 	 s/d}t
||j| 	 || _dS )a5  
        Supplement the private key contents with data loaded from an OpenSSH
        public key (``.pub``) or certificate (``-cert.pub``) file, a string
        containing such a file, or a `.Message` object.

        The .pub contents adds no real value, since the private key
        file includes sufficient information to derive the public
        key info. For certificates, however, this can be used on
        the client side to offer authentication requests to the server
        based on certificate instead of raw public key.

        See:
        https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys

        Note: very little effort is made to validate the certificate contents,
        that is for the server to decide if it is good enough to authenticate
        successfully.
        from_message	from_filefrom_stringz0PublicBlob type {} incompatible with key type {}N)rI   r   r   rW   isfilegetattr
PublicBlobr&   
startswithr}   rG   r   public_blob)r(   valueconstructorblobr   r    r    r!   rV   C  s   

zPKey.load_certificater$   r-   )4r.   r/   r0   r1   r   r   r   r   r   r   r   r   recompiler   r   staticmethodr`   rc   classmethodrb   r)   ro   rs   rt   rx   rz   propertyru   r}   rl   rm   r   r   rn   r   r   r   r   rT   r   r   r   r   r   r   r   r   r  r   r  rV   r    r    r    r!   r2   [   s    

I












%4V
1
"1r2   c                   @   sV   e Zd ZdZdddZedd Zedd Zed	d
 Zdd Z	dd Z
dd ZdS )r  a  
    OpenSSH plain public key or OpenSSH signed public key (certificate).

    Tries to be as dumb as possible and barely cares about specific
    per-key-type data.

    .. note::

        Most of the time you'll want to call `from_file`, `from_string` or
        `from_message` for useful instantiation, the main constructor is
        basically "I should be using ``attrs`` for this."
    Nc                 C   s   || _ || _|| _dS )a  
        Create a new public blob of given type and contents.

        :param str type_: Type indicator, eg ``ssh-rsa``.
        :param bytes blob: The blob bytes themselves.
        :param str comment: A comment, if one was given (e.g. file-based.)
        N)r&   key_blobri   )r(   r  r  ri   r    r    r!   r)   w  s   
zPublicBlob.__init__c                 C   s:   t |}| }W d   n1 sw   Y  | |S )zO
        Create a public blob from a ``-cert.pub``-style file on disk.
        N)rS   readr  )re   r   r   stringr    r    r!   r    s   


zPublicBlob.from_filec           
      C   s   | dd}t|dk rd}t|||d }tt|d }z|d  }W n ty4   d}Y nw t|}|	 }||krNd||}	td|	| |||dS )	zI
        Create a public blob from a ``-cert.pub``-style string.
        Nr:   z%Not enough fields for public blob: {}r   r   z!key type={!r}, but blob type={!r}zInvalid PublicBlob contents: {})r  r  ri   )
r   r*   rG   r   r   r   r   
IndexErrorr   r
  )
re   r#  fieldsrg   r&   r!  ri   r   	blob_typedeetsr    r    r!   r    s&   zPublicBlob.from_stringc                 C   s   |  }| || dS )z
        Create a public blob from a network `.Message`.

        Specifically, a cert-bearing pubkey auth packet, because by definition
        OpenSSH-style certificates 'are' their own network representation."
        )r  r  )r
  rs   )re   messager  r    r    r!   r    s   zPublicBlob.from_messagec                 C   s&   d | j}| jr|d | j7 }|S )Nz{} public key/certificatez- {})r   r&   ri   )r(   retr    r    r!   r,     s   zPublicBlob.__str__c                 C   s   | o	|o	| j |j kS r$   )r!  rv   r    r    r!   rx     s   zPublicBlob.__eq__c                 C   s
   | |k S r$   r    rv   r    r    r!   __ne__  r{   zPublicBlob.__ne__r$   )r.   r/   r0   r1   r)   r  r  r  r  r,   rx   r*  r    r    r    r!   r  i  s    




r  )/r1   r   r   r   r   r   r   pathlibr   hashlibr   r   r  r   r   cryptography.hazmat.backendsr   cryptography.hazmat.primitivesr	   r
   &cryptography.hazmat.primitives.ciphersr   r   r   r   rA   r   paramiko.utilr   r   paramiko.commonr   paramiko.ssh_exceptionr   r   paramiko.messager   /cryptography.hazmat.decrepit.ciphers.algorithmsr   ImportError1cryptography.hazmat.primitives.ciphers.algorithmsr   r"   r   r#   r2   r  r    r    r    r!   <module>   sF         