transport.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  1. # -*- test-case-name: twisted.conch.test.test_transport -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. The lowest level SSH protocol. This handles the key negotiation, the
  6. encryption and the compression. The transport layer is described in
  7. RFC 4253.
  8. Maintainer: Paul Swartz
  9. """
  10. from __future__ import absolute_import, division
  11. import binascii
  12. import hmac
  13. import struct
  14. import zlib
  15. from hashlib import md5, sha1, sha256, sha384, sha512
  16. from cryptography.exceptions import UnsupportedAlgorithm
  17. from cryptography.hazmat.backends import default_backend
  18. from cryptography.hazmat.primitives import serialization
  19. from cryptography.hazmat.primitives.ciphers import algorithms, modes, Cipher
  20. from cryptography.hazmat.primitives.asymmetric import dh, ec, x25519
  21. from twisted import __version__ as twisted_version
  22. from twisted.internet import protocol, defer
  23. from twisted.python import log, randbytes
  24. from twisted.python.compat import iterbytes, _bytesChr as chr, networkString
  25. # This import is needed if SHA256 hashing is used.
  26. # from twisted.python.compat import nativeString
  27. from twisted.conch.ssh import address, keys, _kex
  28. from twisted.conch.ssh.common import (
  29. NS, getNS, MP, getMP, ffs, int_from_bytes
  30. )
  31. def _mpFromBytes(data):
  32. """Make an SSH multiple-precision integer from big-endian L{bytes}.
  33. Used in ECDH key exchange.
  34. @type data: L{bytes}
  35. @param data: The input data, interpreted as a big-endian octet string.
  36. @rtype: L{bytes}
  37. @return: The given data encoded as an SSH multiple-precision integer.
  38. """
  39. return MP(int_from_bytes(data, 'big'))
  40. class _MACParams(tuple):
  41. """
  42. L{_MACParams} represents the parameters necessary to compute SSH MAC
  43. (Message Authenticate Codes).
  44. L{_MACParams} is a L{tuple} subclass to maintain compatibility with older
  45. versions of the code. The elements of a L{_MACParams} are::
  46. 0. The digest object used for the MAC
  47. 1. The inner pad ("ipad") string
  48. 2. The outer pad ("opad") string
  49. 3. The size of the digest produced by the digest object
  50. L{_MACParams} is also an object lesson in why tuples are a bad type for
  51. public APIs.
  52. @ivar key: The HMAC key which will be used.
  53. """
  54. class SSHCiphers:
  55. """
  56. SSHCiphers represents all the encryption operations that need to occur
  57. to encrypt and authenticate the SSH connection.
  58. @cvar cipherMap: A dictionary mapping SSH encryption names to 3-tuples of
  59. (<cryptography.hazmat.primitives.interfaces.CipherAlgorithm>,
  60. <block size>, <cryptography.hazmat.primitives.interfaces.Mode>)
  61. @cvar macMap: A dictionary mapping SSH MAC names to hash modules.
  62. @ivar outCipType: the string type of the outgoing cipher.
  63. @ivar inCipType: the string type of the incoming cipher.
  64. @ivar outMACType: the string type of the incoming MAC.
  65. @ivar inMACType: the string type of the incoming MAC.
  66. @ivar encBlockSize: the block size of the outgoing cipher.
  67. @ivar decBlockSize: the block size of the incoming cipher.
  68. @ivar verifyDigestSize: the size of the incoming MAC.
  69. @ivar outMAC: a tuple of (<hash module>, <inner key>, <outer key>,
  70. <digest size>) representing the outgoing MAC.
  71. @ivar inMAc: see outMAC, but for the incoming MAC.
  72. """
  73. cipherMap = {
  74. b'3des-cbc': (algorithms.TripleDES, 24, modes.CBC),
  75. b'blowfish-cbc': (algorithms.Blowfish, 16, modes.CBC),
  76. b'aes256-cbc': (algorithms.AES, 32, modes.CBC),
  77. b'aes192-cbc': (algorithms.AES, 24, modes.CBC),
  78. b'aes128-cbc': (algorithms.AES, 16, modes.CBC),
  79. b'cast128-cbc': (algorithms.CAST5, 16, modes.CBC),
  80. b'aes128-ctr': (algorithms.AES, 16, modes.CTR),
  81. b'aes192-ctr': (algorithms.AES, 24, modes.CTR),
  82. b'aes256-ctr': (algorithms.AES, 32, modes.CTR),
  83. b'3des-ctr': (algorithms.TripleDES, 24, modes.CTR),
  84. b'blowfish-ctr': (algorithms.Blowfish, 16, modes.CTR),
  85. b'cast128-ctr': (algorithms.CAST5, 16, modes.CTR),
  86. b'none': (None, 0, modes.CBC),
  87. }
  88. macMap = {
  89. b'hmac-sha2-512': sha512,
  90. b'hmac-sha2-384': sha384,
  91. b'hmac-sha2-256': sha256,
  92. b'hmac-sha1': sha1,
  93. b'hmac-md5': md5,
  94. b'none': None
  95. }
  96. def __init__(self, outCip, inCip, outMac, inMac):
  97. self.outCipType = outCip
  98. self.inCipType = inCip
  99. self.outMACType = outMac
  100. self.inMACType = inMac
  101. self.encBlockSize = 0
  102. self.decBlockSize = 0
  103. self.verifyDigestSize = 0
  104. self.outMAC = (None, b'', b'', 0)
  105. self.inMAC = (None, b'', b'', 0)
  106. def setKeys(self, outIV, outKey, inIV, inKey, outInteg, inInteg):
  107. """
  108. Set up the ciphers and hashes using the given keys,
  109. @param outIV: the outgoing initialization vector
  110. @param outKey: the outgoing encryption key
  111. @param inIV: the incoming initialization vector
  112. @param inKey: the incoming encryption key
  113. @param outInteg: the outgoing integrity key
  114. @param inInteg: the incoming integrity key.
  115. """
  116. o = self._getCipher(self.outCipType, outIV, outKey)
  117. self.encryptor = o.encryptor()
  118. self.encBlockSize = o.algorithm.block_size // 8
  119. o = self._getCipher(self.inCipType, inIV, inKey)
  120. self.decryptor = o.decryptor()
  121. self.decBlockSize = o.algorithm.block_size // 8
  122. self.outMAC = self._getMAC(self.outMACType, outInteg)
  123. self.inMAC = self._getMAC(self.inMACType, inInteg)
  124. if self.inMAC:
  125. self.verifyDigestSize = self.inMAC[3]
  126. def _getCipher(self, cip, iv, key):
  127. """
  128. Creates an initialized cipher object.
  129. @param cip: the name of the cipher, maps into cipherMap
  130. @param iv: the initialzation vector
  131. @param key: the encryption key
  132. @return: the cipher object.
  133. """
  134. algorithmClass, keySize, modeClass = self.cipherMap[cip]
  135. if algorithmClass is None:
  136. return _DummyCipher()
  137. return Cipher(
  138. algorithmClass(key[:keySize]),
  139. modeClass(iv[:algorithmClass.block_size // 8]),
  140. backend=default_backend(),
  141. )
  142. def _getMAC(self, mac, key):
  143. """
  144. Gets a 4-tuple representing the message authentication code.
  145. (<hash module>, <inner hash value>, <outer hash value>,
  146. <digest size>)
  147. @type mac: L{bytes}
  148. @param mac: a key mapping into macMap
  149. @type key: L{bytes}
  150. @param key: the MAC key.
  151. @rtype: L{bytes}
  152. @return: The MAC components.
  153. """
  154. mod = self.macMap[mac]
  155. if not mod:
  156. return (None, b'', b'', 0)
  157. # With stdlib we can only get attributes fron an instantiated object.
  158. hashObject = mod()
  159. digestSize = hashObject.digest_size
  160. blockSize = hashObject.block_size
  161. # Truncation here appears to contravene RFC 2104, section 2. However,
  162. # implementing the hashing behavior prescribed by the RFC breaks
  163. # interoperability with OpenSSH (at least version 5.5p1).
  164. key = key[:digestSize] + (b'\x00' * (blockSize - digestSize))
  165. i = key.translate(hmac.trans_36)
  166. o = key.translate(hmac.trans_5C)
  167. result = _MACParams((mod, i, o, digestSize))
  168. result.key = key
  169. return result
  170. def encrypt(self, blocks):
  171. """
  172. Encrypt some data.
  173. @type blocks: L{bytes}
  174. @param blocks: The data to encrypt.
  175. @rtype: L{bytes}
  176. @return: The encrypted data.
  177. """
  178. return self.encryptor.update(blocks)
  179. def decrypt(self, blocks):
  180. """
  181. Decrypt some data.
  182. @type blocks: L{bytes}
  183. @param blocks: The data to decrypt.
  184. @rtype: L{bytes}
  185. @return: The decrypted data.
  186. """
  187. return self.decryptor.update(blocks)
  188. def makeMAC(self, seqid, data):
  189. """
  190. Create a message authentication code (MAC) for the given packet using
  191. the outgoing MAC values.
  192. @type seqid: L{int}
  193. @param seqid: The sequence ID of the outgoing packet.
  194. @type data: L{bytes}
  195. @param data: The data to create a MAC for.
  196. @rtype: L{str}
  197. @return: The serialized MAC.
  198. """
  199. if not self.outMAC[0]:
  200. return b''
  201. data = struct.pack('>L', seqid) + data
  202. return hmac.HMAC(self.outMAC.key, data, self.outMAC[0]).digest()
  203. def verify(self, seqid, data, mac):
  204. """
  205. Verify an incoming MAC using the incoming MAC values.
  206. @type seqid: L{int}
  207. @param seqid: The sequence ID of the incoming packet.
  208. @type data: L{bytes}
  209. @param data: The packet data to verify.
  210. @type mac: L{bytes}
  211. @param mac: The MAC sent with the packet.
  212. @rtype: L{bool}
  213. @return: C{True} if the MAC is valid.
  214. """
  215. if not self.inMAC[0]:
  216. return mac == b''
  217. data = struct.pack('>L', seqid) + data
  218. outer = hmac.HMAC(self.inMAC.key, data, self.inMAC[0]).digest()
  219. return mac == outer
  220. def _getSupportedCiphers():
  221. """
  222. Build a list of ciphers that are supported by the backend in use.
  223. @return: a list of supported ciphers.
  224. @rtype: L{list} of L{str}
  225. """
  226. supportedCiphers = []
  227. cs = [b'aes256-ctr', b'aes256-cbc', b'aes192-ctr', b'aes192-cbc',
  228. b'aes128-ctr', b'aes128-cbc', b'cast128-ctr', b'cast128-cbc',
  229. b'blowfish-ctr', b'blowfish-cbc', b'3des-ctr', b'3des-cbc']
  230. for cipher in cs:
  231. algorithmClass, keySize, modeClass = SSHCiphers.cipherMap[cipher]
  232. try:
  233. Cipher(
  234. algorithmClass(b' ' * keySize),
  235. modeClass(b' ' * (algorithmClass.block_size // 8)),
  236. backend=default_backend(),
  237. ).encryptor()
  238. except UnsupportedAlgorithm:
  239. pass
  240. else:
  241. supportedCiphers.append(cipher)
  242. return supportedCiphers
  243. class SSHTransportBase(protocol.Protocol):
  244. """
  245. Protocol supporting basic SSH functionality: sending/receiving packets
  246. and message dispatch. To connect to or run a server, you must use
  247. SSHClientTransport or SSHServerTransport.
  248. @ivar protocolVersion: A string representing the version of the SSH
  249. protocol we support. Currently defaults to '2.0'.
  250. @ivar version: A string representing the version of the server or client.
  251. Currently defaults to 'Twisted'.
  252. @ivar comment: An optional string giving more information about the
  253. server or client.
  254. @ivar supportedCiphers: A list of strings representing the encryption
  255. algorithms supported, in order from most-preferred to least.
  256. @ivar supportedMACs: A list of strings representing the message
  257. authentication codes (hashes) supported, in order from most-preferred
  258. to least. Both this and supportedCiphers can include 'none' to use
  259. no encryption or authentication, but that must be done manually,
  260. @ivar supportedKeyExchanges: A list of strings representing the
  261. key exchanges supported, in order from most-preferred to least.
  262. @ivar supportedPublicKeys: A list of strings representing the
  263. public key types supported, in order from most-preferred to least.
  264. @ivar supportedCompressions: A list of strings representing compression
  265. types supported, from most-preferred to least.
  266. @ivar supportedLanguages: A list of strings representing languages
  267. supported, from most-preferred to least.
  268. @ivar supportedVersions: A container of strings representing supported ssh
  269. protocol version numbers.
  270. @ivar isClient: A boolean indicating whether this is a client or server.
  271. @ivar gotVersion: A boolean indicating whether we have received the
  272. version string from the other side.
  273. @ivar buf: Data we've received but hasn't been parsed into a packet.
  274. @ivar outgoingPacketSequence: the sequence number of the next packet we
  275. will send.
  276. @ivar incomingPacketSequence: the sequence number of the next packet we
  277. are expecting from the other side.
  278. @ivar outgoingCompression: an object supporting the .compress(str) and
  279. .flush() methods, or None if there is no outgoing compression. Used to
  280. compress outgoing data.
  281. @ivar outgoingCompressionType: A string representing the outgoing
  282. compression type.
  283. @ivar incomingCompression: an object supporting the .decompress(str)
  284. method, or None if there is no incoming compression. Used to
  285. decompress incoming data.
  286. @ivar incomingCompressionType: A string representing the incoming
  287. compression type.
  288. @ivar ourVersionString: the version string that we sent to the other side.
  289. Used in the key exchange.
  290. @ivar otherVersionString: the version string sent by the other side. Used
  291. in the key exchange.
  292. @ivar ourKexInitPayload: the MSG_KEXINIT payload we sent. Used in the key
  293. exchange.
  294. @ivar otherKexInitPayload: the MSG_KEXINIT payload we received. Used in
  295. the key exchange
  296. @ivar sessionID: a string that is unique to this SSH session. Created as
  297. part of the key exchange, sessionID is used to generate the various
  298. encryption and authentication keys.
  299. @ivar service: an SSHService instance, or None. If it's set to an object,
  300. it's the currently running service.
  301. @ivar kexAlg: the agreed-upon key exchange algorithm.
  302. @ivar keyAlg: the agreed-upon public key type for the key exchange.
  303. @ivar currentEncryptions: an SSHCiphers instance. It represents the
  304. current encryption and authentication options for the transport.
  305. @ivar nextEncryptions: an SSHCiphers instance. Held here until the
  306. MSG_NEWKEYS messages are exchanged, when nextEncryptions is
  307. transitioned to currentEncryptions.
  308. @ivar first: the first bytes of the next packet. In order to avoid
  309. decrypting data twice, the first bytes are decrypted and stored until
  310. the whole packet is available.
  311. @ivar _keyExchangeState: The current protocol state with respect to key
  312. exchange. This is either C{_KEY_EXCHANGE_NONE} if no key exchange is
  313. in progress (and returns to this value after any key exchange
  314. completqes), C{_KEY_EXCHANGE_REQUESTED} if this side of the connection
  315. initiated a key exchange, and C{_KEY_EXCHANGE_PROGRESSING} if the other
  316. side of the connection initiated a key exchange. C{_KEY_EXCHANGE_NONE}
  317. is the initial value (however SSH connections begin with key exchange,
  318. so it will quickly change to another state).
  319. @ivar _blockedByKeyExchange: Whenever C{_keyExchangeState} is not
  320. C{_KEY_EXCHANGE_NONE}, this is a C{list} of pending messages which were
  321. passed to L{sendPacket} but could not be sent because it is not legal
  322. to send them while a key exchange is in progress. When the key
  323. exchange completes, another attempt is made to send these messages.
  324. """
  325. protocolVersion = b'2.0'
  326. version = b'Twisted_' + twisted_version.encode('ascii')
  327. comment = b''
  328. ourVersionString = (b'SSH-' + protocolVersion + b'-' + version + b' '
  329. + comment).strip()
  330. # L{None} is supported as cipher and hmac. For security they are disabled
  331. # by default. To enable them, subclass this class and add it, or do:
  332. # SSHTransportBase.supportedCiphers.append('none')
  333. # List ordered by preference.
  334. supportedCiphers = _getSupportedCiphers()
  335. supportedMACs = [
  336. b'hmac-sha2-512',
  337. b'hmac-sha2-384',
  338. b'hmac-sha2-256',
  339. b'hmac-sha1',
  340. b'hmac-md5',
  341. # `none`,
  342. ]
  343. supportedKeyExchanges = _kex.getSupportedKeyExchanges()
  344. supportedPublicKeys = []
  345. # Add the supported EC keys, and change the name from ecdh* to ecdsa*
  346. for eckey in supportedKeyExchanges:
  347. if eckey.find(b'ecdh') != -1:
  348. supportedPublicKeys += [eckey.replace(b'ecdh', b'ecdsa')]
  349. supportedPublicKeys += [b'ssh-rsa', b'ssh-dss']
  350. supportedCompressions = [b'none', b'zlib']
  351. supportedLanguages = ()
  352. supportedVersions = (b'1.99', b'2.0')
  353. isClient = False
  354. gotVersion = False
  355. buf = b''
  356. outgoingPacketSequence = 0
  357. incomingPacketSequence = 0
  358. outgoingCompression = None
  359. incomingCompression = None
  360. sessionID = None
  361. service = None
  362. # There is no key exchange activity in progress.
  363. _KEY_EXCHANGE_NONE = '_KEY_EXCHANGE_NONE'
  364. # Key exchange is in progress and we started it.
  365. _KEY_EXCHANGE_REQUESTED = '_KEY_EXCHANGE_REQUESTED'
  366. # Key exchange is in progress and both sides have sent KEXINIT messages.
  367. _KEY_EXCHANGE_PROGRESSING = '_KEY_EXCHANGE_PROGRESSING'
  368. # There is a fourth conceptual state not represented here: KEXINIT received
  369. # but not sent. Since we always send a KEXINIT as soon as we get it, we
  370. # can't ever be in that state.
  371. # The current key exchange state.
  372. _keyExchangeState = _KEY_EXCHANGE_NONE
  373. _blockedByKeyExchange = None
  374. def connectionLost(self, reason):
  375. """
  376. When the underlying connection is closed, stop the running service (if
  377. any), and log out the avatar (if any).
  378. @type reason: L{twisted.python.failure.Failure}
  379. @param reason: The cause of the connection being closed.
  380. """
  381. if self.service:
  382. self.service.serviceStopped()
  383. if hasattr(self, 'avatar'):
  384. self.logoutFunction()
  385. log.msg('connection lost')
  386. def connectionMade(self):
  387. """
  388. Called when the connection is made to the other side. We sent our
  389. version and the MSG_KEXINIT packet.
  390. """
  391. self.transport.write(self.ourVersionString + b'\r\n')
  392. self.currentEncryptions = SSHCiphers(b'none', b'none', b'none',
  393. b'none')
  394. self.currentEncryptions.setKeys(b'', b'', b'', b'', b'', b'')
  395. self.sendKexInit()
  396. def sendKexInit(self):
  397. """
  398. Send a I{KEXINIT} message to initiate key exchange or to respond to a
  399. key exchange initiated by the peer.
  400. @raise RuntimeError: If a key exchange has already been started and it
  401. is not appropriate to send a I{KEXINIT} message at this time.
  402. @return: L{None}
  403. """
  404. if self._keyExchangeState != self._KEY_EXCHANGE_NONE:
  405. raise RuntimeError(
  406. "Cannot send KEXINIT while key exchange state is %r" % (
  407. self._keyExchangeState,))
  408. self.ourKexInitPayload = b''.join([
  409. chr(MSG_KEXINIT),
  410. randbytes.secureRandom(16),
  411. NS(b','.join(self.supportedKeyExchanges)),
  412. NS(b','.join(self.supportedPublicKeys)),
  413. NS(b','.join(self.supportedCiphers)),
  414. NS(b','.join(self.supportedCiphers)),
  415. NS(b','.join(self.supportedMACs)),
  416. NS(b','.join(self.supportedMACs)),
  417. NS(b','.join(self.supportedCompressions)),
  418. NS(b','.join(self.supportedCompressions)),
  419. NS(b','.join(self.supportedLanguages)),
  420. NS(b','.join(self.supportedLanguages)),
  421. b'\000\000\000\000\000'])
  422. self.sendPacket(MSG_KEXINIT, self.ourKexInitPayload[1:])
  423. self._keyExchangeState = self._KEY_EXCHANGE_REQUESTED
  424. self._blockedByKeyExchange = []
  425. def _allowedKeyExchangeMessageType(self, messageType):
  426. """
  427. Determine if the given message type may be sent while key exchange is
  428. in progress.
  429. @param messageType: The type of message
  430. @type messageType: L{int}
  431. @return: C{True} if the given type of message may be sent while key
  432. exchange is in progress, C{False} if it may not.
  433. @rtype: L{bool}
  434. @see: U{http://tools.ietf.org/html/rfc4253#section-7.1}
  435. """
  436. # Written somewhat peculularly to reflect the way the specification
  437. # defines the allowed message types.
  438. if 1 <= messageType <= 19:
  439. return messageType not in (MSG_SERVICE_REQUEST, MSG_SERVICE_ACCEPT)
  440. if 20 <= messageType <= 29:
  441. return messageType not in (MSG_KEXINIT,)
  442. return 30 <= messageType <= 49
  443. def sendPacket(self, messageType, payload):
  444. """
  445. Sends a packet. If it's been set up, compress the data, encrypt it,
  446. and authenticate it before sending. If key exchange is in progress and
  447. the message is not part of key exchange, queue it to be sent later.
  448. @param messageType: The type of the packet; generally one of the
  449. MSG_* values.
  450. @type messageType: L{int}
  451. @param payload: The payload for the message.
  452. @type payload: L{str}
  453. """
  454. if self._keyExchangeState != self._KEY_EXCHANGE_NONE:
  455. if not self._allowedKeyExchangeMessageType(messageType):
  456. self._blockedByKeyExchange.append((messageType, payload))
  457. return
  458. payload = chr(messageType) + payload
  459. if self.outgoingCompression:
  460. payload = (self.outgoingCompression.compress(payload)
  461. + self.outgoingCompression.flush(2))
  462. bs = self.currentEncryptions.encBlockSize
  463. # 4 for the packet length and 1 for the padding length
  464. totalSize = 5 + len(payload)
  465. lenPad = bs - (totalSize % bs)
  466. if lenPad < 4:
  467. lenPad = lenPad + bs
  468. packet = (struct.pack('!LB',
  469. totalSize + lenPad - 4, lenPad) +
  470. payload + randbytes.secureRandom(lenPad))
  471. encPacket = (
  472. self.currentEncryptions.encrypt(packet) +
  473. self.currentEncryptions.makeMAC(
  474. self.outgoingPacketSequence, packet))
  475. self.transport.write(encPacket)
  476. self.outgoingPacketSequence += 1
  477. def getPacket(self):
  478. """
  479. Try to return a decrypted, authenticated, and decompressed packet
  480. out of the buffer. If there is not enough data, return None.
  481. @rtype: L{str} or L{None}
  482. @return: The decoded packet, if any.
  483. """
  484. bs = self.currentEncryptions.decBlockSize
  485. ms = self.currentEncryptions.verifyDigestSize
  486. if len(self.buf) < bs:
  487. # Not enough data for a block
  488. return
  489. if not hasattr(self, 'first'):
  490. first = self.currentEncryptions.decrypt(self.buf[:bs])
  491. else:
  492. first = self.first
  493. del self.first
  494. packetLen, paddingLen = struct.unpack('!LB', first[:5])
  495. if packetLen > 1048576: # 1024 ** 2
  496. self.sendDisconnect(
  497. DISCONNECT_PROTOCOL_ERROR,
  498. networkString('bad packet length {}'.format(packetLen)))
  499. return
  500. if len(self.buf) < packetLen + 4 + ms:
  501. # Not enough data for a packet
  502. self.first = first
  503. return
  504. if (packetLen + 4) % bs != 0:
  505. self.sendDisconnect(
  506. DISCONNECT_PROTOCOL_ERROR,
  507. networkString(
  508. 'bad packet mod (%i%%%i == %i)' % (
  509. packetLen + 4, bs, (packetLen + 4) % bs)))
  510. return
  511. encData, self.buf = self.buf[:4 + packetLen], self.buf[4 + packetLen:]
  512. packet = first + self.currentEncryptions.decrypt(encData[bs:])
  513. if len(packet) != 4 + packetLen:
  514. self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
  515. b'bad decryption')
  516. return
  517. if ms:
  518. macData, self.buf = self.buf[:ms], self.buf[ms:]
  519. if not self.currentEncryptions.verify(self.incomingPacketSequence,
  520. packet, macData):
  521. self.sendDisconnect(DISCONNECT_MAC_ERROR, b'bad MAC')
  522. return
  523. payload = packet[5:-paddingLen]
  524. if self.incomingCompression:
  525. try:
  526. payload = self.incomingCompression.decompress(payload)
  527. except:
  528. # Tolerate any errors in decompression
  529. log.err()
  530. self.sendDisconnect(DISCONNECT_COMPRESSION_ERROR,
  531. b'compression error')
  532. return
  533. self.incomingPacketSequence += 1
  534. return payload
  535. def _unsupportedVersionReceived(self, remoteVersion):
  536. """
  537. Called when an unsupported version of the ssh protocol is received from
  538. the remote endpoint.
  539. @param remoteVersion: remote ssh protocol version which is unsupported
  540. by us.
  541. @type remoteVersion: L{str}
  542. """
  543. self.sendDisconnect(DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED,
  544. b'bad version ' + remoteVersion)
  545. def dataReceived(self, data):
  546. """
  547. First, check for the version string (SSH-2.0-*). After that has been
  548. received, this method adds data to the buffer, and pulls out any
  549. packets.
  550. @type data: L{bytes}
  551. @param data: The data that was received.
  552. """
  553. self.buf = self.buf + data
  554. if not self.gotVersion:
  555. if self.buf.find(b'\n', self.buf.find(b'SSH-')) == -1:
  556. return
  557. # RFC 4253 section 4.2 ask for strict `\r\n` line ending.
  558. # Here we are a bit more relaxed and accept implementations ending
  559. # only in '\n'.
  560. # https://tools.ietf.org/html/rfc4253#section-4.2
  561. lines = self.buf.split(b'\n')
  562. for p in lines:
  563. if p.startswith(b'SSH-'):
  564. self.gotVersion = True
  565. # Since the line was split on '\n' and most of the time
  566. # it uses '\r\n' we may get an extra '\r'.
  567. self.otherVersionString = p.rstrip(b'\r')
  568. remoteVersion = p.split(b'-')[1]
  569. if remoteVersion not in self.supportedVersions:
  570. self._unsupportedVersionReceived(remoteVersion)
  571. return
  572. i = lines.index(p)
  573. self.buf = b'\n'.join(lines[i + 1:])
  574. packet = self.getPacket()
  575. while packet:
  576. messageNum = ord(packet[0:1])
  577. self.dispatchMessage(messageNum, packet[1:])
  578. packet = self.getPacket()
  579. def dispatchMessage(self, messageNum, payload):
  580. """
  581. Send a received message to the appropriate method.
  582. @type messageNum: L{int}
  583. @param messageNum: The message number.
  584. @type payload: L{bytes}
  585. @param payload: The message payload.
  586. """
  587. if messageNum < 50 and messageNum in messages:
  588. messageType = messages[messageNum][4:]
  589. f = getattr(self, 'ssh_%s' % (messageType,), None)
  590. if f is not None:
  591. f(payload)
  592. else:
  593. log.msg("couldn't handle %s" % messageType)
  594. log.msg(repr(payload))
  595. self.sendUnimplemented()
  596. elif self.service:
  597. log.callWithLogger(self.service, self.service.packetReceived,
  598. messageNum, payload)
  599. else:
  600. log.msg("couldn't handle %s" % messageNum)
  601. log.msg(repr(payload))
  602. self.sendUnimplemented()
  603. def getPeer(self):
  604. """
  605. Returns an L{SSHTransportAddress} corresponding to the other (peer)
  606. side of this transport.
  607. @return: L{SSHTransportAddress} for the peer
  608. @rtype: L{SSHTransportAddress}
  609. @since: 12.1
  610. """
  611. return address.SSHTransportAddress(self.transport.getPeer())
  612. def getHost(self):
  613. """
  614. Returns an L{SSHTransportAddress} corresponding to the this side of
  615. transport.
  616. @return: L{SSHTransportAddress} for the peer
  617. @rtype: L{SSHTransportAddress}
  618. @since: 12.1
  619. """
  620. return address.SSHTransportAddress(self.transport.getHost())
  621. @property
  622. def kexAlg(self):
  623. """
  624. The key exchange algorithm name agreed between client and server.
  625. """
  626. return self._kexAlg
  627. @kexAlg.setter
  628. def kexAlg(self, value):
  629. """
  630. Set the key exchange algorithm name.
  631. """
  632. self._kexAlg = value
  633. # Client-initiated rekeying looks like this:
  634. #
  635. # C> MSG_KEXINIT
  636. # S> MSG_KEXINIT
  637. # C> MSG_KEX_DH_GEX_REQUEST or MSG_KEXDH_INIT
  638. # S> MSG_KEX_DH_GEX_GROUP or MSG_KEXDH_REPLY
  639. # C> MSG_KEX_DH_GEX_INIT or --
  640. # S> MSG_KEX_DH_GEX_REPLY or --
  641. # C> MSG_NEWKEYS
  642. # S> MSG_NEWKEYS
  643. #
  644. # Server-initiated rekeying is the same, only the first two messages are
  645. # switched.
  646. def ssh_KEXINIT(self, packet):
  647. """
  648. Called when we receive a MSG_KEXINIT message. Payload::
  649. bytes[16] cookie
  650. string keyExchangeAlgorithms
  651. string keyAlgorithms
  652. string incomingEncryptions
  653. string outgoingEncryptions
  654. string incomingAuthentications
  655. string outgoingAuthentications
  656. string incomingCompressions
  657. string outgoingCompressions
  658. string incomingLanguages
  659. string outgoingLanguages
  660. bool firstPacketFollows
  661. unit32 0 (reserved)
  662. Starts setting up the key exchange, keys, encryptions, and
  663. authentications. Extended by ssh_KEXINIT in SSHServerTransport and
  664. SSHClientTransport.
  665. @type packet: L{bytes}
  666. @param packet: The message data.
  667. @return: A L{tuple} of negotiated key exchange algorithms, key
  668. algorithms, and unhandled data, or L{None} if something went wrong.
  669. """
  670. self.otherKexInitPayload = chr(MSG_KEXINIT) + packet
  671. # This is useless to us:
  672. # cookie = packet[: 16]
  673. k = getNS(packet[16:], 10)
  674. strings, rest = k[:-1], k[-1]
  675. (kexAlgs, keyAlgs, encCS, encSC, macCS, macSC, compCS, compSC, langCS,
  676. langSC) = [s.split(b',') for s in strings]
  677. # These are the server directions
  678. outs = [encSC, macSC, compSC]
  679. ins = [encCS, macSC, compCS]
  680. if self.isClient:
  681. outs, ins = ins, outs # Switch directions
  682. server = (self.supportedKeyExchanges, self.supportedPublicKeys,
  683. self.supportedCiphers, self.supportedCiphers,
  684. self.supportedMACs, self.supportedMACs,
  685. self.supportedCompressions, self.supportedCompressions)
  686. client = (kexAlgs, keyAlgs, outs[0], ins[0], outs[1], ins[1],
  687. outs[2], ins[2])
  688. if self.isClient:
  689. server, client = client, server
  690. self.kexAlg = ffs(client[0], server[0])
  691. self.keyAlg = ffs(client[1], server[1])
  692. self.nextEncryptions = SSHCiphers(
  693. ffs(client[2], server[2]),
  694. ffs(client[3], server[3]),
  695. ffs(client[4], server[4]),
  696. ffs(client[5], server[5]))
  697. self.outgoingCompressionType = ffs(client[6], server[6])
  698. self.incomingCompressionType = ffs(client[7], server[7])
  699. if None in (self.kexAlg, self.keyAlg, self.outgoingCompressionType,
  700. self.incomingCompressionType):
  701. self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
  702. b"couldn't match all kex parts")
  703. return
  704. if None in self.nextEncryptions.__dict__.values():
  705. self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
  706. b"couldn't match all kex parts")
  707. return
  708. log.msg('kex alg, key alg: %r %r' % (self.kexAlg, self.keyAlg))
  709. log.msg('outgoing: %r %r %r' % (self.nextEncryptions.outCipType,
  710. self.nextEncryptions.outMACType,
  711. self.outgoingCompressionType))
  712. log.msg('incoming: %r %r %r' % (self.nextEncryptions.inCipType,
  713. self.nextEncryptions.inMACType,
  714. self.incomingCompressionType))
  715. if self._keyExchangeState == self._KEY_EXCHANGE_REQUESTED:
  716. self._keyExchangeState = self._KEY_EXCHANGE_PROGRESSING
  717. else:
  718. self.sendKexInit()
  719. return kexAlgs, keyAlgs, rest # For SSHServerTransport to use
  720. def ssh_DISCONNECT(self, packet):
  721. """
  722. Called when we receive a MSG_DISCONNECT message. Payload::
  723. long code
  724. string description
  725. This means that the other side has disconnected. Pass the message up
  726. and disconnect ourselves.
  727. @type packet: L{bytes}
  728. @param packet: The message data.
  729. """
  730. reasonCode = struct.unpack('>L', packet[: 4])[0]
  731. description, foo = getNS(packet[4:])
  732. self.receiveError(reasonCode, description)
  733. self.transport.loseConnection()
  734. def ssh_IGNORE(self, packet):
  735. """
  736. Called when we receive a MSG_IGNORE message. No payload.
  737. This means nothing; we simply return.
  738. @type packet: L{bytes}
  739. @param packet: The message data.
  740. """
  741. def ssh_UNIMPLEMENTED(self, packet):
  742. """
  743. Called when we receive a MSG_UNIMPLEMENTED message. Payload::
  744. long packet
  745. This means that the other side did not implement one of our packets.
  746. @type packet: L{bytes}
  747. @param packet: The message data.
  748. """
  749. seqnum, = struct.unpack('>L', packet)
  750. self.receiveUnimplemented(seqnum)
  751. def ssh_DEBUG(self, packet):
  752. """
  753. Called when we receive a MSG_DEBUG message. Payload::
  754. bool alwaysDisplay
  755. string message
  756. string language
  757. This means the other side has passed along some debugging info.
  758. @type packet: L{bytes}
  759. @param packet: The message data.
  760. """
  761. alwaysDisplay = bool(ord(packet[0:1]))
  762. message, lang, foo = getNS(packet[1:], 2)
  763. self.receiveDebug(alwaysDisplay, message, lang)
  764. def setService(self, service):
  765. """
  766. Set our service to service and start it running. If we were
  767. running a service previously, stop it first.
  768. @type service: C{SSHService}
  769. @param service: The service to attach.
  770. """
  771. log.msg('starting service %r' % (service.name,))
  772. if self.service:
  773. self.service.serviceStopped()
  774. self.service = service
  775. service.transport = self
  776. self.service.serviceStarted()
  777. def sendDebug(self, message, alwaysDisplay=False, language=b''):
  778. """
  779. Send a debug message to the other side.
  780. @param message: the message to send.
  781. @type message: L{str}
  782. @param alwaysDisplay: if True, tell the other side to always
  783. display this message.
  784. @type alwaysDisplay: L{bool}
  785. @param language: optionally, the language the message is in.
  786. @type language: L{str}
  787. """
  788. self.sendPacket(MSG_DEBUG, chr(alwaysDisplay) + NS(message) +
  789. NS(language))
  790. def sendIgnore(self, message):
  791. """
  792. Send a message that will be ignored by the other side. This is
  793. useful to fool attacks based on guessing packet sizes in the
  794. encrypted stream.
  795. @param message: data to send with the message
  796. @type message: L{str}
  797. """
  798. self.sendPacket(MSG_IGNORE, NS(message))
  799. def sendUnimplemented(self):
  800. """
  801. Send a message to the other side that the last packet was not
  802. understood.
  803. """
  804. seqnum = self.incomingPacketSequence
  805. self.sendPacket(MSG_UNIMPLEMENTED, struct.pack('!L', seqnum))
  806. def sendDisconnect(self, reason, desc):
  807. """
  808. Send a disconnect message to the other side and then disconnect.
  809. @param reason: the reason for the disconnect. Should be one of the
  810. DISCONNECT_* values.
  811. @type reason: L{int}
  812. @param desc: a descrption of the reason for the disconnection.
  813. @type desc: L{str}
  814. """
  815. self.sendPacket(
  816. MSG_DISCONNECT, struct.pack('>L', reason) + NS(desc) + NS(b''))
  817. log.msg('Disconnecting with error, code %s\nreason: %s' % (reason,
  818. desc))
  819. self.transport.loseConnection()
  820. def _startEphemeralDH(self):
  821. """
  822. Prepares for a Diffie-Hellman key agreement exchange.
  823. Creates an ephemeral keypair in the group defined by (self.g,
  824. self.p) and stores it.
  825. """
  826. numbers = dh.DHParameterNumbers(self.p, self.g)
  827. parameters = numbers.parameters(default_backend())
  828. self.dhSecretKey = parameters.generate_private_key()
  829. y = self.dhSecretKey.public_key().public_numbers().y
  830. self.dhSecretKeyPublicMP = MP(y)
  831. def _finishEphemeralDH(self, remoteDHpublicKey):
  832. """
  833. Completes the Diffie-Hellman key agreement started by
  834. _startEphemeralDH, and forgets the ephemeral secret key.
  835. @type remoteDHpublicKey: L{int}
  836. @rtype: L{bytes}
  837. @return: The new shared secret, in SSH C{mpint} format.
  838. """
  839. remoteKey = dh.DHPublicNumbers(
  840. remoteDHpublicKey,
  841. dh.DHParameterNumbers(self.p, self.g)
  842. ).public_key(default_backend())
  843. secret = self.dhSecretKey.exchange(remoteKey)
  844. del self.dhSecretKey
  845. # The result of a Diffie-Hellman exchange is an integer, but
  846. # the Cryptography module returns it as bytes in a form that
  847. # is only vaguely documented. We fix it up to match the SSH
  848. # MP-integer format as described in RFC4251.
  849. secret = secret.lstrip(b'\x00')
  850. ch = ord(secret[0:1])
  851. if ch & 0x80: # High bit set?
  852. # Make room for the sign bit
  853. prefix = struct.pack('>L', len(secret) + 1) + b'\x00'
  854. else:
  855. prefix = struct.pack('>L', len(secret))
  856. return prefix + secret
  857. def _getKey(self, c, sharedSecret, exchangeHash):
  858. """
  859. Get one of the keys for authentication/encryption.
  860. @type c: L{bytes}
  861. @param c: The letter identifying which key this is.
  862. @type sharedSecret: L{bytes}
  863. @param sharedSecret: The shared secret K.
  864. @type exchangeHash: L{bytes}
  865. @param exchangeHash: The hash H from key exchange.
  866. @rtype: L{bytes}
  867. @return: The derived key.
  868. """
  869. hashProcessor = _kex.getHashProcessor(self.kexAlg)
  870. k1 = hashProcessor(sharedSecret + exchangeHash + c + self.sessionID)
  871. k1 = k1.digest()
  872. k2 = hashProcessor(sharedSecret + exchangeHash + k1).digest()
  873. k3 = hashProcessor(sharedSecret + exchangeHash + k1 + k2).digest()
  874. k4 = hashProcessor(sharedSecret + exchangeHash + k1 + k2 + k3).digest()
  875. return k1 + k2 + k3 + k4
  876. def _keySetup(self, sharedSecret, exchangeHash):
  877. """
  878. Set up the keys for the connection and sends MSG_NEWKEYS when
  879. finished,
  880. @param sharedSecret: a secret string agreed upon using a Diffie-
  881. Hellman exchange, so it is only shared between
  882. the server and the client.
  883. @type sharedSecret: L{str}
  884. @param exchangeHash: A hash of various data known by both sides.
  885. @type exchangeHash: L{str}
  886. """
  887. if not self.sessionID:
  888. self.sessionID = exchangeHash
  889. initIVCS = self._getKey(b'A', sharedSecret, exchangeHash)
  890. initIVSC = self._getKey(b'B', sharedSecret, exchangeHash)
  891. encKeyCS = self._getKey(b'C', sharedSecret, exchangeHash)
  892. encKeySC = self._getKey(b'D', sharedSecret, exchangeHash)
  893. integKeyCS = self._getKey(b'E', sharedSecret, exchangeHash)
  894. integKeySC = self._getKey(b'F', sharedSecret, exchangeHash)
  895. outs = [initIVSC, encKeySC, integKeySC]
  896. ins = [initIVCS, encKeyCS, integKeyCS]
  897. if self.isClient: # Reverse for the client
  898. log.msg('REVERSE')
  899. outs, ins = ins, outs
  900. self.nextEncryptions.setKeys(outs[0], outs[1], ins[0], ins[1],
  901. outs[2], ins[2])
  902. self.sendPacket(MSG_NEWKEYS, b'')
  903. def _newKeys(self):
  904. """
  905. Called back by a subclass once a I{MSG_NEWKEYS} message has been
  906. received. This indicates key exchange has completed and new encryption
  907. and compression parameters should be adopted. Any messages which were
  908. queued during key exchange will also be flushed.
  909. """
  910. log.msg('NEW KEYS')
  911. self.currentEncryptions = self.nextEncryptions
  912. if self.outgoingCompressionType == b'zlib':
  913. self.outgoingCompression = zlib.compressobj(6)
  914. if self.incomingCompressionType == b'zlib':
  915. self.incomingCompression = zlib.decompressobj()
  916. self._keyExchangeState = self._KEY_EXCHANGE_NONE
  917. messages = self._blockedByKeyExchange
  918. self._blockedByKeyExchange = None
  919. for (messageType, payload) in messages:
  920. self.sendPacket(messageType, payload)
  921. def isEncrypted(self, direction="out"):
  922. """
  923. Check if the connection is encrypted in the given direction.
  924. @type direction: L{str}
  925. @param direction: The direction: one of 'out', 'in', or 'both'.
  926. @rtype: L{bool}
  927. @return: C{True} if it is encrypted.
  928. """
  929. if direction == "out":
  930. return self.currentEncryptions.outCipType != b'none'
  931. elif direction == "in":
  932. return self.currentEncryptions.inCipType != b'none'
  933. elif direction == "both":
  934. return self.isEncrypted("in") and self.isEncrypted("out")
  935. else:
  936. raise TypeError('direction must be "out", "in", or "both"')
  937. def isVerified(self, direction="out"):
  938. """
  939. Check if the connection is verified/authentication in the given direction.
  940. @type direction: L{str}
  941. @param direction: The direction: one of 'out', 'in', or 'both'.
  942. @rtype: L{bool}
  943. @return: C{True} if it is verified.
  944. """
  945. if direction == "out":
  946. return self.currentEncryptions.outMACType != b'none'
  947. elif direction == "in":
  948. return self.currentEncryptions.inMACType != b'none'
  949. elif direction == "both":
  950. return self.isVerified("in") and self.isVerified("out")
  951. else:
  952. raise TypeError('direction must be "out", "in", or "both"')
  953. def loseConnection(self):
  954. """
  955. Lose the connection to the other side, sending a
  956. DISCONNECT_CONNECTION_LOST message.
  957. """
  958. self.sendDisconnect(DISCONNECT_CONNECTION_LOST,
  959. b"user closed connection")
  960. # Client methods
  961. def receiveError(self, reasonCode, description):
  962. """
  963. Called when we receive a disconnect error message from the other
  964. side.
  965. @param reasonCode: the reason for the disconnect, one of the
  966. DISCONNECT_ values.
  967. @type reasonCode: L{int}
  968. @param description: a human-readable description of the
  969. disconnection.
  970. @type description: L{str}
  971. """
  972. log.msg('Got remote error, code %s\nreason: %s' % (reasonCode,
  973. description))
  974. def receiveUnimplemented(self, seqnum):
  975. """
  976. Called when we receive an unimplemented packet message from the other
  977. side.
  978. @param seqnum: the sequence number that was not understood.
  979. @type seqnum: L{int}
  980. """
  981. log.msg('other side unimplemented packet #%s' % (seqnum,))
  982. def receiveDebug(self, alwaysDisplay, message, lang):
  983. """
  984. Called when we receive a debug message from the other side.
  985. @param alwaysDisplay: if True, this message should always be
  986. displayed.
  987. @type alwaysDisplay: L{bool}
  988. @param message: the debug message
  989. @type message: L{str}
  990. @param lang: optionally the language the message is in.
  991. @type lang: L{str}
  992. """
  993. if alwaysDisplay:
  994. log.msg('Remote Debug Message: %s' % (message,))
  995. def _generateECPrivateKey(self):
  996. """
  997. Generate an private key for ECDH key exchange.
  998. @rtype: The appropriate private key type matching C{self.kexAlg}:
  999. L{EllipticCurvePrivateKey} for C{ecdh-sha2-nistp*}, or
  1000. L{X25519PrivateKey} for C{curve25519-sha256}.
  1001. @return: The generated private key.
  1002. """
  1003. if self.kexAlg.startswith(b'ecdh-sha2-nistp'):
  1004. try:
  1005. curve = keys._curveTable[b'ecdsa' + self.kexAlg[4:]]
  1006. except KeyError:
  1007. raise UnsupportedAlgorithm('unused-key')
  1008. return ec.generate_private_key(curve, default_backend())
  1009. elif self.kexAlg in (
  1010. b'curve25519-sha256', b'curve25519-sha256@libssh.org'):
  1011. return x25519.X25519PrivateKey.generate()
  1012. else:
  1013. raise UnsupportedAlgorithm(
  1014. 'Cannot generate elliptic curve private key for %r' %
  1015. (self.kexAlg,))
  1016. def _encodeECPublicKey(self, ecPub):
  1017. """
  1018. Encode an elliptic curve public key to bytes.
  1019. @type ecPub: The appropriate public key type matching
  1020. C{self.kexAlg}: L{EllipticCurvePublicKey} for
  1021. C{ecdh-sha2-nistp*}, or L{X25519PublicKey} for
  1022. C{curve25519-sha256}.
  1023. @param ecPub: The public key to encode.
  1024. @rtype: L{bytes}
  1025. @return: The encoded public key.
  1026. """
  1027. if self.kexAlg.startswith(b'ecdh-sha2-nistp'):
  1028. return ecPub.public_bytes(
  1029. serialization.Encoding.X962,
  1030. serialization.PublicFormat.UncompressedPoint
  1031. )
  1032. elif self.kexAlg in (
  1033. b'curve25519-sha256', b'curve25519-sha256@libssh.org'):
  1034. return ecPub.public_bytes(
  1035. serialization.Encoding.Raw,
  1036. serialization.PublicFormat.Raw
  1037. )
  1038. else:
  1039. raise UnsupportedAlgorithm(
  1040. 'Cannot encode elliptic curve public key for %r' %
  1041. (self.kexAlg,))
  1042. def _generateECSharedSecret(self, ecPriv, theirECPubBytes):
  1043. """
  1044. Generate a shared secret for ECDH key exchange.
  1045. @type ecPriv: The appropriate private key type matching
  1046. C{self.kexAlg}: L{EllipticCurvePrivateKey} for
  1047. C{ecdh-sha2-nistp*}, or L{X25519PrivateKey} for
  1048. C{curve25519-sha256}.
  1049. @param ecPriv: Our private key.
  1050. @rtype: L{bytes}
  1051. @return: The generated shared secret, as an SSH multiple-precision
  1052. integer.
  1053. """
  1054. if self.kexAlg.startswith(b'ecdh-sha2-nistp'):
  1055. try:
  1056. curve = keys._curveTable[b'ecdsa' + self.kexAlg[4:]]
  1057. except KeyError:
  1058. raise UnsupportedAlgorithm('unused-key')
  1059. theirECPub = ec.EllipticCurvePublicKey.from_encoded_point(
  1060. curve, theirECPubBytes)
  1061. sharedSecret = ecPriv.exchange(ec.ECDH(), theirECPub)
  1062. elif self.kexAlg in (
  1063. b'curve25519-sha256', b'curve25519-sha256@libssh.org'):
  1064. theirECPub = x25519.X25519PublicKey.from_public_bytes(
  1065. theirECPubBytes)
  1066. sharedSecret = ecPriv.exchange(theirECPub)
  1067. else:
  1068. raise UnsupportedAlgorithm(
  1069. 'Cannot generate elliptic curve shared secret for %r' %
  1070. (self.kexAlg,))
  1071. return _mpFromBytes(sharedSecret)
  1072. class SSHServerTransport(SSHTransportBase):
  1073. """
  1074. SSHServerTransport implements the server side of the SSH protocol.
  1075. @ivar isClient: since we are never the client, this is always False.
  1076. @ivar ignoreNextPacket: if True, ignore the next key exchange packet. This
  1077. is set when the client sends a guessed key exchange packet but with
  1078. an incorrect guess.
  1079. @ivar dhGexRequest: the KEX_DH_GEX_REQUEST(_OLD) that the client sent.
  1080. The key generation needs this to be stored.
  1081. @ivar g: the Diffie-Hellman group generator.
  1082. @ivar p: the Diffie-Hellman group prime.
  1083. """
  1084. isClient = False
  1085. ignoreNextPacket = 0
  1086. def ssh_KEXINIT(self, packet):
  1087. """
  1088. Called when we receive a MSG_KEXINIT message. For a description
  1089. of the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally,
  1090. this method checks if a guessed key exchange packet was sent. If
  1091. it was sent, and it guessed incorrectly, the next key exchange
  1092. packet MUST be ignored.
  1093. """
  1094. retval = SSHTransportBase.ssh_KEXINIT(self, packet)
  1095. if not retval: # Disconnected
  1096. return
  1097. else:
  1098. kexAlgs, keyAlgs, rest = retval
  1099. if ord(rest[0:1]): # Flag first_kex_packet_follows?
  1100. if (kexAlgs[0] != self.supportedKeyExchanges[0] or
  1101. keyAlgs[0] != self.supportedPublicKeys[0]):
  1102. self.ignoreNextPacket = True # Guess was wrong
  1103. def _ssh_KEX_ECDH_INIT(self, packet):
  1104. """
  1105. Called from L{ssh_KEX_DH_GEX_REQUEST_OLD} to handle
  1106. elliptic curve key exchanges.
  1107. Payload::
  1108. string client Elliptic Curve Diffie-Hellman public key
  1109. Just like L{_ssh_KEXDH_INIT} this message type is also not dispatched
  1110. directly. Extra check to determine if this is really KEX_ECDH_INIT
  1111. is required.
  1112. First we load the host's public/private keys.
  1113. Then we generate the ECDH public/private keypair for the given curve.
  1114. With that we generate the shared secret key.
  1115. Then we compute the hash to sign and send back to the client
  1116. Along with the server's public key and the ECDH public key.
  1117. @type packet: L{bytes}
  1118. @param packet: The message data.
  1119. @return: None.
  1120. """
  1121. # Get the raw client public key.
  1122. pktPub, packet = getNS(packet)
  1123. # Get the host's public and private keys
  1124. pubHostKey = self.factory.publicKeys[self.keyAlg]
  1125. privHostKey = self.factory.privateKeys[self.keyAlg]
  1126. # Generate the private key
  1127. ecPriv = self._generateECPrivateKey()
  1128. # Get the public key
  1129. self.ecPub = ecPriv.public_key()
  1130. encPub = self._encodeECPublicKey(self.ecPub)
  1131. # Generate the shared secret
  1132. sharedSecret = self._generateECSharedSecret(ecPriv, pktPub)
  1133. # Finish update and digest
  1134. h = _kex.getHashProcessor(self.kexAlg)()
  1135. h.update(NS(self.otherVersionString))
  1136. h.update(NS(self.ourVersionString))
  1137. h.update(NS(self.otherKexInitPayload))
  1138. h.update(NS(self.ourKexInitPayload))
  1139. h.update(NS(pubHostKey.blob()))
  1140. h.update(NS(pktPub))
  1141. h.update(NS(encPub))
  1142. h.update(sharedSecret)
  1143. exchangeHash = h.digest()
  1144. self.sendPacket(
  1145. MSG_KEXDH_REPLY,
  1146. NS(pubHostKey.blob()) + NS(encPub) +
  1147. NS(privHostKey.sign(exchangeHash)))
  1148. self._keySetup(sharedSecret, exchangeHash)
  1149. def _ssh_KEXDH_INIT(self, packet):
  1150. """
  1151. Called to handle the beginning of a non-group key exchange.
  1152. Unlike other message types, this is not dispatched automatically. It
  1153. is called from C{ssh_KEX_DH_GEX_REQUEST_OLD} because an extra check is
  1154. required to determine if this is really a KEXDH_INIT message or if it
  1155. is a KEX_DH_GEX_REQUEST_OLD message.
  1156. The KEXDH_INIT payload::
  1157. integer e (the client's Diffie-Hellman public key)
  1158. We send the KEXDH_REPLY with our host key and signature.
  1159. @type packet: L{bytes}
  1160. @param packet: The message data.
  1161. """
  1162. clientDHpublicKey, foo = getMP(packet)
  1163. self.g, self.p = _kex.getDHGeneratorAndPrime(self.kexAlg)
  1164. self._startEphemeralDH()
  1165. sharedSecret = self._finishEphemeralDH(clientDHpublicKey)
  1166. h = sha1()
  1167. h.update(NS(self.otherVersionString))
  1168. h.update(NS(self.ourVersionString))
  1169. h.update(NS(self.otherKexInitPayload))
  1170. h.update(NS(self.ourKexInitPayload))
  1171. h.update(NS(self.factory.publicKeys[self.keyAlg].blob()))
  1172. h.update(MP(clientDHpublicKey))
  1173. h.update(self.dhSecretKeyPublicMP)
  1174. h.update(sharedSecret)
  1175. exchangeHash = h.digest()
  1176. self.sendPacket(
  1177. MSG_KEXDH_REPLY,
  1178. NS(self.factory.publicKeys[self.keyAlg].blob()) +
  1179. self.dhSecretKeyPublicMP +
  1180. NS(self.factory.privateKeys[self.keyAlg].sign(exchangeHash)))
  1181. self._keySetup(sharedSecret, exchangeHash)
  1182. def ssh_KEX_DH_GEX_REQUEST_OLD(self, packet):
  1183. """
  1184. This represents different key exchange methods that share the same
  1185. integer value. If the message is determined to be a KEXDH_INIT,
  1186. L{_ssh_KEXDH_INIT} is called to handle it. If it is a KEX_ECDH_INIT,
  1187. L{_ssh_KEX_ECDH_INIT} is called.
  1188. Otherwise, for KEX_DH_GEX_REQUEST_OLD payload::
  1189. integer ideal (ideal size for the Diffie-Hellman prime)
  1190. We send the KEX_DH_GEX_GROUP message with the group that is
  1191. closest in size to ideal.
  1192. If we were told to ignore the next key exchange packet by ssh_KEXINIT,
  1193. drop it on the floor and return.
  1194. @type packet: L{bytes}
  1195. @param packet: The message data.
  1196. """
  1197. if self.ignoreNextPacket:
  1198. self.ignoreNextPacket = 0
  1199. return
  1200. # KEXDH_INIT, KEX_ECDH_INIT, and KEX_DH_GEX_REQUEST_OLD
  1201. # have the same value, so use another cue
  1202. # to decide what kind of message the peer sent us.
  1203. if _kex.isFixedGroup(self.kexAlg):
  1204. return self._ssh_KEXDH_INIT(packet)
  1205. elif _kex.isEllipticCurve(self.kexAlg):
  1206. return self._ssh_KEX_ECDH_INIT(packet)
  1207. else:
  1208. self.dhGexRequest = packet
  1209. ideal = struct.unpack('>L', packet)[0]
  1210. self.g, self.p = self.factory.getDHPrime(ideal)
  1211. self._startEphemeralDH()
  1212. self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p) + MP(self.g))
  1213. def ssh_KEX_DH_GEX_REQUEST(self, packet):
  1214. """
  1215. Called when we receive a MSG_KEX_DH_GEX_REQUEST message. Payload::
  1216. integer minimum
  1217. integer ideal
  1218. integer maximum
  1219. The client is asking for a Diffie-Hellman group between minimum and
  1220. maximum size, and close to ideal if possible. We reply with a
  1221. MSG_KEX_DH_GEX_GROUP message.
  1222. If we were told to ignore the next key exchange packet by ssh_KEXINIT,
  1223. drop it on the floor and return.
  1224. @type packet: L{bytes}
  1225. @param packet: The message data.
  1226. """
  1227. if self.ignoreNextPacket:
  1228. self.ignoreNextPacket = 0
  1229. return
  1230. self.dhGexRequest = packet
  1231. min, ideal, max = struct.unpack('>3L', packet)
  1232. self.g, self.p = self.factory.getDHPrime(ideal)
  1233. self._startEphemeralDH()
  1234. self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p) + MP(self.g))
  1235. def ssh_KEX_DH_GEX_INIT(self, packet):
  1236. """
  1237. Called when we get a MSG_KEX_DH_GEX_INIT message. Payload::
  1238. integer e (client DH public key)
  1239. We send the MSG_KEX_DH_GEX_REPLY message with our host key and
  1240. signature.
  1241. @type packet: L{bytes}
  1242. @param packet: The message data.
  1243. """
  1244. clientDHpublicKey, foo = getMP(packet)
  1245. # TODO: we should also look at the value they send to us and reject
  1246. # insecure values of f (if g==2 and f has a single '1' bit while the
  1247. # rest are '0's, then they must have used a small y also).
  1248. # TODO: This could be computed when self.p is set up
  1249. # or do as openssh does and scan f for a single '1' bit instead
  1250. sharedSecret = self._finishEphemeralDH(clientDHpublicKey)
  1251. h = _kex.getHashProcessor(self.kexAlg)()
  1252. h.update(NS(self.otherVersionString))
  1253. h.update(NS(self.ourVersionString))
  1254. h.update(NS(self.otherKexInitPayload))
  1255. h.update(NS(self.ourKexInitPayload))
  1256. h.update(NS(self.factory.publicKeys[self.keyAlg].blob()))
  1257. h.update(self.dhGexRequest)
  1258. h.update(MP(self.p))
  1259. h.update(MP(self.g))
  1260. h.update(MP(clientDHpublicKey))
  1261. h.update(self.dhSecretKeyPublicMP)
  1262. h.update(sharedSecret)
  1263. exchangeHash = h.digest()
  1264. self.sendPacket(
  1265. MSG_KEX_DH_GEX_REPLY,
  1266. NS(self.factory.publicKeys[self.keyAlg].blob()) +
  1267. self.dhSecretKeyPublicMP +
  1268. NS(self.factory.privateKeys[self.keyAlg].sign(exchangeHash)))
  1269. self._keySetup(sharedSecret, exchangeHash)
  1270. def ssh_NEWKEYS(self, packet):
  1271. """
  1272. Called when we get a MSG_NEWKEYS message. No payload.
  1273. When we get this, the keys have been set on both sides, and we
  1274. start using them to encrypt and authenticate the connection.
  1275. @type packet: L{bytes}
  1276. @param packet: The message data.
  1277. """
  1278. if packet != b'':
  1279. self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
  1280. b"NEWKEYS takes no data")
  1281. return
  1282. self._newKeys()
  1283. def ssh_SERVICE_REQUEST(self, packet):
  1284. """
  1285. Called when we get a MSG_SERVICE_REQUEST message. Payload::
  1286. string serviceName
  1287. The client has requested a service. If we can start the service,
  1288. start it; otherwise, disconnect with
  1289. DISCONNECT_SERVICE_NOT_AVAILABLE.
  1290. @type packet: L{bytes}
  1291. @param packet: The message data.
  1292. """
  1293. service, rest = getNS(packet)
  1294. cls = self.factory.getService(self, service)
  1295. if not cls:
  1296. self.sendDisconnect(DISCONNECT_SERVICE_NOT_AVAILABLE,
  1297. b"don't have service " + service)
  1298. return
  1299. else:
  1300. self.sendPacket(MSG_SERVICE_ACCEPT, NS(service))
  1301. self.setService(cls())
  1302. class SSHClientTransport(SSHTransportBase):
  1303. """
  1304. SSHClientTransport implements the client side of the SSH protocol.
  1305. @ivar isClient: since we are always the client, this is always True.
  1306. @ivar _gotNewKeys: if we receive a MSG_NEWKEYS message before we are
  1307. ready to transition to the new keys, this is set to True so we
  1308. can transition when the keys are ready locally.
  1309. @ivar x: our Diffie-Hellman private key.
  1310. @ivar e: our Diffie-Hellman public key.
  1311. @ivar g: the Diffie-Hellman group generator.
  1312. @ivar p: the Diffie-Hellman group prime
  1313. @ivar instance: the SSHService object we are requesting.
  1314. @ivar _dhMinimalGroupSize: Minimal acceptable group size advertised by the
  1315. client in MSG_KEX_DH_GEX_REQUEST.
  1316. @type _dhMinimalGroupSize: int
  1317. @ivar _dhMaximalGroupSize: Maximal acceptable group size advertised by the
  1318. client in MSG_KEX_DH_GEX_REQUEST.
  1319. @type _dhMaximalGroupSize: int
  1320. @ivar _dhPreferredGroupSize: Preferred group size advertised by the client
  1321. in MSG_KEX_DH_GEX_REQUEST.
  1322. @type _dhPreferredGroupSize: int
  1323. """
  1324. isClient = True
  1325. # Recommended minimal and maximal values from RFC 4419, 3.
  1326. _dhMinimalGroupSize = 1024
  1327. _dhMaximalGroupSize = 8192
  1328. # FIXME: https://twistedmatrix.com/trac/ticket/8103
  1329. # This may need to be more dynamic; compare kexgex_client in
  1330. # OpenSSH.
  1331. _dhPreferredGroupSize = 2048
  1332. def connectionMade(self):
  1333. """
  1334. Called when the connection is started with the server. Just sets
  1335. up a private instance variable.
  1336. """
  1337. SSHTransportBase.connectionMade(self)
  1338. self._gotNewKeys = 0
  1339. def ssh_KEXINIT(self, packet):
  1340. """
  1341. Called when we receive a MSG_KEXINIT message. For a description
  1342. of the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally,
  1343. this method sends the first key exchange packet.
  1344. If the agreed-upon exchange is ECDH, generate a key pair for the
  1345. corresponding curve and send the public key.
  1346. If the agreed-upon exchange has a fixed prime/generator group,
  1347. generate a public key and send it in a MSG_KEXDH_INIT message.
  1348. Otherwise, ask for a 2048 bit group with a MSG_KEX_DH_GEX_REQUEST
  1349. message.
  1350. """
  1351. if SSHTransportBase.ssh_KEXINIT(self, packet) is None:
  1352. # Connection was disconnected while doing base processing.
  1353. # Maybe no common protocols were agreed.
  1354. return
  1355. # Are we using ECDH?
  1356. if _kex.isEllipticCurve(self.kexAlg):
  1357. # Generate the keys
  1358. self.ecPriv = self._generateECPrivateKey()
  1359. self.ecPub = self.ecPriv.public_key()
  1360. # DH_GEX_REQUEST_OLD is the same number we need.
  1361. self.sendPacket(
  1362. MSG_KEX_DH_GEX_REQUEST_OLD,
  1363. NS(self._encodeECPublicKey(self.ecPub))
  1364. )
  1365. elif _kex.isFixedGroup(self.kexAlg):
  1366. # We agreed on a fixed group key exchange algorithm.
  1367. self.g, self.p = _kex.getDHGeneratorAndPrime(self.kexAlg)
  1368. self._startEphemeralDH()
  1369. self.sendPacket(MSG_KEXDH_INIT, self.dhSecretKeyPublicMP)
  1370. else:
  1371. # We agreed on a dynamic group. Tell the server what range of
  1372. # group sizes we accept, and what size we prefer; the server
  1373. # will then select a group.
  1374. self.sendPacket(
  1375. MSG_KEX_DH_GEX_REQUEST,
  1376. struct.pack(
  1377. '!LLL',
  1378. self._dhMinimalGroupSize,
  1379. self._dhPreferredGroupSize,
  1380. self._dhMaximalGroupSize,
  1381. ))
  1382. def _ssh_KEX_ECDH_REPLY(self, packet):
  1383. """
  1384. Called to handle a reply to a ECDH exchange message(KEX_ECDH_INIT).
  1385. Like the handler for I{KEXDH_INIT}, this message type has an
  1386. overlapping value. This method is called from C{ssh_KEX_DH_GEX_GROUP}
  1387. if that method detects a non-group key exchange is in progress.
  1388. Payload::
  1389. string serverHostKey
  1390. string server Elliptic Curve Diffie-Hellman public key
  1391. string signature
  1392. We verify the host key and continue if it passes verificiation.
  1393. Otherwise raise an exception and return.
  1394. @type packet: L{bytes}
  1395. @param packet: The message data.
  1396. @return: A deferred firing when key exchange is complete.
  1397. """
  1398. def _continue_KEX_ECDH_REPLY(ignored, hostKey, pubKey, signature):
  1399. # Save off the host public key.
  1400. theirECHost = hostKey
  1401. sharedSecret = self._generateECSharedSecret(self.ecPriv, pubKey)
  1402. h = _kex.getHashProcessor(self.kexAlg)()
  1403. h.update(NS(self.ourVersionString))
  1404. h.update(NS(self.otherVersionString))
  1405. h.update(NS(self.ourKexInitPayload))
  1406. h.update(NS(self.otherKexInitPayload))
  1407. h.update(NS(theirECHost))
  1408. h.update(NS(self._encodeECPublicKey(self.ecPub)))
  1409. h.update(NS(pubKey))
  1410. h.update(sharedSecret)
  1411. exchangeHash = h.digest()
  1412. if not keys.Key.fromString(theirECHost).verify(
  1413. signature, exchangeHash):
  1414. self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
  1415. b'bad signature')
  1416. else:
  1417. self._keySetup(sharedSecret, exchangeHash)
  1418. # Get the host public key,
  1419. # the raw ECDH public key bytes and the signature
  1420. hostKey, pubKey, signature, packet = getNS(packet, 3)
  1421. # Easier to comment this out for now than to update all of the tests.
  1422. #fingerprint = nativeString(base64.b64encode(
  1423. # sha256(hostKey).digest()))
  1424. fingerprint = b':'.join(
  1425. [binascii.hexlify(ch) for ch in iterbytes(md5(hostKey).digest())])
  1426. d = self.verifyHostKey(hostKey, fingerprint)
  1427. d.addCallback(_continue_KEX_ECDH_REPLY, hostKey, pubKey, signature)
  1428. d.addErrback(
  1429. lambda unused: self.sendDisconnect(
  1430. DISCONNECT_HOST_KEY_NOT_VERIFIABLE, b'bad host key'))
  1431. return d
  1432. def _ssh_KEXDH_REPLY(self, packet):
  1433. """
  1434. Called to handle a reply to a non-group key exchange message
  1435. (KEXDH_INIT).
  1436. Like the handler for I{KEXDH_INIT}, this message type has an
  1437. overlapping value. This method is called from C{ssh_KEX_DH_GEX_GROUP}
  1438. if that method detects a non-group key exchange is in progress.
  1439. Payload::
  1440. string serverHostKey
  1441. integer f (server Diffie-Hellman public key)
  1442. string signature
  1443. We verify the host key by calling verifyHostKey, then continue in
  1444. _continueKEXDH_REPLY.
  1445. @type packet: L{bytes}
  1446. @param packet: The message data.
  1447. @return: A deferred firing when key exchange is complete.
  1448. """
  1449. pubKey, packet = getNS(packet)
  1450. f, packet = getMP(packet)
  1451. signature, packet = getNS(packet)
  1452. fingerprint = b':'.join([binascii.hexlify(ch) for ch in
  1453. iterbytes(md5(pubKey).digest())])
  1454. d = self.verifyHostKey(pubKey, fingerprint)
  1455. d.addCallback(self._continueKEXDH_REPLY, pubKey, f, signature)
  1456. d.addErrback(
  1457. lambda unused: self.sendDisconnect(
  1458. DISCONNECT_HOST_KEY_NOT_VERIFIABLE, b'bad host key'))
  1459. return d
  1460. def ssh_KEX_DH_GEX_GROUP(self, packet):
  1461. """
  1462. This handles different messages which share an integer value.
  1463. If the key exchange does not have a fixed prime/generator group,
  1464. we generate a Diffie-Hellman public key and send it in a
  1465. MSG_KEX_DH_GEX_INIT message.
  1466. Payload::
  1467. string g (group generator)
  1468. string p (group prime)
  1469. @type packet: L{bytes}
  1470. @param packet: The message data.
  1471. """
  1472. if _kex.isFixedGroup(self.kexAlg):
  1473. return self._ssh_KEXDH_REPLY(packet)
  1474. elif _kex.isEllipticCurve(self.kexAlg):
  1475. return self._ssh_KEX_ECDH_REPLY(packet)
  1476. else:
  1477. self.p, rest = getMP(packet)
  1478. self.g, rest = getMP(rest)
  1479. self._startEphemeralDH()
  1480. self.sendPacket(MSG_KEX_DH_GEX_INIT, self.dhSecretKeyPublicMP)
  1481. def _continueKEXDH_REPLY(self, ignored, pubKey, f, signature):
  1482. """
  1483. The host key has been verified, so we generate the keys.
  1484. @param ignored: Ignored.
  1485. @param pubKey: the public key blob for the server's public key.
  1486. @type pubKey: L{str}
  1487. @param f: the server's Diffie-Hellman public key.
  1488. @type f: L{long}
  1489. @param signature: the server's signature, verifying that it has the
  1490. correct private key.
  1491. @type signature: L{str}
  1492. """
  1493. serverKey = keys.Key.fromString(pubKey)
  1494. sharedSecret = self._finishEphemeralDH(f)
  1495. h = sha1()
  1496. h.update(NS(self.ourVersionString))
  1497. h.update(NS(self.otherVersionString))
  1498. h.update(NS(self.ourKexInitPayload))
  1499. h.update(NS(self.otherKexInitPayload))
  1500. h.update(NS(pubKey))
  1501. h.update(self.dhSecretKeyPublicMP)
  1502. h.update(MP(f))
  1503. h.update(sharedSecret)
  1504. exchangeHash = h.digest()
  1505. if not serverKey.verify(signature, exchangeHash):
  1506. self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
  1507. b'bad signature')
  1508. return
  1509. self._keySetup(sharedSecret, exchangeHash)
  1510. def ssh_KEX_DH_GEX_REPLY(self, packet):
  1511. """
  1512. Called when we receive a MSG_KEX_DH_GEX_REPLY message. Payload::
  1513. string server host key
  1514. integer f (server DH public key)
  1515. We verify the host key by calling verifyHostKey, then continue in
  1516. _continueGEX_REPLY.
  1517. @type packet: L{bytes}
  1518. @param packet: The message data.
  1519. @return: A deferred firing once key exchange is complete.
  1520. """
  1521. pubKey, packet = getNS(packet)
  1522. f, packet = getMP(packet)
  1523. signature, packet = getNS(packet)
  1524. fingerprint = b':'.join(
  1525. [binascii.hexlify(c) for c in iterbytes(md5(pubKey).digest())])
  1526. d = self.verifyHostKey(pubKey, fingerprint)
  1527. d.addCallback(self._continueGEX_REPLY, pubKey, f, signature)
  1528. d.addErrback(
  1529. lambda unused: self.sendDisconnect(
  1530. DISCONNECT_HOST_KEY_NOT_VERIFIABLE, b'bad host key'))
  1531. return d
  1532. def _continueGEX_REPLY(self, ignored, pubKey, f, signature):
  1533. """
  1534. The host key has been verified, so we generate the keys.
  1535. @param ignored: Ignored.
  1536. @param pubKey: the public key blob for the server's public key.
  1537. @type pubKey: L{str}
  1538. @param f: the server's Diffie-Hellman public key.
  1539. @type f: L{long}
  1540. @param signature: the server's signature, verifying that it has the
  1541. correct private key.
  1542. @type signature: L{str}
  1543. """
  1544. serverKey = keys.Key.fromString(pubKey)
  1545. sharedSecret = self._finishEphemeralDH(f)
  1546. h = _kex.getHashProcessor(self.kexAlg)()
  1547. h.update(NS(self.ourVersionString))
  1548. h.update(NS(self.otherVersionString))
  1549. h.update(NS(self.ourKexInitPayload))
  1550. h.update(NS(self.otherKexInitPayload))
  1551. h.update(NS(pubKey))
  1552. h.update(struct.pack(
  1553. '!LLL',
  1554. self._dhMinimalGroupSize,
  1555. self._dhPreferredGroupSize,
  1556. self._dhMaximalGroupSize,
  1557. ))
  1558. h.update(MP(self.p))
  1559. h.update(MP(self.g))
  1560. h.update(self.dhSecretKeyPublicMP)
  1561. h.update(MP(f))
  1562. h.update(sharedSecret)
  1563. exchangeHash = h.digest()
  1564. if not serverKey.verify(signature, exchangeHash):
  1565. self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
  1566. b'bad signature')
  1567. return
  1568. self._keySetup(sharedSecret, exchangeHash)
  1569. def _keySetup(self, sharedSecret, exchangeHash):
  1570. """
  1571. See SSHTransportBase._keySetup().
  1572. """
  1573. SSHTransportBase._keySetup(self, sharedSecret, exchangeHash)
  1574. if self._gotNewKeys:
  1575. self.ssh_NEWKEYS(b'')
  1576. def ssh_NEWKEYS(self, packet):
  1577. """
  1578. Called when we receive a MSG_NEWKEYS message. No payload.
  1579. If we've finished setting up our own keys, start using them.
  1580. Otherwise, remember that we've received this message.
  1581. @type packet: L{bytes}
  1582. @param packet: The message data.
  1583. """
  1584. if packet != b'':
  1585. self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
  1586. b"NEWKEYS takes no data")
  1587. return
  1588. if not self.nextEncryptions.encBlockSize:
  1589. self._gotNewKeys = 1
  1590. return
  1591. self._newKeys()
  1592. self.connectionSecure()
  1593. def ssh_SERVICE_ACCEPT(self, packet):
  1594. """
  1595. Called when we receive a MSG_SERVICE_ACCEPT message. Payload::
  1596. string service name
  1597. Start the service we requested.
  1598. @type packet: L{bytes}
  1599. @param packet: The message data.
  1600. """
  1601. if packet == b'':
  1602. log.msg('got SERVICE_ACCEPT without payload')
  1603. else:
  1604. name = getNS(packet)[0]
  1605. if name != self.instance.name:
  1606. self.sendDisconnect(
  1607. DISCONNECT_PROTOCOL_ERROR,
  1608. b"received accept for service we did not request")
  1609. self.setService(self.instance)
  1610. def requestService(self, instance):
  1611. """
  1612. Request that a service be run over this transport.
  1613. @type instance: subclass of L{twisted.conch.ssh.service.SSHService}
  1614. @param instance: The service to run.
  1615. """
  1616. self.sendPacket(MSG_SERVICE_REQUEST, NS(instance.name))
  1617. self.instance = instance
  1618. # Client methods
  1619. def verifyHostKey(self, hostKey, fingerprint):
  1620. """
  1621. Returns a Deferred that gets a callback if it is a valid key, or
  1622. an errback if not.
  1623. @type hostKey: L{bytes}
  1624. @param hostKey: The host key to verify.
  1625. @type fingerprint: L{bytes}
  1626. @param fingerprint: The fingerprint of the key.
  1627. @return: A deferred firing with C{True} if the key is valid.
  1628. """
  1629. return defer.fail(NotImplementedError())
  1630. def connectionSecure(self):
  1631. """
  1632. Called when the encryption has been set up. Generally,
  1633. requestService() is called to run another service over the transport.
  1634. """
  1635. raise NotImplementedError()
  1636. class _NullEncryptionContext(object):
  1637. """
  1638. An encryption context that does not actually encrypt anything.
  1639. """
  1640. def update(self, data):
  1641. """
  1642. 'Encrypt' new data by doing nothing.
  1643. @type data: L{bytes}
  1644. @param data: The data to 'encrypt'.
  1645. @rtype: L{bytes}
  1646. @return: The 'encrypted' data.
  1647. """
  1648. return data
  1649. class _DummyAlgorithm(object):
  1650. """
  1651. An encryption algorithm that does not actually encrypt anything.
  1652. """
  1653. block_size = 64
  1654. class _DummyCipher(object):
  1655. """
  1656. A cipher for the none encryption method.
  1657. @ivar block_size: the block size of the encryption. In the case of the
  1658. none cipher, this is 8 bytes.
  1659. """
  1660. algorithm = _DummyAlgorithm()
  1661. def encryptor(self):
  1662. """
  1663. Construct a noop encryptor.
  1664. @return: The encryptor.
  1665. """
  1666. return _NullEncryptionContext()
  1667. def decryptor(self):
  1668. """
  1669. Construct a noop decryptor.
  1670. @return: The decryptor.
  1671. """
  1672. return _NullEncryptionContext()
  1673. DH_GENERATOR, DH_PRIME = _kex.getDHGeneratorAndPrime(
  1674. b'diffie-hellman-group14-sha1')
  1675. MSG_DISCONNECT = 1
  1676. MSG_IGNORE = 2
  1677. MSG_UNIMPLEMENTED = 3
  1678. MSG_DEBUG = 4
  1679. MSG_SERVICE_REQUEST = 5
  1680. MSG_SERVICE_ACCEPT = 6
  1681. MSG_KEXINIT = 20
  1682. MSG_NEWKEYS = 21
  1683. MSG_KEXDH_INIT = 30
  1684. MSG_KEXDH_REPLY = 31
  1685. MSG_KEX_DH_GEX_REQUEST_OLD = 30
  1686. MSG_KEX_DH_GEX_REQUEST = 34
  1687. MSG_KEX_DH_GEX_GROUP = 31
  1688. MSG_KEX_DH_GEX_INIT = 32
  1689. MSG_KEX_DH_GEX_REPLY = 33
  1690. DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT = 1
  1691. DISCONNECT_PROTOCOL_ERROR = 2
  1692. DISCONNECT_KEY_EXCHANGE_FAILED = 3
  1693. DISCONNECT_RESERVED = 4
  1694. DISCONNECT_MAC_ERROR = 5
  1695. DISCONNECT_COMPRESSION_ERROR = 6
  1696. DISCONNECT_SERVICE_NOT_AVAILABLE = 7
  1697. DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED = 8
  1698. DISCONNECT_HOST_KEY_NOT_VERIFIABLE = 9
  1699. DISCONNECT_CONNECTION_LOST = 10
  1700. DISCONNECT_BY_APPLICATION = 11
  1701. DISCONNECT_TOO_MANY_CONNECTIONS = 12
  1702. DISCONNECT_AUTH_CANCELLED_BY_USER = 13
  1703. DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE = 14
  1704. DISCONNECT_ILLEGAL_USER_NAME = 15
  1705. messages = {}
  1706. for name, value in list(globals().items()):
  1707. # Avoid legacy messages which overlap with never ones
  1708. if name.startswith('MSG_') and not name.startswith('MSG_KEXDH_'):
  1709. messages[value] = name
  1710. # Check for regressions (#5352)
  1711. if 'MSG_KEXDH_INIT' in messages or 'MSG_KEXDH_REPLY' in messages:
  1712. raise RuntimeError(
  1713. "legacy SSH mnemonics should not end up in messages dict")