3 L]]Q@sdZddlZddlmZddlZddlmZddlmZddl m Z ddl m Z m Z mZddlmZdd lmZdd lmZmZmZmZmZdd lmZmZdd lmZGd ddeZGdddeZ dS)z! Common API for all public keys. N) unhexlify)md5)default_backend) serialization) algorithmsmodesCipher)util)o600)u encodebytes decodebytesb string_types) SSHExceptionPasswordRequiredException)Messagec@seZdZdZejddejdejddejdejddejddZ d5d d Z d d Z d dZ ddZ ddZddZddZddZddZddZddZdd Zed6d!d"Zed7d#d$Zd8d%d&Zd9d'd(Zd:d)d*Zd;d+d,ZdPKeyz% Base class for public keys. )cipherkeysize blocksizemode )z AES-128-CBCz AES-256-CBCz DES-EDE3-CBCNcCsdS)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. N)selfmsgdatarr3/tmp/pip-install-wfra5znf/paramiko/paramiko/pkey.py__init__Bsz 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. )bytes)rrrr asbytesTsz PKey.asbytescCs|jS)N)r#)rrrr __str__\sz PKey.__str__cCs4t|}t|}||kr"t||St|j|jS)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#)rotherZhsZhorrr __cmp__bs  z PKey.__cmp__cCst|t|kS)N)r%)rr'rrr __eq__qsz 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"``). r)rrrr get_nametsz 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`) rr)rrrr get_bits~sz PKey.get_bitscCsdS)zf Return ``True`` if this key has the private part necessary for signing data. Fr)rrrr can_signsz PKey.can_signcCst|jjS)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#digest)rrrr get_fingerprints zPKey.get_fingerprintcCstt|jjddS)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.  r*)r r r#replace)rrrr 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")rrrrr 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)rrrrrr verify_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)clsr5r6keyrrr from_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_objr6r)r7r:r6r8rrr from_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 zNot implemented in PKeyN) Exception)rr5r6rrr write_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 zNot implemented in PKeyN)r<)rr:r6rrr write_private_keys zPKey.write_private_keyc Cs(t|d}|j|||}WdQRX|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. rN)open_read_private_key)rtagr5r6frrrr _read_private_key_files zPKey._read_private_key_filecCsD|j}d}d|d}x(|t|kr@||j|kr@|d7}qW|t|kr^td|di}|d7}xL|t|kr||jd}t|dkrP|dj||dj<|d7}qlW|} d|d} x(| t|kr|| j| kr| d7} qWyttd j||| } Wn8t j j k rH} ztd t | WYdd} ~ XnXd |krX| S|d } | d krxtd j | y|djd\}}WntdYnX||jkrtdj ||dkrtd|j|d}|j|d}|j|d}tt|}tjt|||}t||||tdj}|j| |jS)Nrz -----BEGIN z PRIVATE KEY-----z not a valid z private key filez: z -----END r*zbase64 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 encryptedrrr)backend) readlineslenstriprsplitlowerr rjoinbase64binasciiErrorstrformat _CIPHER_TABLErrr Zgenerate_key_bytesrrr decryptorupdatefinalize)rrBrCr6linesstartZbeginning_of_keyheaderslineendZ ending_of_keyreZ proc_typeZencryption_typeZsaltstrrrrZsaltr8rTrrr rAs\       "       zPKey._read_private_keyc Cs8t|d$}tj|t|j||||dWdQRXdS)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)r6N)r@oschmodr _write_private_key)rr5r8rRr6rCrrr _write_private_key_fileTs  zPKey._write_private_key_filecCs@|dkrtj}ntjt|}|j|jtjj||jdS)N) rZ NoEncryptionZBestAvailableEncryptionrwriteZ private_bytesEncodingZPEMdecode)rrCr8rRr6Z encryptionrrr r`gs  zPKey._write_private_keycCs|}|}t|tr|g}t|tr(|g}|dkr8td|j|j}||krRn<||krv|jt|j|jnd}t|j |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_stringrR __class____name__)rrkey_typeZ cert_typeZ key_typesZ cert_typestype_errrrr _check_type_and_load_certss"    zPKey._check_type_and_load_certcCsht|trd}ntjj|r"d}nd}tt||}|jj|j s^d}t |j |j|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) rerr^pathisfilegetattr PublicBlobrk startswithr+ ValueErrorrRZ public_blob)rvalue constructorblobrmrrr rhs  zPKey.load_certificate)NN)N)N)N)N)N)N)N)N)!rj __module__ __qualname____doc__rZAESrZCBCZ TripleDESrSr!r#r$r(r)r+r,r-r/r2r3r4 classmethodr9r;r=r>rDrArar`rnrhrrrr r'sJ            :  /rc@sVeZdZdZdddZeddZeddZed d Zd d Z d dZ ddZ dS)rua 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)rkkey_blobcomment)rrlrzrrrr r!szPublicBlob.__init__c Cs&t|}|j}WdQRX|j|S)zO Create a public blob from a ``-cert.pub``-style file on disk. N)r@readrq)r7r5rCstringrrr rps zPublicBlob.from_filec Cs|jdd}t|dkr*d}t|j||d}tt|d}y|dj}Wntk rjd}YnXt|}|j }||krdj||} tdj| ||||dS) zI Create a public blob from a ``-cert.pub``-style string. Nz%Not enough fields for public blob: {}rrEz!key type={!r}, but blob type={!r}zInvalid PublicBlob contents: {})rlrzr) rKrIrwrRr rrJ IndexErrorrrg) r7rfieldsrrkrrmZ blob_typeZdeetsrrr rqs"   zPublicBlob.from_stringcCs|j}|||jdS)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." )rlrz)rgr#)r7messagerlrrr roszPublicBlob.from_messagecCs&dj|j}|jr"|dj|j7}|S)Nz{} public key/certificatez- {})rRrkr)rretrrr r$s zPublicBlob.__str__cCs|o|o|j|jkS)N)r)rr'rrr r)szPublicBlob.__eq__cCs ||k S)Nr)rr'rrr __ne__szPublicBlob.__ne__)N) rjr{r|r}r!r~rprqror$r)rrrrr rus   ru)!r}rNrOrr^hashlibrZcryptography.hazmat.backendsrZcryptography.hazmat.primitivesrZ&cryptography.hazmat.primitives.ciphersrrrZparamikor Zparamiko.commonr Zparamiko.py3compatr r r rrZparamiko.ssh_exceptionrrZparamiko.messagerobjectrrurrrr s"       $