_kex.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. # -*- test-case-name: twisted.conch.test.test_transport -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. SSH key exchange handling.
  6. """
  7. from __future__ import absolute_import, division
  8. from hashlib import sha1, sha256, sha384, sha512
  9. from zope.interface import Attribute, implementer, Interface
  10. from twisted.conch import error
  11. from twisted.python.compat import long
  12. class _IKexAlgorithm(Interface):
  13. """
  14. An L{_IKexAlgorithm} describes a key exchange algorithm.
  15. """
  16. preference = Attribute(
  17. "An L{int} giving the preference of the algorithm when negotiating "
  18. "key exchange. Algorithms with lower precedence values are more "
  19. "preferred.")
  20. hashProcessor = Attribute(
  21. "A callable hash algorithm constructor (e.g. C{hashlib.sha256}) "
  22. "suitable for use with this key exchange algorithm.")
  23. class _IFixedGroupKexAlgorithm(_IKexAlgorithm):
  24. """
  25. An L{_IFixedGroupKexAlgorithm} describes a key exchange algorithm with a
  26. fixed prime / generator group.
  27. """
  28. prime = Attribute(
  29. "A L{long} giving the prime number used in Diffie-Hellman key "
  30. "exchange, or L{None} if not applicable.")
  31. generator = Attribute(
  32. "A L{long} giving the generator number used in Diffie-Hellman key "
  33. "exchange, or L{None} if not applicable. (This is not related to "
  34. "Python generator functions.)")
  35. class _IEllipticCurveExchangeKexAlgorithm(_IKexAlgorithm):
  36. """
  37. An L{_IEllipticCurveExchangeKexAlgorithm} describes a key exchange algorithm
  38. that uses an elliptic curve exchange between the client and server.
  39. """
  40. class _IGroupExchangeKexAlgorithm(_IKexAlgorithm):
  41. """
  42. An L{_IGroupExchangeKexAlgorithm} describes a key exchange algorithm
  43. that uses group exchange between the client and server.
  44. A prime / generator group should be chosen at run time based on the
  45. requested size. See RFC 4419.
  46. """
  47. @implementer(_IEllipticCurveExchangeKexAlgorithm)
  48. class _ECDH256(object):
  49. """
  50. Elliptic Curve Key Exchange with SHA-256 as HASH. Defined in
  51. RFC 5656.
  52. """
  53. preference = 1
  54. hashProcessor = sha256
  55. @implementer(_IEllipticCurveExchangeKexAlgorithm)
  56. class _ECDH384(object):
  57. """
  58. Elliptic Curve Key Exchange with SHA-384 as HASH. Defined in
  59. RFC 5656.
  60. """
  61. preference = 2
  62. hashProcessor = sha384
  63. @implementer(_IEllipticCurveExchangeKexAlgorithm)
  64. class _ECDH512(object):
  65. """
  66. Elliptic Curve Key Exchange with SHA-512 as HASH. Defined in
  67. RFC 5656.
  68. """
  69. preference = 3
  70. hashProcessor = sha512
  71. @implementer(_IGroupExchangeKexAlgorithm)
  72. class _DHGroupExchangeSHA256(object):
  73. """
  74. Diffie-Hellman Group and Key Exchange with SHA-256 as HASH. Defined in
  75. RFC 4419, 4.2.
  76. """
  77. preference = 4
  78. hashProcessor = sha256
  79. @implementer(_IGroupExchangeKexAlgorithm)
  80. class _DHGroupExchangeSHA1(object):
  81. """
  82. Diffie-Hellman Group and Key Exchange with SHA-1 as HASH. Defined in
  83. RFC 4419, 4.1.
  84. """
  85. preference = 5
  86. hashProcessor = sha1
  87. @implementer(_IFixedGroupKexAlgorithm)
  88. class _DHGroup14SHA1(object):
  89. """
  90. Diffie-Hellman key exchange with SHA-1 as HASH and Oakley Group 14
  91. (2048-bit MODP Group). Defined in RFC 4253, 8.2.
  92. """
  93. preference = 7
  94. hashProcessor = sha1
  95. # Diffie-Hellman primes from Oakley Group 14 (RFC 3526, 3).
  96. prime = long('32317006071311007300338913926423828248817941241140239112842'
  97. '00975140074170663435422261968941736356934711790173790970419175460587'
  98. '32091950288537589861856221532121754125149017745202702357960782362488'
  99. '84246189477587641105928646099411723245426622522193230540919037680524'
  100. '23551912567971587011700105805587765103886184728025797605490356973256'
  101. '15261670813393617995413364765591603683178967290731783845896806396719'
  102. '00977202194168647225871031411336429319536193471636533209717077448227'
  103. '98858856536920864529663607725026895550592836275112117409697299806841'
  104. '05543595848665832916421362182310789909994486524682624169720359118525'
  105. '07045361090559')
  106. generator = 2
  107. # Which ECDH hash function to use is dependent on the size.
  108. _kexAlgorithms = {
  109. b"diffie-hellman-group-exchange-sha256": _DHGroupExchangeSHA256(),
  110. b"diffie-hellman-group-exchange-sha1": _DHGroupExchangeSHA1(),
  111. b"diffie-hellman-group14-sha1": _DHGroup14SHA1(),
  112. b"ecdh-sha2-nistp256": _ECDH256(),
  113. b"ecdh-sha2-nistp384": _ECDH384(),
  114. b"ecdh-sha2-nistp521": _ECDH512(),
  115. }
  116. def getKex(kexAlgorithm):
  117. """
  118. Get a description of a named key exchange algorithm.
  119. @param kexAlgorithm: The key exchange algorithm name.
  120. @type kexAlgorithm: L{bytes}
  121. @return: A description of the key exchange algorithm named by
  122. C{kexAlgorithm}.
  123. @rtype: L{_IKexAlgorithm}
  124. @raises ConchError: if the key exchange algorithm is not found.
  125. """
  126. if kexAlgorithm not in _kexAlgorithms:
  127. raise error.ConchError(
  128. "Unsupported key exchange algorithm: %s" % (kexAlgorithm,))
  129. return _kexAlgorithms[kexAlgorithm]
  130. def isEllipticCurve(kexAlgorithm):
  131. """
  132. Returns C{True} if C{kexAlgorithm} is an elliptic curve.
  133. @param kexAlgorithm: The key exchange algorithm name.
  134. @type kexAlgorithm: C{str}
  135. @return: C{True} if C{kexAlgorithm} is an elliptic curve,
  136. otherwise C{False}.
  137. @rtype: C{bool}
  138. """
  139. return _IEllipticCurveExchangeKexAlgorithm.providedBy(getKex(kexAlgorithm))
  140. def isFixedGroup(kexAlgorithm):
  141. """
  142. Returns C{True} if C{kexAlgorithm} has a fixed prime / generator group.
  143. @param kexAlgorithm: The key exchange algorithm name.
  144. @type kexAlgorithm: L{bytes}
  145. @return: C{True} if C{kexAlgorithm} has a fixed prime / generator group,
  146. otherwise C{False}.
  147. @rtype: L{bool}
  148. """
  149. return _IFixedGroupKexAlgorithm.providedBy(getKex(kexAlgorithm))
  150. def getHashProcessor(kexAlgorithm):
  151. """
  152. Get the hash algorithm callable to use in key exchange.
  153. @param kexAlgorithm: The key exchange algorithm name.
  154. @type kexAlgorithm: L{bytes}
  155. @return: A callable hash algorithm constructor (e.g. C{hashlib.sha256}).
  156. @rtype: C{callable}
  157. """
  158. kex = getKex(kexAlgorithm)
  159. return kex.hashProcessor
  160. def getDHGeneratorAndPrime(kexAlgorithm):
  161. """
  162. Get the generator and the prime to use in key exchange.
  163. @param kexAlgorithm: The key exchange algorithm name.
  164. @type kexAlgorithm: L{bytes}
  165. @return: A L{tuple} containing L{long} generator and L{long} prime.
  166. @rtype: L{tuple}
  167. """
  168. kex = getKex(kexAlgorithm)
  169. return kex.generator, kex.prime
  170. def getSupportedKeyExchanges():
  171. """
  172. Get a list of supported key exchange algorithm names in order of
  173. preference.
  174. @return: A C{list} of supported key exchange algorithm names.
  175. @rtype: C{list} of L{bytes}
  176. """
  177. from cryptography.hazmat.backends import default_backend
  178. from cryptography.hazmat.primitives.asymmetric import ec
  179. from twisted.conch.ssh.keys import _curveTable
  180. backend = default_backend()
  181. kexAlgorithms = _kexAlgorithms.copy()
  182. for keyAlgorithm in list(kexAlgorithms):
  183. if keyAlgorithm.startswith(b"ecdh"):
  184. keyAlgorithmDsa = keyAlgorithm.replace(b"ecdh", b"ecdsa")
  185. supported = backend.elliptic_curve_exchange_algorithm_supported(
  186. ec.ECDH(), _curveTable[keyAlgorithmDsa])
  187. if not supported:
  188. kexAlgorithms.pop(keyAlgorithm)
  189. return sorted(
  190. kexAlgorithms,
  191. key = lambda kexAlgorithm: kexAlgorithms[kexAlgorithm].preference)