ecdsakey.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
  2. #
  3. # This file is part of paramiko.
  4. #
  5. # Paramiko is free software; you can redistribute it and/or modify it under the
  6. # terms of the GNU Lesser General Public License as published by the Free
  7. # Software Foundation; either version 2.1 of the License, or (at your option)
  8. # any later version.
  9. #
  10. # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
  11. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  13. # details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
  17. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. """
  19. ECDSA keys
  20. """
  21. from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
  22. from cryptography.hazmat.backends import default_backend
  23. from cryptography.hazmat.primitives import hashes, serialization
  24. from cryptography.hazmat.primitives.asymmetric import ec
  25. from cryptography.hazmat.primitives.asymmetric.utils import (
  26. decode_dss_signature,
  27. encode_dss_signature,
  28. )
  29. from paramiko.common import four_byte
  30. from paramiko.message import Message
  31. from paramiko.pkey import PKey
  32. from paramiko.ssh_exception import SSHException
  33. from paramiko.util import deflate_long
  34. class _ECDSACurve(object):
  35. """
  36. Represents a specific ECDSA Curve (nistp256, nistp384, etc).
  37. Handles the generation of the key format identifier and the selection of
  38. the proper hash function. Also grabs the proper curve from the 'ecdsa'
  39. package.
  40. """
  41. def __init__(self, curve_class, nist_name):
  42. self.nist_name = nist_name
  43. self.key_length = curve_class.key_size
  44. # Defined in RFC 5656 6.2
  45. self.key_format_identifier = "ecdsa-sha2-" + self.nist_name
  46. # Defined in RFC 5656 6.2.1
  47. if self.key_length <= 256:
  48. self.hash_object = hashes.SHA256
  49. elif self.key_length <= 384:
  50. self.hash_object = hashes.SHA384
  51. else:
  52. self.hash_object = hashes.SHA512
  53. self.curve_class = curve_class
  54. class _ECDSACurveSet(object):
  55. """
  56. A collection to hold the ECDSA curves. Allows querying by oid and by key
  57. format identifier. The two ways in which ECDSAKey needs to be able to look
  58. up curves.
  59. """
  60. def __init__(self, ecdsa_curves):
  61. self.ecdsa_curves = ecdsa_curves
  62. def get_key_format_identifier_list(self):
  63. return [curve.key_format_identifier for curve in self.ecdsa_curves]
  64. def get_by_curve_class(self, curve_class):
  65. for curve in self.ecdsa_curves:
  66. if curve.curve_class == curve_class:
  67. return curve
  68. def get_by_key_format_identifier(self, key_format_identifier):
  69. for curve in self.ecdsa_curves:
  70. if curve.key_format_identifier == key_format_identifier:
  71. return curve
  72. def get_by_key_length(self, key_length):
  73. for curve in self.ecdsa_curves:
  74. if curve.key_length == key_length:
  75. return curve
  76. class ECDSAKey(PKey):
  77. """
  78. Representation of an ECDSA key which can be used to sign and verify SSH2
  79. data.
  80. """
  81. _ECDSA_CURVES = _ECDSACurveSet(
  82. [
  83. _ECDSACurve(ec.SECP256R1, "nistp256"),
  84. _ECDSACurve(ec.SECP384R1, "nistp384"),
  85. _ECDSACurve(ec.SECP521R1, "nistp521"),
  86. ]
  87. )
  88. def __init__(
  89. self,
  90. msg=None,
  91. data=None,
  92. filename=None,
  93. password=None,
  94. vals=None,
  95. file_obj=None,
  96. validate_point=True,
  97. ):
  98. self.verifying_key = None
  99. self.signing_key = None
  100. self.public_blob = None
  101. if file_obj is not None:
  102. self._from_private_key(file_obj, password)
  103. return
  104. if filename is not None:
  105. self._from_private_key_file(filename, password)
  106. return
  107. if (msg is None) and (data is not None):
  108. msg = Message(data)
  109. if vals is not None:
  110. self.signing_key, self.verifying_key = vals
  111. c_class = self.signing_key.curve.__class__
  112. self.ecdsa_curve = self._ECDSA_CURVES.get_by_curve_class(c_class)
  113. else:
  114. # Must set ecdsa_curve first; subroutines called herein may need to
  115. # spit out our get_name(), which relies on this.
  116. key_type = msg.get_text()
  117. # But this also means we need to hand it a real key/curve
  118. # identifier, so strip out any cert business. (NOTE: could push
  119. # that into _ECDSACurveSet.get_by_key_format_identifier(), but it
  120. # feels more correct to do it here?)
  121. suffix = "-cert-v01@openssh.com"
  122. if key_type.endswith(suffix):
  123. key_type = key_type[: -len(suffix)]
  124. self.ecdsa_curve = self._ECDSA_CURVES.get_by_key_format_identifier(
  125. key_type
  126. )
  127. key_types = self._ECDSA_CURVES.get_key_format_identifier_list()
  128. cert_types = [
  129. "{}-cert-v01@openssh.com".format(x) for x in key_types
  130. ]
  131. self._check_type_and_load_cert(
  132. msg=msg, key_type=key_types, cert_type=cert_types
  133. )
  134. curvename = msg.get_text()
  135. if curvename != self.ecdsa_curve.nist_name:
  136. raise SSHException(
  137. "Can't handle curve of type {}".format(curvename)
  138. )
  139. pointinfo = msg.get_binary()
  140. try:
  141. key = ec.EllipticCurvePublicKey.from_encoded_point(
  142. self.ecdsa_curve.curve_class(), pointinfo
  143. )
  144. self.verifying_key = key
  145. except ValueError:
  146. raise SSHException("Invalid public key")
  147. @classmethod
  148. def supported_key_format_identifiers(cls):
  149. return cls._ECDSA_CURVES.get_key_format_identifier_list()
  150. def asbytes(self):
  151. key = self.verifying_key
  152. m = Message()
  153. m.add_string(self.ecdsa_curve.key_format_identifier)
  154. m.add_string(self.ecdsa_curve.nist_name)
  155. numbers = key.public_numbers()
  156. key_size_bytes = (key.curve.key_size + 7) // 8
  157. x_bytes = deflate_long(numbers.x, add_sign_padding=False)
  158. x_bytes = b"\x00" * (key_size_bytes - len(x_bytes)) + x_bytes
  159. y_bytes = deflate_long(numbers.y, add_sign_padding=False)
  160. y_bytes = b"\x00" * (key_size_bytes - len(y_bytes)) + y_bytes
  161. point_str = four_byte + x_bytes + y_bytes
  162. m.add_string(point_str)
  163. return m.asbytes()
  164. def __str__(self):
  165. return self.asbytes()
  166. @property
  167. def _fields(self):
  168. return (
  169. self.get_name(),
  170. self.verifying_key.public_numbers().x,
  171. self.verifying_key.public_numbers().y,
  172. )
  173. def get_name(self):
  174. return self.ecdsa_curve.key_format_identifier
  175. def get_bits(self):
  176. return self.ecdsa_curve.key_length
  177. def can_sign(self):
  178. return self.signing_key is not None
  179. def sign_ssh_data(self, data, algorithm=None):
  180. ecdsa = ec.ECDSA(self.ecdsa_curve.hash_object())
  181. sig = self.signing_key.sign(data, ecdsa)
  182. r, s = decode_dss_signature(sig)
  183. m = Message()
  184. m.add_string(self.ecdsa_curve.key_format_identifier)
  185. m.add_string(self._sigencode(r, s))
  186. return m
  187. def verify_ssh_sig(self, data, msg):
  188. if msg.get_text() != self.ecdsa_curve.key_format_identifier:
  189. return False
  190. sig = msg.get_binary()
  191. sigR, sigS = self._sigdecode(sig)
  192. signature = encode_dss_signature(sigR, sigS)
  193. try:
  194. self.verifying_key.verify(
  195. signature, data, ec.ECDSA(self.ecdsa_curve.hash_object())
  196. )
  197. except InvalidSignature:
  198. return False
  199. else:
  200. return True
  201. def write_private_key_file(self, filename, password=None):
  202. self._write_private_key_file(
  203. filename,
  204. self.signing_key,
  205. serialization.PrivateFormat.TraditionalOpenSSL,
  206. password=password,
  207. )
  208. def write_private_key(self, file_obj, password=None):
  209. self._write_private_key(
  210. file_obj,
  211. self.signing_key,
  212. serialization.PrivateFormat.TraditionalOpenSSL,
  213. password=password,
  214. )
  215. @classmethod
  216. def generate(cls, curve=ec.SECP256R1(), progress_func=None, bits=None):
  217. """
  218. Generate a new private ECDSA key. This factory function can be used to
  219. generate a new host key or authentication key.
  220. :param progress_func: Not used for this type of key.
  221. :returns: A new private key (`.ECDSAKey`) object
  222. """
  223. if bits is not None:
  224. curve = cls._ECDSA_CURVES.get_by_key_length(bits)
  225. if curve is None:
  226. raise ValueError("Unsupported key length: {:d}".format(bits))
  227. curve = curve.curve_class()
  228. private_key = ec.generate_private_key(curve, backend=default_backend())
  229. return ECDSAKey(vals=(private_key, private_key.public_key()))
  230. # ...internals...
  231. def _from_private_key_file(self, filename, password):
  232. data = self._read_private_key_file("EC", filename, password)
  233. self._decode_key(data)
  234. def _from_private_key(self, file_obj, password):
  235. data = self._read_private_key("EC", file_obj, password)
  236. self._decode_key(data)
  237. def _decode_key(self, data):
  238. pkformat, data = data
  239. if pkformat == self._PRIVATE_KEY_FORMAT_ORIGINAL:
  240. try:
  241. key = serialization.load_der_private_key(
  242. data, password=None, backend=default_backend()
  243. )
  244. except (
  245. ValueError,
  246. AssertionError,
  247. TypeError,
  248. UnsupportedAlgorithm,
  249. ) as e:
  250. raise SSHException(str(e))
  251. elif pkformat == self._PRIVATE_KEY_FORMAT_OPENSSH:
  252. try:
  253. msg = Message(data)
  254. curve_name = msg.get_text()
  255. verkey = msg.get_binary() # noqa: F841
  256. sigkey = msg.get_mpint()
  257. name = "ecdsa-sha2-" + curve_name
  258. curve = self._ECDSA_CURVES.get_by_key_format_identifier(name)
  259. if not curve:
  260. raise SSHException("Invalid key curve identifier")
  261. key = ec.derive_private_key(
  262. sigkey, curve.curve_class(), default_backend()
  263. )
  264. except Exception as e:
  265. # PKey._read_private_key_openssh() should check or return
  266. # keytype - parsing could fail for any reason due to wrong type
  267. raise SSHException(str(e))
  268. else:
  269. self._got_bad_key_format_id(pkformat)
  270. self.signing_key = key
  271. self.verifying_key = key.public_key()
  272. curve_class = key.curve.__class__
  273. self.ecdsa_curve = self._ECDSA_CURVES.get_by_curve_class(curve_class)
  274. def _sigencode(self, r, s):
  275. msg = Message()
  276. msg.add_mpint(r)
  277. msg.add_mpint(s)
  278. return msg.asbytes()
  279. def _sigdecode(self, sig):
  280. msg = Message(sig)
  281. r = msg.get_mpint()
  282. s = msg.get_mpint()
  283. return r, s