U q`l@sdZddlZddlmZddlZddlmZddlZddlZddl Z ddl Z ddl m Z ddl mZddlmZmZmZddlmZdd lmZdd lmZmZmZmZmZdd lmZmZdd l m!Z!d Z"ddZ#Gddde$Z%Gddde$Z&dS)z! Common API for all public keys. N) unhexlify)md5)default_backend) serialization) algorithmsmodesCipher)util)o600)ub encodebytes decodebytes string_types) SSHExceptionPasswordRequiredException)Messagesopenssh-key-v1cCstt|d}d|kr dkr(nn|S|dkr8tdt|D]$}t||||dkr@tdq@|d| S)N z Invalid key)six indexbytesrrange)dataZpadding_lengthir4/tmp/pip-target-nv4zd3e_/lib/python/paramiko/pkey.py_unpad_openssh/s   rc@sLeZdZdZejddejdejddejdejddejddZ dZ d Z e d Ze d ZdAd dZddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$ZedBd%d&ZedCd'd(ZdDd)d*ZdEd+d,Z dFd-d.Z!dGd/d0Z"d1d2Z#d3d4Z$d5d6Z%d7d8Z&dHd9d:Z'dId;d<Z(d=d>Z)d?d@Z*d S)JPKeyz% Base class for public keys. )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*$NcCsdS)a[ 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 str data: an optional string containing 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)selfmsgrrrr__init___sz PKey.__init__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)rrrasbytesqsz PKey.asbytescCs|SN)r/r.rrr__str__ysz PKey.__str__cCs4t|}t|}||kr"t||St||S)aB Compare this key to another. Returns 0 if this key is equivalent to the given key, or non-0 if they are different. Only the public parts of the key are compared, so a public key will compare equal to its corresponding private key. :param .PKey other: key to compare to. )hashcmpr/)r)otherZhsZhorrr__cmp__s  z PKey.__cmp__cCst|t|kSr0)r2r)r4rrr__eq__sz PKey.__eq__cCsdS)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"``). rr.rrrget_namesz PKey.get_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.rrrget_bitssz PKey.get_bitscCsdS)zf Return ``True`` if this key has the private part necessary for signing data. Frr.rrrcan_signsz 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. )rr/digestr.rrrget_fingerprints zPKey.get_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.  r8)r r r/replacer.rrr get_base64szPKey.get_base64cCstS)z Sign a blob of data with this private key, and return a `.Message` representing an SSH signature message. :param str data: the data to sign. :return: an SSH signature `message <.Message>`. r,)r)rrrr 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 str data: the data that was signed. :param .Message msg: an SSH signature message :return: ``True`` if the signature verifies correctly; ``False`` otherwise. Fr)r)rr*rrrverify_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 )filenamepasswordr)clsrCrDkeyrrrfrom_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_objrDr)rErHrDrFrrrfrom_private_keys 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)rCrDrrrwrite_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 rJNrK)r)rHrDrrrwrite_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: data blob (`str`) that makes 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)open_read_private_key)r)tagrCrDfrrrr_read_private_key_files zPKey._read_private_key_filec Cs |}d}|j||}t|d}||krN|sN|d7}|j||}q(|d7}|rd|dnd}|t|ks||dkrtd||} |j|| }| |kr|s| d7} |j|| }q||kr||| |} |j } n6|dkr| ||| |} |j } ntd||| | fS)Nrrznot a valid {} private key fileZOPENSSHz#encountered {} key, expected {} key) readlines BEGIN_TAGmatchlengrouprformatEND_TAG_read_private_key_pem_PRIVATE_KEY_FORMAT_ORIGINAL_read_private_key_openssh_PRIVATE_KEY_FORMAT_OPENSSH) r)rRrSrDlinesstartmZ line_rangekeytypeendrZpkformatrrrrQ7s4     zPKey._read_private_keycCsd}t||jj|dS)Nz={}._read_private_key() spat out an unknown key format id '{}')rrZ __class____name__)r)Zid_errrrr_got_bad_key_format_idZszPKey._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: r8base64 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 encryptedr"r#r%)backend)rXsplitstriplowerrr joinbase64binasciiErrorrrZ _CIPHER_TABLErrr Zgenerate_key_bytesrrr decryptorupdatefinalize)r)r`rdrDraheaderslinereZ proc_typeZencryption_typeZsaltstrr"r#r%saltrFrtrrrr\^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 r8riNrz)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)rr rorprqrrrrZOPENSSH_AUTH_MAGIC_uint32_cstruct_unpackrCBCZCTRdecoderr|ZkdfrrAESrrtrurvr)r)r`rDrryZ auth_magicZcstructr"ZkdfnameZ kdf_optionsZ num_pubkeys remainderZpubkeyZ privkey_blobr%rzroundsZkey_ivrFZivrtZdecrypted_privkeyZ checkint1Z checkint2rcZkeydatarrrr^sr           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>LrTr rON) structunpackappendr Z inflate_longrLrstrtuple) r)rZ strformatZarridxrSZs_sizerrr ryrrrrs8         zPKey._uint32_cstruct_unpackc Cs8t|d$}t|t|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 str 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. w)rDN)rPoschmodr _write_private_key)r)rCrFrZrDrSrrr_write_private_key_files  zPKey._write_private_key_filecCs@|dkrt}ntt|}||tjj||dSr0) rZ NoEncryptionZBestAvailableEncryptionr writeZ private_bytesEncodingZPEMr)r)rSrFrZrDZ encryptionrrrr's 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: {}) isinstancerrrewindget_textload_certificaterr/Z get_stringrZrerf)r)r*key_typeZ cert_typeZ key_typesZ cert_typestype_rgrrr_check_type_and_load_cert3s"    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) rrrpathisfilegetattr PublicBlobr startswithr9 ValueErrorrZZ public_blob)r)value constructorblobrgrrrrbs  zPKey.load_certificate)NN)N)N)N)N)N)N)N)N)+rf __module__ __qualname____doc__rrrrZ TripleDESrsr]r_recompilerVr[r+r/r1r5r7r9r:r;r=r@rArB classmethodrGrIrMrNrTrQrhr\r^rrrrrrrrrr >sf             #/V1  /r 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)z Create a new public blob of given type and contents. :param str type_: Type indicator, eg ``ssh-rsa``. :param blob: The blob bytes themselves. :param str comment: A comment, if one was given (e.g. file-based.) N)rkey_blobcomment)r)rrrrrrr+szPublicBlob.__init__c Cs&t|}|}W5QRX||S)zO Create a public blob from a ``-cert.pub``-style file on disk. )rPreadr)rErCrSstringrrrrs 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. Nr(z%Not enough fields for public blob: {}rrz!key type={!r}, but blob type={!r}zInvalid PublicBlob contents: {})rrr) rlrXrrZrr rm IndexErrorrr) rErfieldsr*rrrrbZ 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)rr/)rEmessagerrrrrszPublicBlob.from_messagecCs&d|j}|jr"|d|j7}|S)Nz{} public key/certificatez- {})rZrr)r)retrrrr1s zPublicBlob.__str__cCs|o|o|j|jkSr0)rr6rrrr7szPublicBlob.__eq__cCs ||k Sr0rr6rrr__ne__szPublicBlob.__ne__)N) rfrrrr+rrrrr1r7rrrrrrs    r)'rrprqrrhashlibrrrrr|Zcryptography.hazmat.backendsrZcryptography.hazmat.primitivesrZ&cryptography.hazmat.primitives.ciphersrrrZparamikor Zparamiko.commonr Zparamiko.py3compatr r r rrZparamiko.ssh_exceptionrrZparamiko.messagerrrobjectr rrrrrs0       N