Ϫf!@ dZddlmZddlZddlZddlZddlZddlZddlm Z m Z m Z m Z m Z ddlmZmZmZmZmZddlmZddlmZddlmZdd lmZmZmZdd lmZm Z m!Z!dd lm"Z"dd l#m$Z%dd l&m'Z'm(Z(m)Z)ddl*m+Z+m,Z,m-Z-m.Z.m/Z/ddl0m1Z1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8m9Z9dZ:eZ;eeGddee>e?e?e@fZAGddZBdZCGdde2jZEGddeEZFGddeEZGGdd ZHGd!d"ZIGd#d$ZJe'jd%\ZLZMd&ZNd'ZOd(ZPd)ZQd*ZRd+ZSd,ZTd-ZUd.ZVd/ZWd0ZXd/ZYd1ZZd0Z[d2Z\d3Z]d&Z^d'Z_d(Z`d)Zad*Zbd+Zcd,Zdd4Zed5Zfd6Zgd7Zhd8Zid9Zjd:Zkd;ZliZmeneojD].\ZqZreqjd<seqjd=r*eqemer<0d>emvsd?emvretd@y)Az The lowest level SSH protocol. This handles the key negotiation, the encryption and the compression. The transport layer is described in RFC 4253. Maintainer: Paul Swartz ) annotationsN)md5sha1sha256sha384sha512)AnyCallableDictTupleUnion)UnsupportedAlgorithm)default_backend) serialization)dhecx25519)Cipher algorithmsmodes)Literal) __version__)_kexaddresskeys)MPNSffsgetMPgetNS)deferprotocol)Logger) randbytes) iterbytes networkStringc@ttj|dS)a*Make an SSH multiple-precision integer from big-endian L{bytes}. Used in ECDH key exchange. @type data: L{bytes} @param data: The input data, interpreted as a big-endian octet string. @rtype: L{bytes} @return: The given data encoded as an SSH multiple-precision integer. big)rint from_bytes)datas =/usr/lib/python3/dist-packages/twisted/conch/ssh/transport.py _mpFromBytesr-)s cnnT5) **ceZdZUdZded<y) _MACParamsaP L{_MACParams} represents the parameters necessary to compute SSH MAC (Message Authenticate Codes). L{_MACParams} is a L{tuple} subclass to maintain compatibility with older versions of the code. The elements of a L{_MACParams} are:: 0. The digest object used for the MAC 1. The inner pad ("ipad") string 2. The outer pad ("opad") string 3. The size of the digest produced by the digest object L{_MACParams} is also an object lesson in why tuples are a bad type for public APIs. @ivar key: The HMAC key which will be used. byteskeyN)__name__ __module__ __qualname____doc____annotations__r.r,r0r0<s$ Jr.r0ceZdZdZej dejfejdejfejdejfejdejfejdejfejdejfejdejfejdejfejdejfej dejfejdejfejdejfddejfd Z e eeeeddZd Zd Zd Z dd Zd ZdZdZdZy) SSHCiphersa SSHCiphers represents all the encryption operations that need to occur to encrypt and authenticate the SSH connection. @cvar cipherMap: A dictionary mapping SSH encryption names to 3-tuples of (, , ) @cvar macMap: A dictionary mapping SSH MAC names to hash modules. @ivar outCipType: the string type of the outgoing cipher. @ivar inCipType: the string type of the incoming cipher. @ivar outMACType: the string type of the incoming MAC. @ivar inMACType: the string type of the incoming MAC. @ivar encBlockSize: the block size of the outgoing cipher. @ivar decBlockSize: the block size of the incoming cipher. @ivar verifyDigestSize: the size of the incoming MAC. @ivar outMAC: a tuple of (, , , ) representing the outgoing MAC. @ivar inMAc: see outMAC, but for the incoming MAC.  Nr) 3des-cbc blowfish-cbc aes256-cbc aes192-cbc aes128-cbc cast128-cbc aes128-ctr aes192-ctr aes256-ctr3des-ctr blowfish-ctr cast128-ctrnone) hmac-sha2-512 hmac-sha2-384 hmac-sha2-256 hmac-sha1hmac-md5rJc||_||_||_||_d|_d|_d|_d|_d|_y)NrNr.r.r) outCipType inCipType outMACType inMACType encBlockSize decBlockSizeverifyDigestSizeoutMACinMAC)selfoutCipinCipoutMacinMacs r,__init__zSSHCiphers.__init__sD   !) ( r.c |j|j||}|j|_|jjdz|_|j|j ||}|j|_|jjdz|_|j|j||_ |j|j||_ |jr|jd|_yy)a Set up the ciphers and hashes using the given keys, @param outIV: the outgoing initialization vector @param outKey: the outgoing encryption key @param inIV: the incoming initialization vector @param inKey: the incoming encryption key @param outInteg: the outgoing integrity key @param inInteg: the incoming integrity key. N) _getCipherrR encryptor algorithm block_sizerVrS decryptorrW_getMACrTrYrUrZrX)r[outIVoutKeyinIVinKeyoutInteginIntegos r,setKeyszSSHCiphers.setKeyss OODOOUF ;KK22a7 OODNND% 8KK22a7ll4??H= \\$..': ::$(JJqMD ! r.c |j|\}}}| tSt||d|||d|jdzt S)z Creates an initialized cipher object. @param cip: the name of the cipher, maps into cipherMap @param iv: the initialzation vector @param key: the encryption key @return: the cipher object. Nrbbackend) cipherMap _DummyCipherrrgr)r[cipivr2algorithmClasskeySize modeClasss r,rdzSSHCiphers._getCiphersc.2^^C-@*  !> ! 3x= ) b9>449: ;#%  r.c,|j|}|sy|}|j}|j}|d|d||z zz}|jtj }|jtj }t||||f} || _| S)am Gets a 4-tuple representing the message authentication code. (, , , ) @type mac: L{bytes} @param mac: a key mapping into macMap @type key: L{bytes} @param key: the MAC key. @rtype: L{bytes} @return: The MAC components. rQN) macMap digest_sizerg translatehmactrans_36trans_5Cr0r2) r[macr2mod hashObject digestSize blockSizeirpresults r,rizSSHCiphers._getMACs"kk#&U ++ )) +:'Y-C"DE MM$-- ( MM$-- (S!Q 34  r.c8|jj|S)z Encrypt some data. @type blocks: L{bytes} @param blocks: The data to encrypt. @rtype: L{bytes} @return: The encrypted data. )reupdater[blockss r,encryptzSSHCiphers.encrypt~~$$V,,r.c8|jj|S)z Decrypt some data. @type blocks: L{bytes} @param blocks: The data to decrypt. @rtype: L{bytes} @return: The decrypted data. )rhrrs r,decryptzSSHCiphers.decryptrr.c|jdsytjd||z}tj|jj ||jdj S)aa Create a message authentication code (MAC) for the given packet using the outgoing MAC values. @type seqid: L{int} @param seqid: The sequence ID of the outgoing packet. @type data: L{bytes} @param data: The data to create a MAC for. @rtype: L{str} @return: The serialized MAC. rr.>L)rYstructpackrHMACr2digest)r[seqidr+s r,makeMACzSSHCiphers.makeMACsS{{1~{{4'$.yy$ A?FFHHr.c|jds|dk(Stjd||z}tj|jj ||jdj }tj||S)a Verify an incoming MAC using the incoming MAC values. @type seqid: L{int} @param seqid: The sequence ID of the incoming packet. @type data: L{bytes} @param data: The packet data to verify. @type mac: L{bytes} @param mac: The MAC sent with the packet. @rtype: L{bool} @return: C{True} if the MAC is valid. rr.r)rZrrrrr2rcompare_digest)r[rr+routers r,verifyzSSHCiphers.verifysl zz!}#: {{4'$. $**..$ 1 >EEG""3..r.)rr1r2r1returnz@tuple[None, Literal[b''], Literal[b''], Literal[0]] | _MACParams)r3r4r5r6r TripleDESrCBCBlowfishAESCAST5CTRrurrrrrr~r`rqrdrirrrrr8r.r,r:r:Rs_,!**B :$--r599="EII6"EII6"EII6#))2uyy9"EII6"EII6"EII6 **B :$--r599=#))2uyy9599%I !   F )2, (""$" I"H - -I&/r.r:c g}gd}|D]n}tj|\}}} t|d|z|d|jdzzt j |j |p|S#t$rY~wxYw)z Build a list of ciphers that are supported by the backend in use. @return: a list of supported ciphers. @rtype: L{list} of L{str} ) rFr@rErArDrBrIrCrHr?rGr> rbrs)r:rurrgrreappendr)supportedCipherscscipherryrzr{s r,_getSupportedCiphersrs B ,-7-A-A&-I* , tg~.$.";";q"@AB') ik  # #F + ,  $   sAA<< BBceZdZUdZeZdZdejdzZ dZ dezdze zdze zjZ e Zgd Zej"ZgZeD]-Zej+d d k7seej-d d gz Z/egd z Zej1rej3dddgZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(e&Z)dZ*dZ+dZ,dZ-iZ.de/d<dZ0dZ1dZ2d Z3d!Z4d"Z5d#Z6d$Z7d%Z8d&Z9d'Z:e;d(Zd+Z?d,Z@d-ZAd.ZBd/ZCd0ZDdDd1ZEd2ZFd3ZGd4ZHd5ZId6ZJd7ZKd8ZLd9ZMd:ZNdEd;ZOdEd<ZPd=ZQd>ZRd?ZSd@ZTdAZUdBZVdCZWy)FSSHTransportBasea Protocol supporting basic SSH functionality: sending/receiving packets and message dispatch. To connect to or run a server, you must use SSHClientTransport or SSHServerTransport. @ivar protocolVersion: A string representing the version of the SSH protocol we support. Currently defaults to '2.0'. @ivar version: A string representing the version of the server or client. Currently defaults to 'Twisted'. @ivar comment: An optional string giving more information about the server or client. @ivar supportedCiphers: A list of strings representing the encryption algorithms supported, in order from most-preferred to least. @ivar supportedMACs: A list of strings representing the message authentication codes (hashes) supported, in order from most-preferred to least. Both this and supportedCiphers can include 'none' to use no encryption or authentication, but that must be done manually, @ivar supportedKeyExchanges: A list of strings representing the key exchanges supported, in order from most-preferred to least. @ivar supportedPublicKeys: A list of strings representing the public key algorithms supported, in order from most-preferred to least. @ivar supportedCompressions: A list of strings representing compression types supported, from most-preferred to least. @ivar supportedLanguages: A list of strings representing languages supported, from most-preferred to least. @ivar supportedVersions: A container of strings representing supported ssh protocol version numbers. @ivar isClient: A boolean indicating whether this is a client or server. @ivar gotVersion: A boolean indicating whether we have received the version string from the other side. @ivar buf: Data we've received but hasn't been parsed into a packet. @ivar outgoingPacketSequence: the sequence number of the next packet we will send. @ivar incomingPacketSequence: the sequence number of the next packet we are expecting from the other side. @ivar outgoingCompression: an object supporting the .compress(str) and .flush() methods, or None if there is no outgoing compression. Used to compress outgoing data. @ivar outgoingCompressionType: A string representing the outgoing compression type. @ivar incomingCompression: an object supporting the .decompress(str) method, or None if there is no incoming compression. Used to decompress incoming data. @ivar incomingCompressionType: A string representing the incoming compression type. @ivar ourVersionString: the version string that we sent to the other side. Used in the key exchange. @ivar otherVersionString: the version string sent by the other side. Used in the key exchange. @ivar ourKexInitPayload: the MSG_KEXINIT payload we sent. Used in the key exchange. @ivar otherKexInitPayload: the MSG_KEXINIT payload we received. Used in the key exchange @ivar sessionID: a string that is unique to this SSH session. Created as part of the key exchange, sessionID is used to generate the various encryption and authentication keys. @ivar service: an SSHService instance, or None. If it's set to an object, it's the currently running service. @ivar kexAlg: the agreed-upon key exchange algorithm. @ivar keyAlg: the agreed-upon public key type for the key exchange. @ivar currentEncryptions: an SSHCiphers instance. It represents the current encryption and authentication options for the transport. @ivar nextEncryptions: an SSHCiphers instance. Held here until the MSG_NEWKEYS messages are exchanged, when nextEncryptions is transitioned to currentEncryptions. @ivar first: the first bytes of the next packet. In order to avoid decrypting data twice, the first bytes are decrypted and stored until the whole packet is available. @ivar _keyExchangeState: The current protocol state with respect to key exchange. This is either C{_KEY_EXCHANGE_NONE} if no key exchange is in progress (and returns to this value after any key exchange completqes), C{_KEY_EXCHANGE_REQUESTED} if this side of the connection initiated a key exchange, and C{_KEY_EXCHANGE_PROGRESSING} if the other side of the connection initiated a key exchange. C{_KEY_EXCHANGE_NONE} is the initial value (however SSH connections begin with key exchange, so it will quickly change to another state). @ivar _blockedByKeyExchange: Whenever C{_keyExchangeState} is not C{_KEY_EXCHANGE_NONE}, this is a C{list} of pending messages which were passed to L{sendPacket} but could not be sent because it is not legal to send them while a key exchange is in progress. When the key exchange completes, another attempt is made to send these messages. @ivar _peerSupportsExtensions: a boolean indicating whether the other side of the connection supports RFC 8308 extension negotiation. @ivar peerExtensions: a dict of extensions supported by the other side of the connection. 2.0sTwisted_asciir.SSH--r)rKrLrMrNrOsecdhecdsa) rsa-sha2-512 rsa-sha2-256ssh-rsasssh-dsss ssh-ed25519rJzlibr8)s1.99rFrN_KEY_EXCHANGE_NONE_KEY_EXCHANGE_REQUESTED_KEY_EXCHANGE_PROGRESSINGs ext-info-cs ext-info-szDict[bytes, bytes]peerExtensionsc|jr|jjt|dr|j|jj dy)a When the underlying connection is closed, stop the running service (if any), and log out the avatar (if any). @type reason: L{twisted.python.failure.Failure} @param reason: The cause of the connection being closed. avatarzconnection lostN)serviceserviceStoppedhasattrlogoutFunction_loginfo)r[reasons r,connectionLostzSSHTransportBase.connectionLostsB << LL ' ' ) 4 "    ! ()r.c|jj|jdztdddd|_|jj dddddd|j y)z Called when the connection is made to the other side. We sent our version and the MSG_KEXINIT packet. s rJr.N) transportwriteourVersionStringr:currentEncryptionsrq sendKexInitr[s r,connectionMadezSSHTransportBase.connectionMades^ T22W<=",Wgw"P ''S#sCE r.c|j|jk7rtd|jt|j}|j |j r |jn |jdjttftjdtdj|tdj|jtdj|j tdj|j tdj|j"tdj|j"tdj|j$tdj|j$tdj|j&tdj|j&dg |_|j+t|j(dd|j,|_g|_y)a7 Send a I{KEXINIT} message to initiate key exchange or to respond to a key exchange initiated by the peer. @raise RuntimeError: If a key exchange has already been started and it is not appropriate to send a I{KEXINIT} message at this time. @return: L{None} z0Cannot send KEXINIT while key exchange state is r.r<,sN)_keyExchangeStater RuntimeErrorlistsupportedKeyExchangesrisClient _EXT_INFO_C _EXT_INFO_Sjoinr1 MSG_KEXINITr$ secureRandomrsupportedPublicKeysr supportedMACssupportedCompressionssupportedLanguagesourKexInitPayload sendPacketr_blockedByKeyExchange)r[rs r,rzSSHTransportBase.sendKexInits  ! !T%<%< <)),  !%T%?%? @ $$ $ D  43C3C "%{n%&&r*499234499T5567499T2234499T2234499T//01499T//01499T7789499T7789499T4456499T4456' " "  T%;%;AB%?@!%!=!=%'"r.cd|cxkrdkrnn|tttfvSd|cxkrdkr nn |tfvSd|cxkxrdkScS)a Determine if the given message type may be sent while key exchange is in progress. @param messageType: The type of message @type messageType: L{int} @return: C{True} if the given type of message may be sent while key exchange is in progress, C{False} if it may not. @rtype: L{bool} @see: U{http://tools.ietf.org/html/rfc4253#section-7.1} r1)MSG_SERVICE_REQUESTMSG_SERVICE_ACCEPT MSG_EXT_INFOr)r[ messageTypes r,_allowedKeyExchangeMessageTypez/SSHTransportBase._allowedKeyExchangeMessageTypePs^ !r !#"'   " "{n4 4[&B&&&&r.c|j|jk7r/|j|s|jj ||fyt |f|z}|j r7|j j||j jdz}|jj}dt|z}|||zz }|dkr||z}tjd||zdz ||ztj|z}|jj!||jj#|j$|z}|j&j)||xj$dz c_y)a Sends a packet. If it's been set up, compress the data, encrypt it, and authenticate it before sending. If key exchange is in progress and the message is not part of key exchange, queue it to be sent later. @param messageType: The type of the packet; generally one of the MSG_* values. @type messageType: L{int} @param payload: The payload for the message. @type payload: L{str} N!LBr)rrrrrr1outgoingCompressioncompressflushrrVlenrrr$rrroutgoingPacketSequencerr)r[rpayloadbs totalSizelenPadpacket encPackets r,rzSSHTransportBase.sendPacketjsi  ! !T%<%< <66{C**11;2HI''1  # #..77((..q12G $ $ 1 1G $ y2~& A:b[F KKy61A5v > $$V, -  ++33   # # + +D,G,G PQ  Y' ##q(#r.c |jj}|jj}t|j|kryt |ds)|jj |jd|}n|j}|`tjd|dd\}}|dkDr#|jttd|yt|j|dz|zkr||_y|dz|zdk7r/|jttd |dz||dz|zfzy|jdd|z|jd|zdc}|_||jj ||dz}t|d|zk7r|jtd y|rb|jd||j|dc}|_|jj|j||s|jtd y|d| } |j r |j j#| } |xjdz c_| S#t$$r4|j&j)d |jt*d YywxYw)z Try to return a decrypted, authenticated, and decompressed packet out of the buffer. If there is not enough data, return None. @rtype: L{str} or L{None} @return: The decoded packet, if any. Nfirstrrizbad packet length rrzbad packet mod (%i%%%i == %i)sbad decryptionsbad MACzError decompressing payloadscompression errorr)rrWrXrbufrrrrunpacksendDisconnectDISCONNECT_PROTOCOL_ERRORr&rincomingPacketSequenceDISCONNECT_MAC_ERRORincomingCompression decompress ExceptionrfailureDISCONNECT_COMPRESSION_ERROR) r[rmsr packetLen paddingLenencDatarmacDatars r, getPacketzSSHTransportBase.getPackets} $ $ 1 1  $ $ 5 5 txx=2  tW%++33DHHSbMBEJJE & eU2AY ? : w    ) 29+>?   txx=9q=2- -DJ  MR 1 $   )3 1}b9q=B*>?@   HH_q9}5txxI 7P0088FF v;!i- '    9;L M  $" txx} GTX**11++VW##$8*EJ;'  # # 22==gF ##q(#   !!"?@##$@BVW  sI :JJc6|jtd|zy)z Called when an unsupported version of the ssh protocol is received from the remote endpoint. @param remoteVersion: remote ssh protocol version which is unsupported by us. @type remoteVersion: L{str} s bad version N)r)DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED)r[ remoteVersions r,_unsupportedVersionReceivedz,SSHTransportBase._unsupportedVersionReceiveds  57V r.c|j|z|_|jst|jdkDr|jtdy|jj d|jj ddk(ry|jj d}|D]}|jdsd|_|jd|_ |j d d }||jvr|j|y|j|}dj||d zd|_|j}|r7t|d d }|j!||d d|j}|r6yy) a First, check for the version string (SSH-2.0-*). After that has been received, this method adds data to the buffer, and pulls out any packets. @type data: L{bytes} @param data: The data that was received. isKPeer version string longer than 4KB. Preventing a denial of service attack.N rrT rrr)r gotVersionrrDISCONNECT_CONNECTION_LOSTfindsplit startswithrstripotherVersionStringsupportedVersionsrindexrrorddispatchMessage)r[r+linesprrr messageNums r, dataReceivedzSSHTransportBase.dataReceivedsT88d?488}t###.> xx}}UDHHMM'$:;rA HHNN5)E :<<(&*DO/0hhuoD+$%GGDM!$4M$D,B,BB88G AA$zz%A.9DH :!VAa[)J  VABZ 8^^%Fr.cx|dkr^|tvrVt|dd}t|d|d}| ||y|jjd|||j y|j r|j j ||y|jjd|||j y) z Send a received message to the appropriate method. @type messageNum: L{int} @param messageNum: The message number. @type payload: L{bytes} @param payload: The message payload. 2rNssh_z*couldn't handle {messageType}: {payload!r})rrz)couldn't handle {messageNum}: {payload!r})r%r)messagesgetattrrdebugsendUnimplementedrpacketReceived)r[r%rrfs r,r"z SSHTransportBase.dispatchMessage s ?zX5":.qr2K[M2D9A}'  @ +#  &&( \\ LL ' ' G < IIOO;%    " " $r.c\tj|jjS)z Returns an L{SSHTransportAddress} corresponding to the other (peer) side of this transport. @return: L{SSHTransportAddress} for the peer @rtype: L{SSHTransportAddress} @since: 12.1 )rSSHTransportAddressrgetPeerrs r,r2zSSHTransportBase.getPeer)"**4>>+A+A+CDDr.c\tj|jjS)z Returns an L{SSHTransportAddress} corresponding to the this side of transport. @return: L{SSHTransportAddress} for the peer @rtype: L{SSHTransportAddress} @since: 12.1 )rr1rgetHostrs r,r5zSSHTransportBase.getHost4r3r.c|jS)zS The key exchange algorithm name agreed between client and server. _kexAlgrs r,kexAlgzSSHTransportBase.kexAlg?s ||r.c||_y)z6 Set the key exchange algorithm name. Nr7)r[values r,r9zSSHTransportBase.kexAlgFs  r.c ttf|z|_t|ddd}|dd|d}}d|D\ }}}}} } } } } }|| | g}|| | g}|jr||}}|j |j |j|j|j|j|j|jf}|||d|d|d|d|d|df}|jr||}}t|d|d|_ t|d|d|_ tt|d|dt|d |d t|d |d t|d |d |_t|d |d |_t|d |d |_d|j|j|j|j fvs$|j|j"|j$fvr|j't(dyd|jj*j-vr|j't(dy|jr |j$n |j"|v|_|j0j3d|j|j|j0j3d|jj4|jj6|j|j0j3d|jj8|jj:|j |j<|j>k(r|j@|_n|jC|||fS)a Called when we receive a MSG_KEXINIT message. Payload:: bytes[16] cookie string keyExchangeAlgorithms string keyAlgorithms string incomingEncryptions string outgoingEncryptions string incomingAuthentications string outgoingAuthentications string incomingCompressions string outgoingCompressions string incomingLanguages string outgoingLanguages bool firstPacketFollows unit32 0 (reserved) Starts setting up the key exchange, keys, encryptions, and authentications. Extended by ssh_KEXINIT in SSHServerTransport and SSHClientTransport. @type packet: L{bytes} @param packet: The message data. @return: A L{tuple} of negotiated key exchange algorithms, key algorithms, and unhandled data, or L{None} if something went wrong. r<N rc3>K|]}|jdyw)rN)r).0ss r, z/SSHTransportBase.ssh_KEXINIT..s ,qQWWT] ,srrrrcrrscouldn't match all kex partsz%kex alg={kexAlg!r} key alg={keyAlg!r})r9keyAlgz)outgoing: {cip!r} {mac!r} {compression!r})rwr compressionz)incoming: {cip!r} {mac!r} {compression!r})"r1rotherKexInitPayloadr rrrrrrrr9rDr:nextEncryptionsoutgoingCompressionTypeincomingCompressionTyperrrDISCONNECT_KEY_EXCHANGE_FAILED__dict__values_peerSupportsExtensionsrr,rRrTrSrUrrrr)r[rkstringsrestkexAlgskeyAlgsencCSencSCmacCSmacSCcompCScompSClangCSlangSCoutsinsserverclients r, ssh_KEXINITzSSHTransportBase.ssh_KEXINIT[s}6$)+#86#A  &+r "#2" -G ,          uf%eV$ ==T#D  & &  $ $  ! !  ! !        & &  & &  7DGSVT!Wc!fd1gsSTvV ==#VFF&)VAY/ &)VAY/ ) q 6!9 % q 6!9 % q 6!9 % q 6!9 %   (+6!9fQi'@$'*6!9fQi'@$   ,,,,  {{t//1A1ABB   .0O   4''00779 9   .0O   $ D  43C3C ($  3;;;;   7$$//$$//44   7$$..$$..44    ! !T%A%A A%)%C%CD "    %%r.ctjd|ddd}t|dd\}}|j|||jj y)a< Called when we receive a MSG_DISCONNECT message. Payload:: long code string description This means that the other side has disconnected. Pass the message up and disconnect ourselves. @type packet: L{bytes} @param packet: The message data. rNrr)rrr receiveErrorrloseConnection)r[r reasonCode descriptionfoos r,ssh_DISCONNECTzSSHTransportBase.ssh_DISCONNECTsT]]44Q7  , S *k2 %%'r.cy)z Called when we receive a MSG_IGNORE message. No payload. This means nothing; we simply return. @type packet: L{bytes} @param packet: The message data. Nr8r[rs r, ssh_IGNOREzSSHTransportBase.ssh_IGNOREsr.cVtjd|\}|j|y)z Called when we receive a MSG_UNIMPLEMENTED message. Payload:: long packet This means that the other side did not implement one of our packets. @type packet: L{bytes} @param packet: The message data. rN)rrreceiveUnimplemented)r[rseqnums r,ssh_UNIMPLEMENTEDz"SSHTransportBase.ssh_UNIMPLEMENTEDs$MM$/  !!&)r.c~tt|dd}t|ddd\}}}|j|||y)a0 Called when we receive a MSG_DEBUG message. Payload:: bool alwaysDisplay string message string language This means the other side has passed along some debugging info. @type packet: L{bytes} @param packet: The message data. rrNr)boolr!r receiveDebug)r[r alwaysDisplaymessagelangres r, ssh_DEBUGzSSHTransportBase.ssh_DEBUGsDS!-. "6!":q1s -$7r.ctjd|dd\}|dd}i}t|D]}t|d\}}}|||<||_y)aD Called when we get a MSG_EXT_INFO message. Payload:: uint32 nr-extensions repeat the following 2 fields "nr-extensions" times: string extension-name string extension-value (binary) @type packet: L{bytes} @param packet: The message data. rNrr)rrranger r)r[r numExtensions extensions_extNameextValues r, ssh_EXT_INFOzSSHTransportBase.ssh_EXT_INFO sh"==vbqz: }% +A(-fa(8 %GXv"*Jw  +)r.c|jjd|j|jr|jj ||_||_|jj y)z Set our service to service and start it running. If we were running a service previously, stop it first. @type service: C{SSHService} @param service: The service to attach. zstarting service {service!r})rN)rr,namerrrserviceStarted)r[rs r, setServicezSSHTransportBase.setServicesS 6 M << LL ' ' )   ##%r.ch|jt|rdndt|zt|zy)a Send a debug message to the other side. @param message: the message to send. @type message: L{str} @param alwaysDisplay: if True, tell the other side to always display this message. @type alwaysDisplay: L{bool} @param language: optionally, the language the message is in. @type language: L{str} r}N)r MSG_DEBUGr)r[rrrqlanguages r, sendDebugzSSHTransportBase.sendDebug.s+  ER[H2h<W r.cB|jtt|y)a Send a message that will be ignored by the other side. This is useful to fool attacks based on guessing packet sizes in the encrypted stream. @param message: data to send with the message @type message: L{str} N)r MSG_IGNOREr)r[rrs r, sendIgnorezSSHTransportBase.sendIgnore>s  BwK0r.cp|j}|jttjd|y)zc Send a message to the other side that the last packet was not understood. z!LN)rrMSG_UNIMPLEMENTEDrrr[rls r,r-z"SSHTransportBase.sendUnimplementedIs) ,, )6;;tV+DEr.c|jttjd|t |zt dz|j j d|||jjy)aJ Send a disconnect message to the other side and then disconnect. @param reason: the reason for the disconnect. Should be one of the DISCONNECT_* values. @type reason: L{int} @param desc: a descrption of the reason for the disconnection. @type desc: L{str} rr.z;Disconnecting with error, code {code} reason: {description}coderdN) rMSG_DISCONNECTrrrrrrrb)r[rdescs r,rzSSHTransportBase.sendDisconnectQs`  D&(ABtH(LrRUw(VW  J  %%'r.c  |jrqdjtjdt |g|Dcgc]\}}t |t |zc}}z}|j t|yycc}}w)a Send an RFC 8308 extension advertisement to the remote peer. Nothing is sent if the peer doesn't support negotiations. @type extensions: L{list} of (L{bytes}, L{bytes}) @param extensions: a list of (extension-name, extension-value) pairs. r.rN)rMrrrrrrr)r[rxr~r;rs r, sendExtInfozSSHTransportBase.sendExtInfocsp  ' 'hhT3z?34;EFKD%2d8bi'FGG OOL' 2 (Gs!A? c8tj|j|j}|j t }|j |_|jjjj}t||_ y)z Prepares for a Diffie-Hellman key agreement exchange. Creates an ephemeral keypair in the group defined by (self.g, self.p) and stores it. N) rDHParameterNumbersr$g parametersrgenerate_private_key dhSecretKey public_keypublic_numbersyrdhSecretKeyPublicMP)r[numbersrrs r,_startEphemeralDHz"SSHTransportBase._startEphemeralDHrsq''7''(9: %::<    ' ' ) 8 8 : < <#%a5 r.ctj|tj|j|jj t }|jj|}|`|jd}t|dd}|dzr*tjdt|dzdz}||zStjdt|}||zS)a  Completes the Diffie-Hellman key agreement started by _startEphemeralDH, and forgets the ephemeral secret key. @type remoteDHpublicKey: L{int} @rtype: L{bytes} @return: The new shared secret, in SSH C{mpint} format. r}rrr)rDHPublicNumbersrr$rrrrexchangelstripr!rrr)r[remoteDHpublicKey remoteKeysecretchprefixs r,_finishEphemeralDHz#SSHTransportBase._finishEphemeralDHs&& r44TVVTVVD *_& ' !!**95   w' !  9[[s6{Q7'AF[[s6{3Fr.cftj|j}|||z|z|jz}|j }|||z|zj }|||z|z|zj }|||z|z|z|zj }||z|z|zS)a Get one of the keys for authentication/encryption. @type c: L{bytes} @param c: The letter identifying which key this is. @type sharedSecret: L{bytes} @param sharedSecret: The shared secret K. @type exchangeHash: L{bytes} @param exchangeHash: The hash H from key exchange. @rtype: L{bytes} @return: The derived key. )rgetHashProcessorr9 sessionIDr) r[c sharedSecret exchangeHash hashProcessork1k2k3k4s r,_getKeyzSSHTransportBase._getKeys --dkk: <,6:T^^K L YY[ <,6; < C C E <,6;b@ A H H J <,6;b@2E F M M OBw|b  r.c |js||_|jd||}|jd||}|jd||}|jd||}|jd||}|jd||}|||g} |||g} |jr| | } } |jj | d| d| d| d| d | d |j t d y ) a Set up the keys for the connection and sends MSG_NEWKEYS when finished, @param sharedSecret: a secret string agreed upon using a Diffie- Hellman exchange, so it is only shared between the server and the client. @type sharedSecret: L{str} @param exchangeHash: A hash of various data known by both sides. @type exchangeHash: L{str} ABCDEFrrrr.N)rrrrGrqr MSG_NEWKEYS) r[rrinitIVCSinitIVSCencKeyCSencKeySC integKeyCS integKeySCr[r\s r, _keySetupzSSHTransportBase._keySetups~~)DN<<lLA<<lLA<<lLA<<lLA\\$ lC \\$ lC (J/:. ==T#D $$T!Wd1gs1vs1vtAwPSTUPVW  S)r.c~|jjd|j|_|jdk(rt j d|_|jdk(rt j|_ |j|_ |j}d|_ |D]\}}|j||y)a* Called back by a subclass once a I{MSG_NEWKEYS} message has been received. This indicates key exchange has completed and new encryption and compression parameters should be adopted. Any messages which were queued during key exchange will also be flushed. zNEW KEYSrrBN)rr,rGrrHzlib compressobjrrI decompressobjrrrrr)r[r*rrs r,_newKeyszSSHTransportBase._newKeyss  #"&"6"6  ' '7 2'+'7'7':D $  ' '7 2'+'9'9';D $!%!8!8--%)"$, 2 K OOK 1 2r.c|dk(r|jjdk7S|dk(r|jjdk7S|dk(r$|jdxr|jdSt d)z Check if the connection is encrypted in the given direction. @type direction: L{str} @param direction: The direction: one of 'out', 'in', or 'both'. @rtype: L{bool} @return: C{True} if it is encrypted. outrJinboth(direction must be "out", "in", or "both")rrRrS isEncrypted TypeErrorr[ directions r,rzSSHTransportBase.isEncryptedsw  **55@ @ $ **44? ? & ##D)Ed.>.>u.E EFG Gr.c|dk(r|jjdk7S|dk(r|jjdk7S|dk(r$|jdxr|jdSt d)a  Check if the connection is verified/authentication in the given direction. @type direction: L{str} @param direction: The direction: one of 'out', 'in', or 'both'. @rtype: L{bool} @return: C{True} if it is verified. rrJrrr)rrTrU isVerifiedrrs r,rzSSHTransportBase.isVerifiedss  **55@ @ $ **44? ? & ??4(CT__U-C CFG Gr.c0|jtdy)zn Lose the connection to the other side, sending a DISCONNECT_CONNECTION_LOST message. suser closed connectionN)rrrs r,rbzSSHTransportBase.loseConnection s 68QRr.c@|jjd||y)a Called when we receive a disconnect error message from the other side. @param reasonCode: the reason for the disconnect, one of the DISCONNECT_ values. @type reasonCode: L{int} @param description: a human-readable description of the disconnection. @type description: L{str} z3Got remote error, code {code} reason: {description}rN)rerror)r[rcrds r,razSSHTransportBase.receiveErrors"  B#  r.c>|jjd|y)z Called when we receive an unimplemented packet message from the other side. @param seqnum: the sequence number that was not understood. @type seqnum: L{int} z)other side unimplemented packet #{seqnum})rlN)rwarnrs r,rkz%SSHTransportBase.receiveUnimplemented&s B6Rr.cD|r|jjd|yy)a Called when we receive a debug message from the other side. @param alwaysDisplay: if True, this message should always be displayed. @type alwaysDisplay: L{bool} @param message: the debug message @type message: L{str} @param lang: optionally the language the message is in. @type lang: L{str} zRemote Debug Message: {message})rrN)rr,)r[rqrrrss r,rpzSSHTransportBase.receiveDebug0s!  IIOO=wO O r.c|jjdrB tjd|jddz}t j|tS|jdvrtjjSt dj|j#t$r t dwxYw)a> Generate an private key for ECDH key exchange. @rtype: The appropriate private key type matching C{self.kexAlg}: L{ec.EllipticCurvePrivateKey} for C{ecdh-sha2-nistp*}, or L{x25519.X25519PrivateKey} for C{curve25519-sha256}. @return: The generated private key. ecdh-sha2-nistprrN unused-keyscurve25519-sha256scurve25519-sha256@libssh.orgz3Cannot generate elliptic curve private key for {!r}) r9rr _curveTableKeyErrorrrrrrX25519PrivateKeygenerateformat)r[curves r,_generateECPrivateKeyz&SSHTransportBase._generateECPrivateKey?s ;; ! !"4 5 9((DKKO)CD**5/2CD D [[S S**335 5&ELLKK  9*<88 9s #B..Cc|jjdrB|jtjj tj jS|jdvrB|jtjjtj jStd|j)a Encode an elliptic curve public key to bytes. @type ecPub: The appropriate public key type matching C{self.kexAlg}: L{ec.EllipticCurvePublicKey} for C{ecdh-sha2-nistp*}, or L{x25519.X25519PublicKey} for C{curve25519-sha256}. @param ecPub: The public key to encode. @rtype: L{bytes} @return: The encoded public key. rrz,Cannot encode elliptic curve public key for ) r9r public_bytesrEncodingX962 PublicFormatUncompressedPointRawr)r[ecPubs r,_encodeECPublicKeyz#SSHTransportBase._encodeECPublicKeyXs ;; ! !"4 5%%&&++**<< [[S S%%&&**M,F,F,J,J '>t{{oN r.c(|jjdrs tjd|jddz}t jj||}|jt j|}t|S|jdvr;tjj|}|j|}t|St dj|j#t$r t dwxYw)a Generate a shared secret for ECDH key exchange. @type ecPriv: The appropriate private key type matching C{self.kexAlg}: L{ec.EllipticCurvePrivateKey} for C{ecdh-sha2-nistp*}, or L{x25519.X25519PrivateKey} for C{curve25519-sha256}. @param ecPriv: Our private key. @rtype: L{bytes} @return: The generated shared secret, as an SSH multiple-precision integer. rrrNrrz5Cannot generate elliptic curve shared secret for {!r})r9rrrrrrEllipticCurvePublicKeyfrom_encoded_pointrECDHrX25519PublicKeyfrom_public_bytesrr-)r[ecPrivtheirECPubBytesr theirECPubrs r,_generateECSharedSecretz(SSHTransportBase._generateECSharedSecretss ;; ! !"4 5 9((DKKO)CD22EEJ"??2779jALL))[[S S//AA/RJ!??:6LL)) 'GNNKK  9*<88 9s #C<<D)Fr.)r)Xr3r4r5r6r#rprotocolVersiontwisted_versionencodeversioncommentstriprrrrrgetSupportedKeyExchangesrreckeyrreplacered25519_supportedrrrrrrrrrrrrrrrrrrrrrMrr7rrrrrrrr&r"r2r5propertyr9setterr_rfrirmrtr|rrrr-rrrrrrrrrrbrarkrprrrr8r.r,rr@spwr 8DO2O227;;GG/!D(72T9GC eg,-M:D99;'F ::g " $ EMM'8$D#E E FUU**,"">2$g.)HJ CIG.8!<+  K K#)+N&+ *0(d'4%)N<|  +&Z%@ E E  ]](x&t("  *8 )& & 1F($ 3 )<!0*62(H&H&S $S P26"*r.rcTeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd Zy)SSHServerTransporta/ SSHServerTransport implements the server side of the SSH protocol. @ivar isClient: since we are never the client, this is always False. @ivar ignoreNextPacket: if True, ignore the next key exchange packet. This is set when the client sends a guessed key exchange packet but with an incorrect guess. @ivar dhGexRequest: the KEX_DH_GEX_REQUEST(_OLD) that the client sent. The key generation needs this to be stored. @ivar g: the Diffie-Hellman group generator. @ivar p: the Diffie-Hellman group prime. Frcx|dvrd}n|}|jj||jj|fS)a Get the public and private host keys corresponding to the given public key signature algorithm. The factory stores public and private host keys by their key format, which is not quite the same as the key signature algorithm: for example, an ssh-rsa key can sign using any of the ssh-rsa, rsa-sha2-256, or rsa-sha2-512 algorithms. @type keyAlg: L{bytes} @param keyAlg: A public key signature algorithm name. @rtype: 2-L{tuple} of L{keys.Key} @return: The public and private host keys. @raises KeyError: if the factory does not have both a public and a private host key for this signature algorithm. >rrr)factory publicKeys privateKeys)r[rD keyFormats r, _getHostKeyszSSHServerTransport._getHostKeyss@& 7 7"II||&&y14<<3K3KI3VVVr.ctj||}|sy|\}}}t|ddr3|d|jdk7s|d|jdk7rd|_yyy)aM Called when we receive a MSG_KEXINIT message. For a description of the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally, this method checks if a guessed key exchange packet was sent. If it was sent, and it guessed incorrectly, the next key exchange packet MUST be ignored. NrrT)rr_r!rrignoreNextPacket)r[rretvalrQrRrPs r,r_zSSHServerTransport.ssh_KEXINITsu"--dF; %+ "GWd tAay> d88;;1:!9!9!!<<(,%= r.c Ft|\}}|j|j\}}|j}|j |_|j |j }|j||}tj|j}|jt|j|jt|j|jt|j|jt|j |jt|j#|jt||jt||j||j%} |j't(t|j#t|zt|j+| |jz|j-|| y)a Called from L{ssh_KEX_DH_GEX_REQUEST_OLD} to handle elliptic curve key exchanges. Payload:: string client Elliptic Curve Diffie-Hellman public key Just like L{_ssh_KEXDH_INIT} this message type is also not dispatched directly. Extra check to determine if this is really KEX_ECDH_INIT is required. First we load the host's public/private keys. Then we generate the ECDH public/private keypair for the given curve. With that we generate the shared secret key. Then we compute the hash to sign and send back to the client Along with the server's public key and the ECDH public key. @type packet: L{bytes} @param packet: The message data. @return: None.  signatureTypeN)r r rDrrrrrrrr9rrrrrFrblobrrMSG_KEXDH_REPLYsignr) r[rpktPub pubHostKey privHostKeyrencPubrhrs r,_ssh_KEX_ECDH_INITz%SSHServerTransport._ssh_KEX_ECDH_INITs2v#'"3"3DKK"@ K++-&&( ((433FFC  /D ! !$++ . 0 D++,- D))*+ D,,-. D**+, JOO%&' F F xxz    z !j !!,dkk!JK L |\2r.c @t|\}}|j|j\}}tj|j \|_|_|j|j|}tj|j }|jt|j|jt|j|jt|j|jt|j |jt|j#|jt%||j|j&|j||j)}|j+t,t|j#|j&zt|j/||jz|j1||y)aW Called to handle the beginning of a non-group key exchange. Unlike other message types, this is not dispatched automatically. It is called from C{ssh_KEX_DH_GEX_REQUEST_OLD} because an extra check is required to determine if this is really a KEXDH_INIT message or if it is a KEX_DH_GEX_REQUEST_OLD message. The KEXDH_INIT payload:: integer e (the client's Diffie-Hellman public key) We send the KEXDH_REPLY with our host key and signature. @type packet: L{bytes} @param packet: The message data. rN)rr rDrgetDHGeneratorAndPrimer9rr$rrrrrrrrFrrrrrrrrr r[rclientDHpublicKeyrerrrrrs r,_ssh_KEXDH_INITz"SSHServerTransport._ssh_KEXDH_INITs$"'v3"&"3"3DKK"@ K44T[[A  ../@A .D ! !$++ . 0 D++,- D))*+ D,,-. D**+, JOO%&' %&' ))* xxz    z !&& '!!,dkk!JK L |\2r.c|jrd|_ytj|jr|j |Stj |jr|j |S||_tjd|d}|jj|\|_ |_ |j|jt t#|jt#|jzy)a This represents different key exchange methods that share the same integer value. If the message is determined to be a KEXDH_INIT, L{_ssh_KEXDH_INIT} is called to handle it. If it is a KEX_ECDH_INIT, L{_ssh_KEX_ECDH_INIT} is called. Otherwise, for KEX_DH_GEX_REQUEST_OLD payload:: integer ideal (ideal size for the Diffie-Hellman prime) We send the KEX_DH_GEX_GROUP message with the group that is closest in size to ideal. If we were told to ignore the next key exchange packet by ssh_KEXINIT, drop it on the floor and return. @type packet: L{bytes} @param packet: The message data. rNr)rr isFixedGroupr9r isEllipticCurver dhGexRequestrrr getDHPrimerr$rrMSG_KEX_DH_GEX_GROUPr)r[rideals r,ssh_KEX_DH_GEX_REQUEST_OLDz-SSHServerTransport.ssh_KEX_DH_GEX_REQUEST_OLD?s&  $%D !    T[[ )''/ /  ! !$++ .**62 2 &D MM$/2E!\\44U;NDFDF  " " $ OO0"TVV*r$&&z2I Jr.c\|jrd|_y||_tjd|\}}}|jj |\|_|_|j|jtt|jt|j zy)a# Called when we receive a MSG_KEX_DH_GEX_REQUEST message. Payload:: integer minimum integer ideal integer maximum The client is asking for a Diffie-Hellman group between minimum and maximum size, and close to ideal if possible. We reply with a MSG_KEX_DH_GEX_GROUP message. If we were told to ignore the next key exchange packet by ssh_KEXINIT, drop it on the floor and return. @type packet: L{bytes} @param packet: The message data. rNz>3L) rr$rrrr%rr$rrr&r)r[rminr'maxs r,ssh_KEX_DH_GEX_REQUESTz)SSHServerTransport.ssh_KEX_DH_GEX_REQUESTds"  $%D ! " --v6UC007   ,bj2dff:.EFr.c t|\}}|j|j\}}|j|}t j |j }|jt|j|jt|j|jt|j|jt|j|jt|j|j|j|jt|j |jt|j"|jt||j|j$|j||j'}|j)t*t|j|j$zt|j-||jz|j/||y)a Called when we get a MSG_KEX_DH_GEX_INIT message. Payload:: integer e (client DH public key) We send the MSG_KEX_DH_GEX_REPLY message with our host key and signature. @type packet: L{bytes} @param packet: The message data. rN)rr rDrrrr9rrrrrFrrr$rr$rrrrMSG_KEX_DH_GEX_REPLYrrrs r,ssh_KEX_DH_GEX_INITz&SSHServerTransport.ssh_KEX_DH_GEX_INIT~s"'v3"&"3"3DKK"@ K../@A .D ! !$++ . 0 D++,- D))*+ D,,-. D**+, JOO%&' ""# DFF DFF %&' ))* xxz   z !&& '!!,dkk!JK L |\2r.c|jdu}tj||||r.|jddj |j fgyy)3 See SSHTransportBase._keySetup(). Nsserver-sig-algsr)rrrrrr)r[rrfirstKeys r,rzSSHServerTransport._keySetupsV>>T)""4|D    $dii0H0H&IJK  r.c\|dk7r|jtdy|jy)a Called when we get a MSG_NEWKEYS message. No payload. When we get this, the keys have been set on both sides, and we start using them to encrypt and authenticate the connection. @type packet: L{bytes} @param packet: The message data. r.NEWKEYS takes no dataN)rrrrhs r, ssh_NEWKEYSzSSHServerTransport.ssh_NEWKEYSs) S=    9;S T  r.ct|\}}|jj||}|s|jtd|zy|j t t||j|y)aX Called when we get a MSG_SERVICE_REQUEST message. Payload:: string serviceName The client has requested a service. If we can start the service, start it; otherwise, disconnect with DISCONNECT_SERVICE_NOT_AVAILABLE. @type packet: L{bytes} @param packet: The message data. sdon't have service N) r r getServicer DISCONNECT_SERVICE_NOT_AVAILABLErrrr)r[rrrPclss r,ssh_SERVICE_REQUESTz&SSHServerTransport.ssh_SERVICE_REQUESTsif ll%%dG4   02H72R   OO.7 < OOCE "r.N)r3r4r5r6rrr r_rr r(r,r/rr5r:r8r.r,rrsM"HW2-(:3x'3R#KJG4(3T #r.rcteZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZy)SSHClientTransporta) SSHClientTransport implements the client side of the SSH protocol. @ivar isClient: since we are always the client, this is always True. @ivar _gotNewKeys: if we receive a MSG_NEWKEYS message before we are ready to transition to the new keys, this is set to True so we can transition when the keys are ready locally. @ivar x: our Diffie-Hellman private key. @ivar e: our Diffie-Hellman public key. @ivar g: the Diffie-Hellman group generator. @ivar p: the Diffie-Hellman group prime @ivar instance: the SSHService object we are requesting. @ivar _dhMinimalGroupSize: Minimal acceptable group size advertised by the client in MSG_KEX_DH_GEX_REQUEST. @type _dhMinimalGroupSize: int @ivar _dhMaximalGroupSize: Maximal acceptable group size advertised by the client in MSG_KEX_DH_GEX_REQUEST. @type _dhMaximalGroupSize: int @ivar _dhPreferredGroupSize: Preferred group size advertised by the client in MSG_KEX_DH_GEX_REQUEST. @type _dhPreferredGroupSize: int Tii ic<tj|d|_y)z{ Called when the connection is started with the server. Just sets up a private instance variable. rN)rr _gotNewKeysrs r,rz!SSHClientTransport.connectionMade s ''-r.c tj||ytj|jrm|j |_|j j|_|jtt|j|jytj|jr]tj|j\|_|_|j#|jt$|j&y|jt(t+j,d|j.|j0|j2y)a> Called when we receive a MSG_KEXINIT message. For a description of the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally, this method sends the first key exchange packet. If the agreed-upon exchange is ECDH, generate a key pair for the corresponding curve and send the public key. If the agreed-upon exchange has a fixed prime/generator group, generate a public key and send it in a MSG_KEXDH_INIT message. Otherwise, ask for a 2048 bit group with a MSG_KEX_DH_GEX_REQUEST message. N!LLL)rr_rr#r9rrrrrMSG_KEX_DH_GEX_REQUEST_OLDrrr"rrr$rMSG_KEXDH_INITrMSG_KEX_DH_GEX_REQUESTrr_dhMinimalGroupSize_dhPreferredGroupSize_dhMaximalGroupSizerhs r,r_zSSHClientTransport.ssh_KEXINITs  ' 'f 5 =     ,446DK//1DJ OO*Bt/F/Ftzz/R,S   t{{ +!88ENDFDF  " " $ OOND,D,D E OO& ,,..,,  r.cVfd}t|d\}}}}djtt|j Dcgc]}t j |c}}j||}|j|||||jfd|Scc}w)a Called to handle a reply to a ECDH exchange message(KEX_ECDH_INIT). Like the handler for I{KEXDH_INIT}, this message type has an overlapping value. This method is called from C{ssh_KEX_DH_GEX_GROUP} if that method detects a non-group key exchange is in progress. Payload:: string serverHostKey string server Elliptic Curve Diffie-Hellman public key string signature We verify the host key and continue if it passes verificiation. Otherwise raise an exception and return. @type packet: L{bytes} @param packet: The message data. @return: A deferred firing when key exchange is complete. cj|}jj|}tjj}|j t j|j t j|j t j|j t j|j t ||j t jj|j t ||j ||j}tjj!|j#||sj%t&dyj)||y)N bad signature)rrrrr9rrrrrrFrrrrKey fromStringrrrJr) ignoredhostKeypubKey signature theirECHostrrrr[s r,_continue_KEX_ECDH_REPLYzHSSHClientTransport._ssh_KEX_ECDH_REPLY.._continue_KEX_ECDH_REPLYWs)!K77 VLL2%%dkk24A HHR--. / HHR//0 1 HHR../ 0 HHR001 2 HHR _ % HHR// ;< = HHRZ HH\ "88:L88&&{3::9lS##$BDTU|\:r.rc:c0jtdSNs bad host keyr"DISCONNECT_HOST_KEY_NOT_VERIFIABLEunusedr[s r,z8SSHClientTransport._ssh_KEX_ECDH_REPLY..|4..2Or.) r rr%rrbinasciihexlify verifyHostKey addCallback addErrback) r[rrQrMrNrOr fingerprintds ` r,_ssh_KEX_ECDH_REPLYz&SSHClientTransport._ssh_KEX_ECDH_REPLY@s. ;2.361-=*F ii,5c'l6I6I6K,L MbX  b ! M    w 4 .K    NsB&ct|\}}t|\}}t|\}}djtt |j Dcgc]}t j|c}}j||}|jj||||jfd|Scc}w)a Called to handle a reply to a non-group key exchange message (KEXDH_INIT). Like the handler for I{KEXDH_INIT}, this message type has an overlapping value. This method is called from C{ssh_KEX_DH_GEX_GROUP} if that method detects a non-group key exchange is in progress. Payload:: string serverHostKey integer f (server Diffie-Hellman public key) string signature We verify the host key by calling verifyHostKey, then continue in _continueKEXDH_REPLY. @type packet: L{bytes} @param packet: The message data. @return: A deferred firing when key exchange is complete. rRc0jtdSrTrUrWs r,rYz5SSHClientTransport._ssh_KEXDH_REPLY..rZr.) r rrr%rrr[r\r]r^_continueKEXDH_REPLYr_)r[rrNr/rOrr`ras` r,_ssh_KEXDH_REPLYz#SSHClientTransport._ssh_KEXDH_REPLYs.v&M 6!&M 6ii,5c&k6H6H6J,K LbX  b ! L    v{ 3 d//IF    MCcptj|jr|j|Stj|jr|j |St |\|_}t |\|_}|j|jt|jy)a This handles different messages which share an integer value. If the key exchange does not have a fixed prime/generator group, we generate a Diffie-Hellman public key and send it in a MSG_KEX_DH_GEX_INIT message. Payload:: string g (group generator) string p (group prime) @type packet: L{bytes} @param packet: The message data. N) rr"r9rfr#rbrr$rrrMSG_KEX_DH_GEX_INITr)r[rrPs r,ssh_KEX_DH_GEX_GROUPz'SSHClientTransport.ssh_KEX_DH_GEX_GROUPs   T[[ )((0 0  ! !$++ .++F3 3 =LDFD ;LDFD  " " $ OO/1I1I Jr.c"tjj|}|j|}t j |j }|jt|j|jt|j|jt|j|jt|j|jt||j|j|jt||j||j}|j!||s|j#t$dy|j'||y) The host key has been verified, so we generate the keys. @param ignored: Ignored. @param pubKey: the public key blob for the server's public key. @type pubKey: L{str} @param f: the server's Diffie-Hellman public key. @type f: L{int} @param signature: the server's signature, verifying that it has the correct private key. @type signature: L{str} rIN)rrJrKrrrr9rrrrrrFrrrrrrJr r[rLrNr/rO serverKeyrrrs r,rez'SSHClientTransport._continueKEXDH_REPLYsHH''/ ..q1 .D ! !$++ . 0 D))*+ D++,- D**+, D,,-. F ))* A xxz  <8    >@P Q  |\2r.ct|\}}t|\}}t|\}}djtt |j Dcgc]}t j|c}}j||}|jj||||jfd|Scc}w)a Called when we receive a MSG_KEX_DH_GEX_REPLY message. Payload:: string server host key integer f (server DH public key) We verify the host key by calling verifyHostKey, then continue in _continueGEX_REPLY. @type packet: L{bytes} @param packet: The message data. @return: A deferred firing once key exchange is complete. rRc0jtdSrTrUrWs r,rYz9SSHClientTransport.ssh_KEX_DH_GEX_REPLY..rZr.) r rrr%rrr[r\r]r^_continueGEX_REPLYr_)r[rrNr/rOrr`ras` r,ssh_KEX_DH_GEX_REPLYz'SSHClientTransport.ssh_KEX_DH_GEX_REPLYsv&M 6!&M 6ii*3CK4F4F4H*I JQX  a J    v{ 3 d--vq)D    Krgc<tjj|}|j|}t j |j }|jt|j|jt|j|jt|j|jt|j|jt||jtjd|j|j |j"|jt%|j&|jt%|j(|j|j*|jt%||j||j-}|j/||s|j1t2dy|j5||y)rlr@rIN)rrJrKrrrr9rrrrrrFrrrDrErFrr$rrrrrrJrrms r,rqz%SSHClientTransport._continueGEX_REPLYsxHH''/ ..q1 .D ! !$++ . 0 D))*+ D++,- D**+, D,,-. F  KK((**((    DFF DFF ))* A xxz  <8    >@P Q  |\2r.cntj||||jr|jdyy)r1r.N)rrr>r5)r[rrs r,rzSSHClientTransport._keySetup&s2 ""4|D      S ! r.c|dk7r|jtdy|jjsd|_y|j |j y)a Called when we receive a MSG_NEWKEYS message. No payload. If we've finished setting up our own keys, start using them. Otherwise, remember that we've received this message. @type packet: L{bytes} @param packet: The message data. r.r4Nr)rrrGrVr>rconnectionSecurerhs r,r5zSSHClientTransport.ssh_NEWKEYS.sO S=    9;S T ##00 D    r.c|dk(r|jjdn=t|d}||jjk7r|j t d|j|jy)z Called when we receive a MSG_SERVICE_ACCEPT message. Payload:: string service name Start the service we requested. @type packet: L{bytes} @param packet: The message data. r.z"got SERVICE_ACCEPT without payloadrs.received accept for service we did not requestN)rrr instancer~rrr)r[rr~s r,ssh_SERVICE_ACCEPTz%SSHClientTransport.ssh_SERVICE_ACCEPT@sb S= IINN? @=#Dt}})))##-E  &r.cd|jtt|j||_y)z Request that a service be run over this transport. @type instance: subclass of L{twisted.conch.ssh.service.SSHService} @param instance: The service to run. N)rrrr~rx)r[rxs r,requestServicez!SSHClientTransport.requestServiceUs# +R ->?  r.c<tjtS)aa Returns a Deferred that gets a callback if it is a valid key, or an errback if not. @type hostKey: L{bytes} @param hostKey: The host key to verify. @type fingerprint: L{bytes} @param fingerprint: The fingerprint of the key. @return: A deferred firing with C{True} if the key is valid. )r!failNotImplementedError)r[rMr`s r,r]z SSHClientTransport.verifyHostKeyaszz-/00r.ct)z Called when the encryption has been set up. Generally, requestService() is called to run another service over the transport. )r~rs r,rvz#SSHClientTransport.connectionSecureps "##r.N)r3r4r5r6rrDrFrErr_rbrfrjrerrrqrr5ryr{r]rvr8r.r,r<r<sq@H!-^@D$LK23>:'3R" $'*! 1$r.r<ceZdZdZdZy)_NullEncryptionContextzH An encryption context that does not actually encrypt anything. c|S)z 'Encrypt' new data by doing nothing. @type data: L{bytes} @param data: The data to 'encrypt'. @rtype: L{bytes} @return: The 'encrypted' data. r8)r[r+s r,rz_NullEncryptionContext.update}s  r.N)r3r4r5r6rr8r.r,rrxs  r.rceZdZdZdZy)_DummyAlgorithmzJ An encryption algorithm that does not actually encrypt anything. @N)r3r4r5r6rgr8r.r,rrsJr.rc*eZdZdZeZdZdZy)rvz A cipher for the none encryption method. @ivar block_size: the block size of the encryption. In the case of the none cipher, this is 8 bytes. ctS)zN Construct a noop encryptor. @return: The encryptor. rrs r,rez_DummyCipher.encryptor &''r.ctS)zN Construct a noop decryptor. @return: The decryptor. rrs r,rhz_DummyCipher.decryptorrr.N)r3r4r5r6rrfrerhr8r.r,rvrvs !I((r.rvsdiffie-hellman-group14-sha1rrrcrrrBrCrr"r=!rb r= MSG_ MSG_KEXDH_rBrz7legacy SSH mnemonics should not end up in messages dict)ur6 __future__rr[rrtypesrhashlibrrrrrtypingr r r r r cryptography.exceptionsrcryptography.hazmat.backendsrcryptography.hazmat.primitivesr)cryptography.hazmat.primitives.asymmetricrrr&cryptography.hazmat.primitives.ciphersrrrrtwistedrrtwisted.conch.sshrrrtwisted.conch.ssh.commonrrrrr twisted.internetr!r"twisted.loggerr#twisted.pythonr$twisted.python.compatr%r&r-_Hashstr ModuleType _DigestModr1r)r0r:rProtocolrrr<rrrvr DH_GENERATORDH_PRIMErrrrrrrrrrBrrArCr&rir.&DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECTrrJDISCONNECT_RESERVEDrr r8rrVrDISCONNECT_BY_APPLICATIONDISCONNECT_TOO_MANY_CONNECTIONS!DISCONNECT_AUTH_CANCELLED_BY_USER)DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLEDISCONNECT_ILLEGAL_USER_NAMEr*rglobalsitemsr~r;rrr8r.r,rsE # 5544888DDLL211>>,!$: +  3U+U-=-== > z5%45,F/F/R"JU*x((U*p"C#)C#L W$)W$t $((65445ST h      *+&!" #$ ,-)%&""$$&!,.)!  )*KD% vt|'D x#4#@ P QQ$Ar.