U vf@sPdZddlZddlmZmZddlmZddlZddlmZddl m Z m Z ddl Z ddl Z ddlZddlmZddlmZdd lmZmZmZdd lmZdd lmZdd lmZmZdd lmZddlm Z m!Z!ddl"m#Z#zddl$m%Z%Wn"e&k rddl'm%Z%YnXdZ(ddZ)Gddde*Z+GdddZ,GdddZ-dS)z! Common API for all public keys. N) encodebytes decodebytes) unhexlify)Path)md5sha256)default_backend) serialization) algorithmsmodesCipher) asymmetric)util)ub)o600) SSHExceptionPasswordRequiredException)Message) TripleDESsopenssh-key-v1cCsl|d}d|krdkr$nn|S|dkr4tdt|D] }||||dkr/opt/alt/python38/lib/python3.8/site-packages/paramiko/pkey.py_unpad_openssh?s  r c@s"eZdZdZdddZddZdS)UnknownKeyTypezK An unknown public/private key algorithm was attempted to be read. NcCs||_||_dSNkey_type key_bytes)selfr$r%rrr__init__SszUnknownKeyType.__init__cCsd|jdt|jdS)NzUnknownKeyType(type=z , bytes=))r$lenr%r&rrr__str__WszUnknownKeyType.__str__)NN)__name__ __module__ __qualname____doc__r'r*rrrrr!Ns r!c@seZdZdZejddejdejddejdeddejddZ dZ d Z e d Ze d ZedOd dZeddZeddZdPddZddZddZddZddZddZedd Zd!d"Zed#d$Zd%d&Zd'd(Z d)d*Z!ed+d,Z"d-d.Z#dQd/d0Z$d1d2Z%edRd3d4Z&edSd5d6Z'dTd7d8Z(dUd9d:Z)dVd;d<Z*dWd=d>Z+d?d@Z,dAdBZ-dCdDZ.dEdFZ/dXdGdHZ0dYdIdJZ1dKdLZ2dMdNZ3d S)ZPKeyz Base class for public keys. Also includes some "meta" level convenience constructors such as `.from_type_string`. )cipherkeysize blocksizemoder)z AES-128-CBCz AES-256-CBCz DES-EDE3-CBCrz3^-{5}BEGIN (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$z1^-{5}END (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$Nc CsNddlm}m}m}m}t|}d}t||rJ|dt| }|}n |}||}t| }t| }| } zt j | |d} Wn"t k rt j| |d} YnXd} t| tjjr|} nLt| tjjr|} n8t| tjjr|} n$t| tjjr|} nt| | jd|} | j| |d} W5QRX|rJ| 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)DSSKeyRSAKey Ed25519KeyECDSAKeyz -cert.pubN)rpassword)r%r$r<)paramikor8r9r:r;strendswithr(r expanduser read_bytesr Zload_ssh_private_key ValueErrorZload_pem_private_key isinstancer ZdsaZ DSAPrivateKeyrsaZ RSAPrivateKeyZed25519ZEd25519PrivateKeyecZEllipticCurvePrivateKeyr! __class__openfrom_private_keyexistsload_certificate)pathZ passphraser8r9r:r;Z cert_suffixZkey_pathZ cert_pathrZloaded key_classfdkeyrrr from_pathsH      zPKey.from_pathcCs@ddlm}|D]}||kr||dSqt||ddS)av Given type `str` & raw `bytes`, return a `PKey` subclass instance. For example, ``PKey.from_type_string("ssh-ed25519", )`` 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)rr#N)r>rQ identifiersr!)r$r%rQrMrrrfrom_type_strings   zPKey.from_type_stringcCs|jgS)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)clsrrrrRs zPKey.identifierscCsdS)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&msgrrrrr'sz PKey.__init__cCsDd}t|dr |jr d|j}d|jd|d|j|dS)Ncommentz , comment=z PKey(alg=z, bits=z, fp=))hasattrrXalgorithm_nameget_bits fingerprint)r&rXrrr__repr__s z PKey.__repr__cCstS)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)rrrasbytessz PKey.asbytescCs|Sr")rar)rrr __bytes__ szPKey.__bytes__cCst|to|j|jkSr")rDr/_fieldsr&otherrrr__eq__#sz PKey.__eq__cCs t|jSr")hashrcr)rrr__hash__&sz PKey.__hash__cCstdSr")NotImplementedErrorr)rrrrc)sz PKey._fieldscCsdS)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"``). rWrr)rrrget_name-sz PKey.get_namecCs@|dd}d}||kr*||d}n|dd}|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. zssh-rWz-cert-v01@openssh.comz-cert-r)rjreplacesplitupper)r&rTZ cert_tailrrrr[7s zPKey.algorithm_namecCsdS)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`) rrr)rrrr\Ks z PKey.get_bitscCsdS)zf Return ``True`` if this key has the private part necessary for signing data. Frr)rrrcan_signVsz PKey.can_signcCst|S)z Return an MD5 fingerprint of the public part of this key. Nothing secret is revealed. :return: a 16-byte `string ` (binary) of the MD5 fingerprint, in SSH format. )rradigestr)rrrget_fingerprint]s zPKey.get_fingerprintcCsBtt|}|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 =:) rr`rTrnrrprstriprstrip)r&Zhashy hash_nameZb64edcleanedrrrr]hs   zPKey.fingerprintcCstt|ddS)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 ` containing the public part of the key.  rW)rrrarlr)rrr get_base64wszPKey.get_base64cCstS)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. r_)r&r algorithmrrr sign_ssh_dataszPKey.sign_ssh_datacCsdS)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&rrVrrrverify_ssh_sigs zPKey.verify_ssh_sigcCs|||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)rUr}r<rOrrrfrom_private_key_files zPKey.from_private_key_filecCs|||d}|S)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)rUrr<rOrrrrIs zPKey.from_private_keycCs tddS)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 PKeyN Exception)r&r}r<rrrwrite_private_key_files zPKey.write_private_key_filecCs tddS)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 rNr)r&rr<rrrwrite_private_keys zPKey.write_private_keyc Cs(t|d}||||}W5QRX|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. r)rH_read_private_key)r&tagr}r<frrrr_read_private_key_files zPKey._read_private_key_filec Cs2|}|std|d}|j||}t|d}||kr`|s`|d7}|j||}q:|d7}|rv|dnd}|t|ks|dkrtd||} |j|| }| |kr|s| d7} |j|| }q||kr||| |} |j } n6|dkr| ||| |} |j } ntd||| | fS)Nzno lines in {} private key filerrznot a valid {} private key fileZOPENSSHz#encountered {} key, expected {} key) readlinesrformat BEGIN_TAGmatchr(groupEND_TAG_read_private_key_pem_PRIVATE_KEY_FORMAT_ORIGINAL_read_private_key_openssh_PRIVATE_KEY_FORMAT_OPENSSH) r&rrr<linesstartm line_rangekeytypeendrZpkformatrrrrs8     zPKey._read_private_keycCsd}t||jj|dS)Nz={}._read_private_key() spat out an unknown key format id '{}')rrrGr+)r&Zid_errrrr_got_bad_key_format_id%szPKey._got_bad_key_format_idc Csd}i}|d7}|t|krZ||d}t|dkr8qZ|d||d<|d7}qzttd|||}Wn4tjj k r}zt d |W5d}~XYnXd|kr|S|d} | dkrt d | z|d d \} } Wnt d YnX| |j krt d | |dkr0t d |j | d} |j | d} |j | d}tt| }tt||| }t| |||td}|||S)Nrrz: rWbase64 decoding error: {}z proc-typez 4,ENCRYPTEDz"Unknown private key structure "{}"zdek-info,z(Can't parse DEK-info in private key filezUnknown private key cipher "{}"zPrivate key file is encryptedr1r2r4)backend)r(rmrtlowerrrjoinbase64binasciiErrorrr _CIPHER_TABLErrrZgenerate_key_bytesrr r decryptorupdatefinalize)r&rrr<rheaderslinereZ proc_typeZencryption_typeZsaltstrr1r2r4saltrOrrrrr)sR        zPKey._read_private_key_pemc Cszttd|}Wn4tjjk rJ}ztd|W5d}~XYnX|dd}|tkrhtd| |ddd}|\}}} } } | dkrtd| | d \} } |td kr~|td krt j }n(|td krt j }ntd | d|dkrtd| | d\}}tjt|t|d|dd}|dd}|dd}tt|||t}|| }||7}n*|tdkr|tdkr| }ntd| |d}|\}}}}||krtdt|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 rWrNrz)unexpected OpenSSH key header encounteredZsssurrz.unsupported: private keyfile has multiple keysssbcryptz aes256-cbcz aes256-ctrz,unknown cipher `{}` used in private key filezutf-8zprivate key file is encryptedZsu0T)Zignore_few_roundsrnonez.unknown cipher or kdf used in private key fileZuusrz/OpenSSH private key file checkints do not match)rrrrrrrrOPENSSH_AUTH_MAGIC_uint32_cstruct_unpackr CBCZCTRdecoderrZkdfr r AESrrrrr )r&rr<rrZ auth_magicZcstructr1ZkdfnameZ kdf_optionsZ num_pubkeys remainderZpubkeyZ privkey_blobr4rroundsZkey_ivrOZivrZdecrypted_privkeyZ checkint1Z checkint2rZkeydatarrrrXsr           zPKey._read_private_key_opensshc CsZg}d}z|D] }|dkrdtd|||dd}|d7}||||}||7}|||dkrtd|||dd}|d7}||||}||7}t|d}||q|dkrtd|||dd} |d7}|| q|dkr||d }||qqWn0tk rP} ztt| W5d } ~ XYnXt|S) 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 rsz>LrTrrN) structunpackappendrZ inflate_longrrr?tuple) r&rZ strformatZarridxrZs_sizerrrrrrrrs8         zPKey._uint32_cstruct_unpackc CsHttj|tjtjBtjBtdd}|j||||dW5QRXdS)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. )flagsr4wr=N)osfdopenrHO_WRONLYO_TRUNCO_CREATr_write_private_key)r&r}rOrr<rrrr_write_private_key_files  zPKey._write_private_key_filecCs@|dkrt}ntt|}||tjj||dSr") r Z NoEncryptionZBestAvailableEncryptionrwriteZ private_bytesZEncodingZPEMr)r&rrOrr<Z encryptionrrrrs zPKey._write_private_keycCs|}|}t|tr|g}t|tr(|g}|dkr8td||}||krRn<||krv|t||nd}t| |j j |dS)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.) NzKey object may not be emptyz%Invalid key (class: {}, data type: {}) rDr?rrewindget_textrKrraZ get_stringrrGr+)r&rVr$Z cert_typeZ key_typesZ cert_typestype_rrrr_check_type_and_load_cert s"    zPKey._check_type_and_load_certcCsht|trd}ntj|r"d}nd}tt||}|j| s^d}t | |j| ||_ dS)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) rDrrrLisfilegetattr PublicBlobr$ startswithrjrCrZ public_blob)r&value constructorblobrrrrrK>s  zPKey.load_certificate)N)NN)N)N)N)N)N)N)N)N)N)4r+r,r-r.r rr rrrrrrecompilerr staticmethodrPrS classmethodrRr'r^rarbrfrhpropertyrcrjr[r\rorqr]ryr{r|r~rIrrrrrrrrrrrrKrrrrr/[s   I                 %/V1 " 1r/c@sVeZdZdZdddZeddZeddZed d Zd d Z d dZ ddZ dS)ra 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." NcCs||_||_||_dS)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_blobrX)r&rrrXrrrr'rszPublicBlob.__init__c Cs&t|}|}W5QRX||S)zO Create a public blob from a ``-cert.pub``-style file on disk. )rHreadr)rUr}rstringrrrr~s zPublicBlob.from_filec Cs|dd}t|dkr*d}t|||d}tt|d}z|d}Wntk rjd}YnXt|}| }||krd||} td| ||||dS) zI Create a public blob from a ``-cert.pub``-style string. Nr7z%Not enough fields for public blob: {}rrz!key type={!r}, but blob type={!r}zInvalid PublicBlob contents: {})rrrX) rmr(rCrrrrt IndexErrorrr) rUrfieldsrVr$rrXrZ blob_typeZdeetsrrrrs&   zPublicBlob.from_stringcCs|}|||dS)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." )rr)rra)rUmessagerrrrrszPublicBlob.from_messagecCs&d|j}|jr"|d|j7}|S)Nz{} public key/certificatez- {})rr$rX)r&retrrrr*s zPublicBlob.__str__cCs|o|o|j|jkSr")rrdrrrrfszPublicBlob.__eq__cCs ||k Sr"rrdrrr__ne__szPublicBlob.__ne__)N) r+r,r-r.r'rrrrr*rfrrrrrrds    r).r.rrrrrrpathlibrhashlibrrrrrZcryptography.hazmat.backendsrZcryptography.hazmat.primitivesr Z&cryptography.hazmat.primitives.ciphersr r r r r>rZ paramiko.utilrrZparamiko.commonrZparamiko.ssh_exceptionrrZparamiko.messagerZ/cryptography.hazmat.decrepit.ciphers.algorithmsr ImportErrorZ1cryptography.hazmat.primitives.ciphers.algorithmsrr rr!r/rrrrrsB